import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import { IUserType } from '@/pages/TaskManage/Detail/TaskList/taskList.types';
import SubTitle from '@/pages/TaskManage/components/SubTitle';
import { OrderStatus, OrderType } from '@/pages/TaskManage/constent';
import {
  getCraftRecordList,
  getMaintainRecordList,
  getPatrolMandateRecord,
  getRepairRecordList,
  getWorkOrderFlow,
  queryReagentDetail,
} from '@/services/TaskManage';
import { useLocation } from '@@/exports';
import { connect, useRequest } from '@umijs/max';
import { Col, Row, Steps } from 'antd';
import dayjs from 'dayjs';
import { DefaultOptionType } from 'rc-select/es/Select';
import React, { useEffect, useState } from 'react';
// @ts-ignore
import ReactZmage from 'react-zmage';

import styles from './taskOrder.less';

interface IPropsType {
  userList: IUserType[];
  dispatch: (args: { type: string; payload: object }) => void;
}

interface IOrderInfo {
  CreateTime: string;
  PlanTime: string;
  RepairTime: string;
  Reason: string;
  Repairman: string | IUserType;
  DispatchMan: string | IUserType;
  OrderStatus: string | DefaultOptionType;
  Lubrication?: number;
  Fasten?: number;
  RustRemoval?: number;
  AntiCorrosive?: number;
  Clean?: number;
  Check?: number;
  MandateImages?: any[];
}

interface IStepInfo {
  content: string;
  time: string;
}

