import { Button, Descriptions, Form, Image, 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 { Key, 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?.serviceOrderFormDetailsDTO?.orderStatus,
            )
              ? flowDictionarySortResult.filter(
                  (v) => v.orderStatus === demandDetail?.serviceOrderFormDetailsDTO?.orderStatus,
                )
              : ['550'].includes(demandDetail?.serviceOrderFormDetailsDTO?.orderStatus)
              ? flowDictionarySortResult.filter((v) => !['700', '500'].includes(v.orderStatus))
              : flowDictionarySortResult.filter((v) => !['700', '550'].includes(v.orderStatus));
            let stepList = flowDictionaryFilterResult
              .map((v) => {
                return {
                  ...v,
                  key: flowStatusKey.find((i) => i.orderStatus === v.orderStatus)?.key,
                };
              })
              .map((v) => {
                return {
                  title:
                    demandDetail?.serviceOrderFormDetailsDTO?.orderStatus > v.orderStatus
                      ? v.doing
                      : v.waiting,
                  orderStatus: v.orderStatus,
                  description: v.key
                    ? flowDictionaryAndTimeRes.result[v.key]?.createTime || ''
                    : '',
                };
              });
            // 如果状态大于200，即相当于需求方同意接单，则不显示拒绝的状态
            if (demandDetail?.serviceOrderFormDetailsDTO?.orderStatus !== '170') {
              stepList = stepList.filter((i) => !['170'].includes(i.orderStatus));
            }
            setSteps(stepList.map((v) => ({ title: v.title, description: v.description })));
            setCurrentStep(
              stepList.findIndex(
                (v) => v.orderStatus === demandDetail?.serviceOrderFormDetailsDTO?.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('判定成功').then();
              getServiceOrderFormDetails(Number(searchParams.get('id')));
            }
          });
        });
      },
    });
  };

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

  // 转化图片字段
  const transformImg = (img?: string) => {
    try {
      if (img) {
        return JSON.parse(img);
      } else {
        return [];
      }
    } catch (err) {
      return [];
    }
  };

  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?.serviceOrderFormDetailsDTO?.createTime}
        </Descriptions.Item>
        <Descriptions.Item label='订单类型'>
          {demandDetail?.serviceOrderFormDetailsDTO?.serviceName}
        </Descriptions.Item>
        <Descriptions.Item label='订单编号'>
          {demandDetail?.serviceOrderFormDetailsDTO?.publisherNumber}
        </Descriptions.Item>
        <Descriptions.Item label='订单金额'>
          {demandDetail?.serviceOrderFormDetailsDTO?.orderAmount.toFixed(2).toLocaleString()}
        </Descriptions.Item>
        <Descriptions.Item label='任务时间'>
          {demandDetail?.serviceOrderFormDetailsDTO?.taskStartTime}~
          {demandDetail?.serviceOrderFormDetailsDTO?.taskEndTime}
        </Descriptions.Item>
        <Descriptions.Item label='任务地址'>
          {demandDetail?.serviceOrderFormDetailsDTO?.taskAddress}
        </Descriptions.Item>
        <Descriptions.Item label='平台收益'>
          {demandDetail?.serviceOrderFormDetailsDTO?.orderEarnings.toFixed(2).toLocaleString()}
        </Descriptions.Item>
      </Descriptions>
      {demandDetail?.serviceArriveSceneDTO && (
        <>
          <Descriptions
            title='飞手抵达任务地点'
            bordered
            style={{ marginTop: '10px' }}
            contentStyle={{ width: 300 }}
          >
            <Descriptions.Item label='飞手位置'>
              {demandDetail?.serviceArriveSceneDTO?.sceneAddress}
            </Descriptions.Item>
            <Descriptions.Item label='飞手凭证'>
              {transformImg(demandDetail?.serviceArriveSceneDTO?.sceneUrl)?.map(
                (v: string, i: Key) => (
                  <Image key={i} src={v} alt='飞手凭证' style={{ width: '35px', height: '35px' }} />
                ),
              )}
            </Descriptions.Item>
            <Descriptions.Item label='完成时间'>
              {demandDetail?.serviceArriveSceneDTO?.updateTime}
            </Descriptions.Item>
          </Descriptions>
        </>
      )}
      {demandDetail?.serviceArriveSceneDTO && (
        <>
          <Descriptions
            title='飞手完成任务'
            bordered
            style={{ marginTop: '10px' }}
            contentStyle={{ width: 300 }}
          >
            <Descriptions.Item label='任务描述'>
              {demandDetail?.serviceFulfilATaskDTO?.taskDescribe
                ? demandDetail?.serviceFulfilATaskDTO?.taskDescribe
                : '无'}
            </Descriptions.Item>
            <Descriptions.Item label='飞手凭证'>
              {transformImg(demandDetail?.serviceFulfilATaskDTO?.taskUrl)?.map(
                (v: string, i: Key) => (
                  <Image key={i} src={v} alt='飞手凭证' style={{ width: '35px', height: '35px' }} />
                ),
              )}
            </Descriptions.Item>
            <Descriptions.Item label='抵达时间'>
              {demandDetail?.serviceArriveSceneDTO?.updateTime}
            </Descriptions.Item>
          </Descriptions>
        </>
      )}

      <Descriptions title='发单方' bordered style={{ marginTop: '10px' }}>
        <Descriptions.Item label='冻结云享金'>
          {demandDetail?.serviceOrderFormDetailsDTO?.cashAmount.toFixed(2).toLocaleString()}
        </Descriptions.Item>
        <Descriptions.Item label='冻结余额'>
          {demandDetail?.serviceOrderFormDetailsDTO?.salaryAmount.toFixed(2).toLocaleString()}
        </Descriptions.Item>
        <Descriptions.Item label='冻结微信支付'>
          {demandDetail?.serviceOrderFormDetailsDTO?.weChat.toFixed(2).toLocaleString()}
        </Descriptions.Item>
      </Descriptions>
      <Descriptions title='接单方' bordered style={{ marginTop: '10px' }}>
        <Descriptions.Item label='冻结云享金'>
          {demandDetail?.serviceOrderFormDetailsDTO?.preemptCashAmount.toFixed(2).toLocaleString()}
        </Descriptions.Item>
        <Descriptions.Item label='冻结余额'>
          {demandDetail?.serviceOrderFormDetailsDTO?.preemptSalaryAmount
            .toFixed(2)
            .toLocaleString()}
        </Descriptions.Item>
        <Descriptions.Item label='冻结微信支付'>
          {demandDetail?.serviceOrderFormDetailsDTO?.preemptWeChat.toFixed(2).toLocaleString()}
        </Descriptions.Item>
      </Descriptions>
      <Descriptions
        title='订单争议处理记录'
        style={{ marginTop: '10px' }}
        column={1}
        extra={
          demandDetail?.serviceOrderFormDetailsDTO?.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?.serviceOrderFormDetailsDTO?.orderStatus === '700'
                  ? demandDetail?.serviceOrderFormDetailsDTO?.duty
                  : 1,
            }}
          >
            <Form.Item label='争议结果' name='duty'>
              {demandDetail?.serviceOrderFormDetailsDTO?.orderStatus === '700' ? (
                <span>
                  {
                    dutyOptionList.find(
                      (v) => v.value === demandDetail?.serviceOrderFormDetailsDTO?.duty,
                    )?.label
                  }
                </span>
              ) : (
                <Radio.Group options={dutyOptionList}></Radio.Group>
              )}
            </Form.Item>
            <Form.Item label='争议描述' name='decisionContent'>
              {demandDetail?.serviceOrderFormDetailsDTO?.orderStatus === '700' ? (
                <div
                  dangerouslySetInnerHTML={{
                    __html: demandDetail?.serviceOrderFormDetailsDTO?.decisionContent || '',
                  }}
                  className='detail-rich-text'
                ></div>
              ) : (
                <RichText richTextContent='' />
              )}
            </Form.Item>
          </Form>
        </Descriptions.Item>
      </Descriptions>
    </div>
  );
};
export default DemandOrderDetail;
