import { Button, Descriptions, Form, message, Modal, Radio, 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';
import './index.scss';

// 详情返回类型
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 dutyOptionList = [
  {
    label: '双方无责',
    value: 1,
  },
  {
    label: '发布者责任',
    value: 2,
  },
  {
    label: '飞手责任',
    value: 3,
  },
];

const DemandOrderDetail = () => {
  const navigate = useNavigate();
  const [controversyForm] = Form.useForm<{ duty: number; decisionContent: string }>();
  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 }) => {
      if (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) => !['700', '500'].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.map((v) => ({ title: v.title, description: v.description })));
            setCurrentStep(stepList.findIndex((v) => v.orderStatus === demandDetail.orderStatus));
          }
        },
      );
    });
  };
  // 提交争议
  const submitDispute = () => {
    Modal.confirm({
      title: '提示',
      content: '确认提交该判定结果？',
      onOk: () => {
        controversyForm.validateFields().then((values) => {
          OrderManageAPI.disputeOrder({
            requirementsInfoId: Number(searchParams.get('id')),
            ...values,
          }).then(({ code }) => {
            if (code === '200') {
              message.success('判定成功');
              getServiceOrderFormDetails(Number(searchParams.get('id')));
            }
          });
        });
      },
    });
  };

  // 返回
  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={
          demandDetail?.orderStatus === '700' ? (
            ''
          ) : (
            <Button danger type='primary' onClick={submitDispute}>
              确认判定
            </Button>
          )
        }
      >
        <Descriptions.Item labelStyle={{ color: '#000' }}>
          <div style={{ color: 'red' }}>
            1、发单方责任（扣除30%违约金，20%支付给接单方，信息推送）
            <br />
            2、接单方责任（扣除30%违约金，20%支付给发单方，信息推送）
            <br />
            3、双方无责（不扣违约金，信息推送）
          </div>
        </Descriptions.Item>
        <Descriptions.Item>
          <Form
            form={controversyForm}
            initialValues={{ duty: demandDetail?.orderStatus === '700' ? demandDetail?.duty : 1 }}
          >
            <Form.Item label='争议结果' name='duty'>
              {demandDetail?.orderStatus === '700' ? (
                <span>{dutyOptionList.find((v) => v.value === demandDetail.duty)?.label}</span>
              ) : (
                <Radio.Group options={dutyOptionList}></Radio.Group>
              )}
            </Form.Item>
            <Form.Item label='争议描述' name='decisionContent'>
              {demandDetail?.orderStatus === '700' ? (
                <div
                  dangerouslySetInnerHTML={{ __html: demandDetail.decisionContent || '' }}
                  className='detail-rich-text'
                ></div>
              ) : (
                <RichText richTextContent='' />
              )}
            </Form.Item>
          </Form>
        </Descriptions.Item>
      </Descriptions>
    </div>
  );
};
export default DemandOrderDetail;
