import {
  getCraftRecordList,
  getMaintainRecordList,
  getReagentOrderDetail,
  getRepairRecordList,
  getWorkOrderFlow,
} from '@/services/TaskManage';
import { CloseCircleFilled } from '@ant-design/icons';
import { connect, useLocation, useParams, useRequest } from '@umijs/max';
import { Button, Col, Divider, Row, Spin, Steps } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useMemo, useState } from 'react';
import ReactZmage from 'react-zmage';
import SubTitle from '../components/SubTitle';
import { OrderStatus, OrderType } from '../constent';
import styles from './WorkOrderModal.less';

import { UnityAction } from '@/utils/utils';

const WorkOrderModal = (props) => {
  const { userList, dispatch } = props;

  const { projectID } = useParams();
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const order_id = Number(queryParams.get('order_id'));
  const order_type = Number(queryParams.get('order_type'));
  const mandate_class = Number(queryParams.get('mandate_class'));

  const [orderInfo, setOrderInfo] = useState({});
  const [additionalInfo, setAdditionalInfo] = useState({});
  const [stepInfo, setStepInfo] = useState([]);

  const { run: getCraftDetail, loading: craftLoading } = useRequest(
    getCraftRecordList,
    {
      manual: true,
      formatResult: (result) => {
        if (result?.data?.list) {
          const temp = result.data.list[0];
          const tempDetail = {
            ...temp,
            CreateTime: dayjs(temp.start_time).format('YYYY-MM-DD HH:mm'),
            PlanTime: dayjs(temp.plan_end_time).format('YYYY-MM-DD HH:mm'),
            RepairTime:
              (temp.actual_end_time &&
                dayjs(temp.actual_end_time).format('YYYY-MM-DD HH:mm')) ||
              '-',
            Reason:
              mandate_class !== 2 ? temp.detail : renderReason(temp.detail),
            Repairman:
              userList.find((item) => item.ID === temp.checker_id) || '-',
            DispatchMan:
              userList.find((item) => item.ID === temp.operator_id) || '-',
            OrderStatus:
              OrderStatus.find((item) => item.value === temp.status) || '-',
            MandateImages:
              temp?.mandate_images?.length > 0
                ? temp.mandate_images.map((item) => {
                    console.log(item);
                    if (item.type === 2) {
                      return {
                        src: item.val,
                      };
                    }
                    return {
                      src: `data:image/png;base64,${item.val}`,
                    };
                  })
                : [],
          };
          setOrderInfo(tempDetail);
          // 根据不同的工单类型查询工单操作详情
        }
      },
    },
  );

  const { run: getRepairDetail, loading: repairLoading } = useRequest(
    getRepairRecordList,
    {
      manual: true,
      formatResult: (result) => {
        if (result?.data?.list) {
          const temp = result.data.list[0];

          const tempDetail = {
            ...temp,
            CreateTime: dayjs(temp.CreateTime).format('YYYY-MM-DD HH:mm'),
            PlanTime: dayjs(temp.PlanTime).format('YYYY-MM-DD HH:mm'),
            RepairTime:
              (temp.RepairTime &&
                dayjs(temp.RepairTime).format('YYYY-MM-DD HH:mm')) ||
              '-',
            Reason: temp.Reason,
            Repairman:
              userList.find((item) => item.ID === temp.Repairman) || '-',
            DispatchMan:
              userList.find((item) => item.ID === temp.operator_id) || '-',
            OrderStatus:
              OrderStatus.find(
                (item) => item.value === temp.AcceptanceStatus,
              ) || '-',
            MandateImages:
              temp?.mandate_images?.length > 0
                ? temp.mandate_images.map((item) => {
                    if (item.type === 2) {
                      return {
                        src: item.val,
                      };
                    }
                    return {
                      src: `data:image/png;base64,${item.val}`,
                    };
                  })
                : [],
          };
          setOrderInfo(tempDetail);
        }
      },
    },
  );

  const { run: getMaintainDetail, loading: maintainLoading } = useRequest(
    getMaintainRecordList,
    {
      manual: true,
      formatResult: (result) => {
        if (result?.data?.list) {
          const temp = result.data.list[0];
          const tempDetail = {
            ...temp,
            CreateTime: dayjs(temp.CreateTime).format('YYYY-MM-DD HH:mm'),
            PlanTime: dayjs(temp.PlanTime).format('YYYY-MM-DD HH:mm'),
            RepairTime:
              dayjs(temp.RepairTime).format('YYYY-MM-DD HH:mm') || '-',
            Reason: temp.Note,
            Repairman:
              userList.find((item) => item.ID === temp.MaintenancePerson) ||
              '-',
            DispatchMan:
              userList.find(
                (item) => (item.ID = temp.Operators[0]?.Operator?.ID),
              ) || '-',
            OrderStatus:
              OrderStatus.find((item) => item.value === temp.Status) || '-',
            MandateImages:
              temp?.mandate_images?.length > 0
                ? temp.mandate_images.map((item) => {
                    if (item.type === 2) {
                      return {
                        src: item.val,
                      };
                    }
                    return {
                      src: `data:image/png;base64,${item.val}`,
                    };
                  })
                : [],
          };
          setOrderInfo(tempDetail);
        }
      },
    },
  );

  const { run: getDosingOrder, loading: dosingLoding } = useRequest(
    getReagentOrderDetail,
    {
      manual: true,
      formatResult: (result) => {
        const temp = {
          ...result,
          CreateTime: result?.start_time?.Valid
            ? dayjs(result?.start_time?.Time).format('YYYY-MM-DD HH:mm')
            : '-',
          PlanTime: result?.plan_end_time?.Valid
            ? dayjs(result.plan_end_time.Time).format('YYYY-MM-DD HH:mm')
            : '-',
          RepairTime: result?.actual_end_time?.Valid
            ? dayjs(result.actual_end_time.Time).format('YYYY-MM-DD HH:mm')
            : '-',
          Reason: result.note,
          Repairman: '-',
          DispatchMan:
            userList.find((user) => user.ID === result.operator_id) || '-',
          OrderStatus:
            OrderStatus.find((status) => status.value === result.status) || '-',
        };
        setOrderInfo(temp);
        setAdditionalInfo(temp);
      },
    },
  );

  useRequest(getWorkOrderFlow, {
    defaultParams: [{ work_type: order_type, work_id: order_id }],
    formatResult(res) {
      if (res && res?.length) {
        setStepInfo(res);
      }
    },
  });

  const loading = useMemo(() => {
    if (craftLoading || repairLoading || maintainLoading || dosingLoding) {
      return true;
    }
    return false;
  }, [craftLoading, repairLoading, maintainLoading, dosingLoding]);

  const closePage = () => {
    // ToDo: send message to unity to close this page
    UnityAction.sendMsg('CloseWorkOrder');
  };

  const renderImg = () => {
    return (
      <Col span={18}>
        {orderInfo?.MandateImages?.length > 0 &&
          orderInfo?.MandateImages?.map((item, index) => {
            return (
              <ReactZmage
                key={index}
                controller={{
                  close: true,
                  flip: true,
                  zoom: true,
                  pagination: true,
                  download: false,
                }}
                backdrop="rgba(255,255,255,0.5)"
                style={{
                  maxWidth: `${Math.floor(
                    100 / orderInfo?.MandateImages?.length,
                  )}%`,
                }}
                src={item.src}
                set={orderInfo?.MandateImages}
                defaultPage={index}
              />
            );
          })}
      </Col>
    );
  };

  useEffect(() => {
    switch (order_type) {
      case 1:
      case 4:
      case 6:
        getCraftDetail({ project_id: projectID, work_id: order_id });
        break;
      case 2:
        getRepairDetail({ project_id: projectID, id: order_id });
        break;
      case 3:
        getMaintainDetail({ project_id: projectID, id: order_id });
        break;
      case 5:
        getDosingOrder(order_id);
        break;
      default:
        break;
    }
  }, []);

  return (
    <div className={styles.pages}>
      <div className={styles.modalContainer}>
        <div className={styles.modalTitle}>工单信息</div>
        <Button
          className={styles.closeModalBtn}
          type="text"
          icon={
            <CloseCircleFilled
              style={{ fontSize: '0.32rem', color: 'rgba(155, 151, 151, 1)' }}
            />
          }
          onClick={closePage}
        />
        <Divider style={{ margin: '0 0 0.1rem 0' }} />
        <Spin spinning={loading}>
          <div>
            <div>
              <SubTitle title="工单信息" radius />
              <div className={styles.basicalInfo}>
                <Row style={{ marginTop: '0' }}>
                  <Col span={13} className={styles.fontS32}>
                    工单类型：
                    {OrderType.find((item) => item.value === order_type)
                      ?.label || '-'}
                  </Col>
                  <Col span={8} className={styles.fontS32}>
                    {/*// @ts-ignore*/}
                    工单负责人：{orderInfo?.Repairman?.CName || '-'}
                  </Col>
                </Row>
                <Row>
                  <Col span={13} className={styles.fontS32}>
                    工单状态：{orderInfo?.OrderStatus?.label}
                  </Col>
                  <Col span={8} className={styles.fontS32}>
                    派单人员：{orderInfo?.DispatchMan?.CName}
                  </Col>
                </Row>
                <Row>
                  <Col className={styles.fontS32}>
                    派单时间：{orderInfo?.CreateTime || '-'}
                  </Col>
                </Row>
                <Row>
                  <Col span={13} className={styles.fontS32}>
                    计划完成时间：{orderInfo?.PlanTime || '-'}
                  </Col>
                </Row>
                <Row>
                  <Col className={styles.fontS32}>
                    实际完成时间：{orderInfo?.RepairTime || '-'}
                  </Col>
                </Row>
                {orderInfo?.MandateImages?.length > 0 && (
                  <Row>
                    <Col className={styles.fontS32} span={4}>
                      任务图片：
                    </Col>
                    {renderImg()}
                  </Row>
                )}
              </div>
            </div>
            {order_type === 3 && (
              <div>
                <SubTitle title="操作内容" />
                <div className={styles.additionInfo}>
                  <Row justify={'space-around'} style={{ marginTop: '0' }}>
                    <Col className={styles.fontS32} span={8}>
                      是否润滑/加油：
                      {orderInfo?.Lubrication === 1 ? '是' : '否'}
                    </Col>
                    <Col className={styles.fontS32} span={8}>
                      是否拆检：{orderInfo?.Check === 1 ? '是' : '否'}
                    </Col>
                    <Col className={styles.fontS32} span={8}>
                      是否清洁：{orderInfo?.Clean === 1 ? '是' : '否'}
                    </Col>
                  </Row>
                  <Row justify={'space-around'}>
                    <Col className={styles.fontS32} span={8}>
                      是否紧固：{orderInfo?.Fasten === 1 ? '是' : '否'}
                    </Col>
                    <Col className={styles.fontS32} span={8}>
                      是否除锈：{orderInfo?.AntiCorrosive === 1 ? '是' : '否'}
                    </Col>
                    <Col className={styles.fontS32} span={8}>
                      是否防腐：{orderInfo?.RustRemoval === 1 ? '是' : '否'}
                    </Col>
                  </Row>
                </div>
              </div>
            )}
            {order_type === 5 && (
              <div>
                <SubTitle title="加药详情" />
                <div
                  style={{
                    padding: '0.15rem',
                    background: 'rgba(23, 85, 255, 0.06)',
                  }}
                >
                  <Row>
                    <Col className={styles.fontS32}>加药详情：</Col>
                    <Col className={styles.fontS32} span={18}>
                      {`药剂名称：${additionalInfo?.name || '-'} 加药量：${
                        additionalInfo?.dosage || '-'
                      }升 浓度：${additionalInfo?.concentration || '-'}`}
                    </Col>
                  </Row>
                </div>
              </div>
            )}
            {stepInfo.length > 0 && (
              <div>
                <SubTitle title="工单流程" />
                <Divider
                  type="horizontal"
                  style={{
                    height: '0.02rem',
                    margin: 0,
                    padding: 0,
                    color: 'rgba(23, 85, 255, 0.50)',
                    background: 'rgba(23, 85, 255, 0.50)',
                  }}
                />
                <div
                  style={{
                    padding: '0.15rem 0.2rem',
                  }}
                  className={styles.taskStep}
                >
                  <Steps
                    direction="vertical"
                    progressDot
                    current={1}
                    items={stepInfo?.map((item) => {
                      return {
                        title: (
                          <span className={styles.fontS32}>{item.content}</span>
                        ),
                        description: (
                          <span className={styles.fontS28}>{item.time}</span>
                        ),
                      };
                    })}
                  />
                </div>
              </div>
            )}
          </div>
        </Spin>
      </div>
    </div>
  );
};

export default connect(({ taskUser }) => {
  return {
    userList: taskUser.userList,
  };
})(WorkOrderModal);
