import { Button, Descriptions, Steps } from 'antd';
import { useNavigate } from 'react-router-dom';
import RichText from '~/components/richText';
import { useSearchParams } from 'react-router-dom';
import { OrderManageAPI } from '~/api';
import { useEffect, useState } from 'react';
import { InterDataType } from '~/api/interface';
import { serviceOrderFormDetailsType } from '~/api/interface/orderManageType';

// 详情返回类型
type detailType = InterDataType<serviceOrderFormDetailsType>;

const flowStatusKey = [
  {
    orderStatus: '550',
    key: 'amountUpdate',
  },
  {
    orderStatus: '100',
    key: 'releaseSuccess',
  },
  {
    orderStatus: '200',
    key: 'requirementsServiceDTO',
  },
  {
    orderStatus: '300',
    key: 'serviceArriveSceneDTO',
  },
  {
    orderStatus: '400',
    key: 'serviceFulfilATaskDTO',
  },
  {
    orderStatus: '500',
    key: 'serviceSettleAccountsDTO',
  },
  {
    orderStatus: '600',
    key: 'serviceEvaluateDTO',
  },
];

const DemandOrderDetail = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  // 需求订单详情
  const [demandDetail, setDemandDetail] = useState<detailType>();
  // 进度条
  const [steps, setSteps] = useState<{ title: string; description: string }[]>([]);
  // 当前进度
  const [currentStep, setCurrentStep] = useState<number>(0);

  //获取详情
  const getServiceOrderFormDetails = (requirementsInfoId: number) => {
    OrderManageAPI.getServiceOrderFormDetails({ requirementsInfoId }).then(({ result }) => {
      setDemandDetail(result);
    });
  };
  // 获取进度条
  const getFlowDictionaryList = (requirementsInfoId: number) => {
    OrderManageAPI.getFlowDictionary().then(({ result: flowDictionaryResult }) => {
      OrderManageAPI.getFlowDictionaryAndTime({ requirementsInfoId }).then(
        (flowDictionaryAndTimeRes: any) => {
          // 排序
          const flowDictionarySortResult = flowDictionaryResult.sort(
            (a, b) => Number(a.orderStatus) - Number(b.orderStatus),
          );
          if (demandDetail) {
            const flowDictionaryFilterResult = ['700'].includes(demandDetail.orderStatus)
              ? flowDictionarySortResult.filter((v) => v.orderStatus === demandDetail.orderStatus)
              : ['550'].includes(demandDetail.orderStatus)
              ? flowDictionarySortResult.filter(
                  (v) =>
                    v.orderStatus !== demandDetail.orderStatus && !['700'].includes(v.orderStatus),
                )
              : flowDictionarySortResult.filter((v) => !['700', '550'].includes(v.orderStatus));
            const stepList = flowDictionaryFilterResult
              .map((v) => {
                return {
                  ...v,
                  key: flowStatusKey.find((i) => i.orderStatus === v.orderStatus)?.key,
                };
              })
              .map((v) => {
                return {
                  title: demandDetail?.orderStatus > v.orderStatus ? v.doing : v.waiting,
                  orderStatus: v.orderStatus,
                  description: v.key
                    ? flowDictionaryAndTimeRes.result[v.key]?.createTime || ''
                    : '',
                };
              });
            setSteps(stepList);
            setCurrentStep(stepList.findIndex((v) => v.orderStatus === demandDetail.orderStatus));
          }
        },
      );
    });
  };

  // 返回
  const backRoute = () => {
    navigate(-1);
  };

  useEffect(() => {
    getServiceOrderFormDetails(Number(searchParams.get('id')));
  }, []);

  useEffect(() => {
    if (demandDetail) {
      getFlowDictionaryList(Number(searchParams.get('id')));
    }
  }, [demandDetail]);

  return (
    <div className='demand-order-detail'>
      <Descriptions
        title='订单进度'
        extra={
          <Button type='primary' onClick={backRoute}>
            返回
          </Button>
        }
      >
        <Descriptions.Item>
          <Steps current={currentStep} items={steps} />
        </Descriptions.Item>
      </Descriptions>
      <Descriptions title='订单信息' bordered style={{ marginTop: '10px' }}>
        <Descriptions.Item label='发单时间'>{demandDetail?.createTime}</Descriptions.Item>
        <Descriptions.Item label='订单类型'>{demandDetail?.serviceName}</Descriptions.Item>
        <Descriptions.Item label='订单编号'>{demandDetail?.publisherNumber}</Descriptions.Item>
        <Descriptions.Item label='订单金额'>
          {demandDetail?.orderAmount.toFixed(2).toLocaleString()}
        </Descriptions.Item>
        <Descriptions.Item label='任务时间'>
          {demandDetail?.taskStartTime}~{demandDetail?.taskEndTime}
        </Descriptions.Item>
        <Descriptions.Item label='任务地址'>{demandDetail?.taskAddress}</Descriptions.Item>
        <Descriptions.Item label='平台收益'>
          {demandDetail?.orderEarnings.toFixed(2).toLocaleString()}
        </Descriptions.Item>
      </Descriptions>
      <Descriptions title='发单方' bordered style={{ marginTop: '10px' }}>
        <Descriptions.Item label='冻结云享金'>
          {demandDetail?.cashAmount.toFixed(2).toLocaleString()}
        </Descriptions.Item>
        <Descriptions.Item label='冻结余额'>
          {demandDetail?.salaryAmount.toFixed(2).toLocaleString()}
        </Descriptions.Item>
        <Descriptions.Item label='冻结微信支付'>
          {demandDetail?.weChat.toFixed(2).toLocaleString()}
        </Descriptions.Item>
      </Descriptions>
      <Descriptions title='接单方' bordered style={{ marginTop: '10px' }}>
        <Descriptions.Item label='冻结云享金'>
          {demandDetail?.preemptCashAmount.toFixed(2).toLocaleString()}
        </Descriptions.Item>
        <Descriptions.Item label='冻结余额'>
          {demandDetail?.preemptSalaryAmount.toFixed(2).toLocaleString()}
        </Descriptions.Item>
        <Descriptions.Item label='冻结微信支付'>
          {demandDetail?.preemptWeChat.toFixed(2).toLocaleString()}
        </Descriptions.Item>
      </Descriptions>
      <Descriptions
        title='订单争议处理记录'
        style={{ marginTop: '10px' }}
        column={1}
        extra={
          <Button danger type='primary'>
            确认判定
          </Button>
        }
      >
        <Descriptions.Item label='判定结果' labelStyle={{ color: '#000' }}>
          <div style={{ color: 'red' }}>
            1、发单方责任（扣除30%违约金，20%支付给接单方，信息推送）
            <br />
            2、发单方责任（扣除30%违约金，20%支付给接单方，信息推送）
            <br />
            3、双方无责（不扣违约金，信息推送）
          </div>
        </Descriptions.Item>
        <Descriptions.Item>
          <RichText richTextContent='' />
        </Descriptions.Item>
      </Descriptions>
    </div>
  );
};
export default DemandOrderDetail;
