import {
  getCraftRecordList,
  getMaintainRecordList,
  getReagentOrderDetail,
  getRepairRecordList,
  getWorkOrderFlow,
} from '@/services/TaskManage';
import { CloseOutlined } from '@ant-design/icons';
import { connect, useLocation, useParams, useRequest } from '@umijs/max';
import { Button, Col, Divider, Row, Steps } from 'antd';
import dayjs from 'dayjs';
import { useEffect, 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 } = 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 } = 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 } = 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 } = 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 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.modalContainer}>
      <div className={styles.modalTitle}>工单信息</div>
      <Button
        className={styles.closeModalBtn}
        type="text"
        icon={<CloseOutlined style={{ fontSize: '24px' }} />}
        onClick={closePage}
      />
      <Divider style={{ margin: '0 0 30px 0' }} />
      <div
        style={{
          marginTop: '20px',
          borderRadius: '8px',
          boxShadow: '2px 0 8px 0 rgba(0, 0, 0, 30%)',
        }}
      >
        <div>
          <SubTitle
            title="工单信息"
            titleFontSize={24}
            showStatus={orderInfo?.OrderStatus?.value === 2}
            radius
          />
          <div className={styles.basicalInfo}>
            <Row>
              <Col span={16} className={styles.fontS28}>
                工单类型：
                {OrderType.find((item) => item.value === order_type)?.label ||
                  '-'}
              </Col>
              <Col span={8} className={styles.fontS28}>
                {/*// @ts-ignore*/}
                工单负责人：{orderInfo?.Repairman?.CName || '-'}
              </Col>
            </Row>
            <Row>
              <Col span={16} className={styles.fontS28}>
                工单状态：{orderInfo?.OrderStatus?.label}
              </Col>
              <Col span={8} className={styles.fontS28}>
                派单人员：{orderInfo?.DispatchMan?.CName}
              </Col>
            </Row>
            <Row>
              <Col className={styles.fontS28}>
                派单时间：{orderInfo?.CreateTime || '-'}
              </Col>
            </Row>
            <Row>
              <Col className={styles.fontS28}>
                计划完成时间：{orderInfo?.PlanTime || '-'}
              </Col>
            </Row>
            <Row>
              <Col className={styles.fontS28}>
                实际完成时间：{orderInfo?.RepairTime || '-'}
              </Col>
            </Row>
            {orderInfo?.MandateImages?.length > 0 && (
              <Row>
                <Col className={styles.fontS28} span={4}>
                  任务图片：
                </Col>
                {renderImg()}
              </Row>
            )}
          </div>
        </div>
        {order_type === 3 && (
          <div>
            <SubTitle title="操作内容" titleFontSize={24} />
            <div className={styles.additionInfo}>
              <Row justify={'space-around'}>
                <Col className={styles.fontS28} span={8}>
                  是否润滑/加油：{orderInfo?.Lubrication === 1 ? '是' : '否'}
                </Col>
                <Col className={styles.fontS28} span={8}>
                  是否拆检：{orderInfo?.Check === 1 ? '是' : '否'}
                </Col>
                <Col className={styles.fontS28} span={8}>
                  是否清洁：{orderInfo?.Clean === 1 ? '是' : '否'}
                </Col>
              </Row>
              <Row justify={'space-around'}>
                <Col className={styles.fontS28} span={8}>
                  是否紧固：{orderInfo?.Fasten === 1 ? '是' : '否'}
                </Col>
                <Col className={styles.fontS28} span={8}>
                  是否除锈：{orderInfo?.AntiCorrosive === 1 ? '是' : '否'}
                </Col>
                <Col className={styles.fontS28} span={8}>
                  是否防腐：{orderInfo?.RustRemoval === 1 ? '是' : '否'}
                </Col>
              </Row>
            </div>
          </div>
        )}
        {order_type === 5 && (
          <div>
            <SubTitle title="加药详情" titleFontSize={24} />
            <div style={{ padding: '15px' }}>
              <Row>
                <Col className={styles.fontS28}>加药详情：</Col>
                <Col className={styles.fontS28} span={18}>
                  {`药剂名称：${additionalInfo?.name || '-'} 加药量：${
                    additionalInfo?.dosage || '-'
                  }升 浓度：${additionalInfo?.concentration || '-'}`}
                </Col>
              </Row>
            </div>
          </div>
        )}
        {stepInfo.length > 0 && (
          <div>
            <SubTitle title="工单流程" titleFontSize={24} />
            <div style={{ padding: '15px 20px' }}>
              <Steps
                direction="vertical"
                progressDot
                current={1}
                items={stepInfo?.map((item) => {
                  return {
                    title: (
                      <span className={styles.fontS28}>{item.content}</span>
                    ),
                    description: (
                      <span className={styles.fontS20}>{item.time}</span>
                    ),
                  };
                })}
              />
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

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