const TaskOrder: React.FC<IPropsType> = (props) => {
  const { userList, dispatch } = props;

  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const project_id = Number(queryParams.get('project_id'));
  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<IOrderInfo>();
  const [additionalInfo, setAdditionalInfo] = useState<any>({});
  const [stepInfo, setStepInfo] = useState<IStepInfo[]>();

  // 根据type请求详情
  const { run: getMaintainDetail } = useRequest(getMaintainRecordList, {
    manual: true,
    formatResult: (result) => {
      const temp = result.data.list[0];
      const tempDetail = {
        CreateTime: temp?.CreateTime
          ? dayjs(temp?.CreateTime).format('YYYY-MM-DD HH:mm')
          : '-',
        PlanTime: temp?.PlanTime
          ? dayjs(temp.PlanTime).format('YYYY-MM-DD HH:mm')
          : '-',
        RepairTime: temp?.RepairTime
          ? dayjs(temp.RepairTime).format('YYYY-MM-DD HH:mm')
          : '-',
        Reason: temp.Note,
        Lubrication: temp.Lubrication,
        Fasten: temp.Fasten,
        RustRemoval: temp.RustRemoval,
        AntiCorrosive: temp.Anticorrosive,
        Clean: temp.Clean,
        Check: temp.Check,
        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: any) => {
                if (item.type === 2) {
                  return {
                    src: item.val,
                  };
                }
                return {
                  src: `data:image/png;base64,${item.val}`,
                };
              })
            : [],
      };
      setOrderInfo(tempDetail);
    },
  });

  // 根据type请求详情
  const { run: getRepairDetail } = useRequest(getRepairRecordList, {
    manual: true,
    formatResult: (result: any) => {
      const temp = result.data.list[0];
      if (temp === undefined) {
        return;
      }
      const tempDetail: IOrderInfo = {
        CreateTime: temp.CreateTime
          ? dayjs(temp.CreateTime).format('YYYY-MM-DD HH:mm')
          : '-',
        PlanTime: temp.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: '-',
        OrderStatus:
          OrderStatus.find((item) => item.value === temp.AcceptanceStatus) ||
          '-',
        MandateImages:
          temp?.mandate_images?.length > 0
            ? temp.mandate_images.map((item: any) => {
                console.log(item);
                if (item.type === 2) {
                  return {
                    src: item.val,
                  };
                }
                return {
                  src: `data:image/png;base64,${item.val}`,
                };
              })
            : [],
      };
      setOrderInfo(tempDetail);
    },
  });

  // 根据type请求详情
  const { run: getCraftDetail } = useRequest(getCraftRecordList, {
    manual: true,
    formatResult: (result) => {
      const temp = result.data.list[0];
      const tempDetail = {
        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: temp.detail,
        Repairman: userList.find((item) => item.ID === temp.operator_id) || '-',
        DispatchMan:
          userList.find((item) => item.ID === temp.checker_id) || '-',
        OrderStatus:
          OrderStatus.find((item) => item.value === temp.status) || '-',
        MandateImages:
          temp?.mandate_images?.length > 0
            ? temp.mandate_images.map((item: any) => {
                console.log(item);
                if (item.type === 2) {
                  return {
                    src: item.val,
                  };
                }
                return {
                  src: `data:image/png;base64,${item.val}`,
                };
              })
            : [],
      };

      setOrderInfo(tempDetail);
    },
  });

  const { run: getDosingOrder } = useRequest(queryReagentDetail, {
    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);
    },
  });

  const { run: getPatrolOrderList } = useRequest(getPatrolMandateRecord, {
    manual: true,
    formatResult: (result) => {
      if (result?.data?.list) {
        const temp = result.data.list[0];
        const tempDetail = {
          ...temp,
          CreateTime: temp?.CreatedTime
            ? dayjs(temp.CreatedTime).format('YYYY-MM-DD HH:mm')
            : '-',
          PlanTime: temp.plan_end_time
            ? 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: temp.detail,
          Repairman: '-',
          DispatchMan:
            userList.find((user) => user.ID === temp.operator_id) || '-',
          OrderStatus:
            OrderStatus.find((status) => status.value === temp.status) || '-',
        };
        setOrderInfo(tempDetail);
      }
    },
  });

  // 获取工单流程信息
  useRequest(getWorkOrderFlow, {
    // manual: true,
    defaultParams: [{ work_type: order_type, work_id: order_id }],
    formatResult(res: IStepInfo[]) {
      if (res && res?.length) {
        setStepInfo(res);
      }
    },
  });

  useEffect(() => {
    if (userList.length === 0) {
      dispatch({
        type: 'taskUser/fetchUserList',
        payload: { project_id },
      });
    }
    switch (order_type) {
      // 工艺
      case 1:
      case 7:
      case 6:
        getCraftDetail({ project_id, work_id: order_id });
        break;
      // 维修
      case 2:
        getRepairDetail({ project_id, id: order_id });
        break;
      // 保养
      case 3:
        getMaintainDetail({ project_id, id: order_id });
        break;
      // 巡检
      case 4:
        getPatrolOrderList({ project_id, id: order_id });
        break;
      // 加药
      case 5:
        getDosingOrder({ id: order_id });
        break;
    }
  }, []);

  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>
    );
  };

  return (
    <PageContent closeable={false}>
      <PageTitle returnable>工单详情</PageTitle>
      <div className={styles.selfCardBox}>
        <div className={styles.orderInfo}>
          <SubTitle
            title="工单信息"
            // @ts-ignore
            showStatus={orderInfo?.OrderStatus.value === 2}
            radius
          />
          <div style={{ padding: '15px', letterSpacing: '1.5px' }}>
            <Row className={styles.rowMargin}>
              <Col className={styles.fontS28} span={15}>
                {/* @ts-ignore */}
                工单类型：
                {OrderType.find((item) => item.value === order_type)?.label ||
                  '-'}
              </Col>
              <Col className={styles.fontS28} span={9}>
                {/* @ts-ignore */}
                工单负责人：{orderInfo?.Repairman?.CName || '-'}
              </Col>
            </Row>
            <Row className={styles.rowMargin}>
              <Col className={styles.fontS28} span={15}>
                {/*  @ts-ignore */}
                工单状态：{orderInfo?.OrderStatus?.label}
              </Col>
              <Col className={styles.fontS28} span={9}>
                {/* @ts-ignore */}
                派单人员：{orderInfo?.DispatchMan?.CName || '-'}
              </Col>
            </Row>
            <Row className={styles.rowMargin}>
              <Col className={styles.fontS28}>
                派单时间：{orderInfo?.CreateTime || '-'}
              </Col>
            </Row>
            <Row className={styles.rowMargin}>
              <Col className={styles.fontS28}>
                计划完成时间：{orderInfo?.PlanTime || '-'}
              </Col>
            </Row>
            <Row className={styles.rowMargin}>
              <Col className={styles.fontS28}>
                实际完成时间：{orderInfo?.RepairTime || '-'}
              </Col>
            </Row>
            <Row>
              <Col className={styles.fontS28}>工单详情：</Col>
              <Col className={styles.fontS28} span={18}>
                {orderInfo?.Reason}
              </Col>
            </Row>

            {/* @ts-ignore */}
            {orderInfo?.MandateImages?.length > 0 && (
              <Row className={styles.rowMarginTop}>
                <Col className={styles.fontS28}>任务图片：</Col>
                {renderImg()}
              </Row>
            )}
          </div>
        </div>
        {order_type === 3 && (
          <div>
            <SubTitle title="维修内容" />
            <div style={{ padding: '15px' }}>
              <Row className={styles.rowMargin} 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="加药详情" />
            <div style={{ padding: '15px' }}>
              <Row>
                <Col className={styles.fontS28} span={8}>
                  药剂名称：{additionalInfo?.name || '-'}
                </Col>
                <Col className={styles.fontS28} span={8}>
                  加药量：{additionalInfo?.dosage || '-'}升
                </Col>
                <Col className={styles.fontS28} span={8}>
                  浓度：{additionalInfo?.concentration || '-'}
                </Col>
              </Row>
            </div>
          </div>
        )}
        {/* @ts-ignore */}
        {stepInfo?.length > 0 && (
          <div>
            <SubTitle title="工单流程" />
            <div style={{ padding: '15px 20px' }}>
              <Steps
                direction="vertical"
                current={stepInfo?.length ? stepInfo.length - 1 : 0}
                progressDot
                items={stepInfo?.map((item) => {
                  return {
                    title: (
                      <span className={styles.fontS28}>{item.content}</span>
                    ),
                    description: (
                      <span className={styles.fontS24}>{item.time}</span>
                    ),
                  };
                })}
              />
            </div>
          </div>
        )}
      </div>
    </PageContent>
  );
};

export default connect(({ taskUser }: any): { userList: IUserType[] } => {
  return {
    userList: taskUser.userList,
  };
})(TaskOrder);
