import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import { getMandateIDs } from '@/services/eqSelfInspection';
import { GetTokenFromUrl, UnityAction } from '@/utils/utils';
import { connect, history, useLocation, useParams } from '@umijs/max';
import { Button, Form, Modal, Select, Spin, message } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import styles from './index.less';

const EqSelfInspection = (props) => {
  const { dispatch, autoReport, patrolList, loading } = props;
  const { projectId } = useParams();
  const { routeId } = useLocation();
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  // 0 正常 1 异常 2 loading
  const [patrolStatus, setPatrolStatus] = useState(0);
  const [faultAnalysisStatus, setFaultAnalysisStatus] = useState(0);
  const [secureStatus, setSecureStatus] = useState(0);
  const [secureChildren, setSecureChildren] = useState([]);
  const getDate = () => {
    dispatch({
      type: 'eqSelfInspection/getAutoPatrol',
      payload: {
        projectId,
      },
    });
  };

  const HandleInspection = () => {
    if (patrolList?.length === 0) {
      message.error('请配置巡检路线！');
    } else {
      UnityAction.sendMsg('StartInspection', '');
      dispatch({
        type: 'eqSelfInspection/getAutoPatrol',
        payload: { projectId },
        callback: (data) => {
          setPatrolStatus(data?.patrolStatus);
          setFaultAnalysisStatus(data?.faultAnalysisStatus);
          setSecureStatus(data?.secureStatus);
          setSecureChildren(data?.secureChild);
          history.replace(`/self-inspection/${projectId}?routeId=${data.Id}`);
        },
      });
    }
  };

  const handleOk = () => {
    UnityAction.sendMsg('StartInspection', '');
    form.validateFields((err, values) => {
      if (err) return;
      dispatch({
        type: 'eqSelfInspection/inspectionRoute',
        payload: { projectId, routeId: values.routeId },
        callback: (data) => {
          setPatrolStatus(data?.patrolStatus);
          setFaultAnalysisStatus(data?.faultAnalysisStatus);
          setSecureStatus(data?.secureStatus);
          setSecureChildren(data?.secureChild);
          history.replace(`/self-inspection/${projectId}?routeId=${data.Id}`);
        },
      });
    });
    handleCancel();
    setPatrolStatus(2);
    setSecureStatus(2);
    setFaultAnalysisStatus(2);
  };

  const handleCancel = () => {
    setVisible(false);
    form.resetFields();
  };

  const openTaskModal = async () => {
    if (!autoReport.Id) {
      return;
    }
    let mandateIDs = await getMandateIDs({
      project_id: projectId,
      id: autoReport.Id,
    }).catch((err) => {
      console.log(err);
    });
    if (mandateIDs?.length) {
      mandateIDs = [...new Set(mandateIDs)];
      UnityAction.sendMsg('OpenTaskModal', `mandate_id=${mandateIDs.join()}`);
    } else {
      message.info('未查询到相关任务');
    }
  };

  useEffect(() => {
    if (routeId) {
      dispatch({
        type: 'eqSelfInspection/getPatrolDataById',
        payload: {
          routeId: routeId,
        },
      });
    } else {
      getDate();
    }

    dispatch({
      type: 'eqSelfInspection/getList',
      payload: {
        ProjectId: projectId * 1,
      },
    });
  }, []);

  useEffect(() => {
    setPatrolStatus(autoReport?.patrolStatus);
    setFaultAnalysisStatus(autoReport?.faultAnalysisStatus);
    setSecureStatus(autoReport?.secureStatus);
    setSecureChildren(autoReport?.secureChild);
  }, [autoReport]);

  return (
    <PageContent>
      <PageTitle>系统自检</PageTitle>
      <Spin spinning={loading} tip="正在自检中...">
        <div className="content-title">
          <div
            className={`${styles.itemMain} card-box`}
            style={{ padding: '15px 24px', position: 'relative' }}
          >
            <div style={{ fontSize: 28, color: 'rgb(110, 110, 110)' }}>
              自检间隔：{autoReport?.RouteInfo?.PlanDur}分钟
            </div>

            <div className={styles.icon}>
              <div
                className={styles.iconDiffFilled}
                onClick={() => {
                  history.push(`/self-inspection/list/${projectId}`);
                }}
              ></div>
              <div
                className={styles.iconFundFilled}
                onClick={() => {
                  history.push(
                    `/self-inspection/statistics/${projectId}?JWT-TOKEN=${GetTokenFromUrl()}`,
                  );
                }}
              ></div>
            </div>
            <div className={styles.logoInfo}>
              <div className={styles.logo} />
              <div className={styles.logoTitle}>
                <div>
                  系统自检&nbsp;
                  {autoReport?.Status == 0 ? (
                    <span style={{ color: '#39CA74' }}>正常</span>
                  ) : (
                    <span style={{ color: 'rgba(254, 88, 80, 1)' }}>异常</span>
                  )}
                </div>
              </div>
              <div className={styles.logoTime}>
                {autoReport?.CreatedTime
                  ? dayjs(autoReport?.CreatedTime).format('YYYY-MM-DD HH:mm')
                  : ''}
              </div>
              <div className={styles.insbtn}>
                <Button type="primary" onClick={HandleInspection}>
                  一键自检
                </Button>
              </div>
              <div className={styles.logoFont}>系统自检中</div>
            </div>
          </div>
          <Item name="设备自检" status={patrolStatus}></Item>
          <Item name="工艺自检" status={faultAnalysisStatus}></Item>
          <Item name="安全自检" status={secureStatus}>
            {secureChildren?.map((item, index) => (
              <WarningItem
                key={index}
                label={item.label}
                status={item.status}
              />
            ))}
          </Item>
          <div
            className={styles.btnContainer}
            style={{
              justifyContent:
                autoReport?.Status == 0 ? 'center' : 'space-between',
            }}
          >
            {autoReport?.Status != 0 && (
              <Button
                className={styles.reportBtn}
                type="primary"
                onClick={() => {
                  openTaskModal();
                }}
              >
                查看任务
              </Button>
            )}
            <Button
              className={styles.reportBtn}
              type="primary"
              onClick={() => {
                history.push(
                  `/self-inspection/detail/${projectId}/${
                    autoReport?.Id
                  }?JWT-TOKEN=${GetTokenFromUrl()}`,
                );
              }}
            >
              查看自检报告
            </Button>
          </div>

          <Modal
            title="选择巡检路线"
            destroyOnClose
            open={visible}
            onOk={handleOk}
            width="40%"
            maskClosable={false}
            onCancel={handleCancel}
          >
            <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
              <Form.Item
                label="巡检路线"
                name="routeId"
                rules={[
                  {
                    required: true,
                    message: '请选择巡检路线',
                  },
                ]}
              >
                <Select placeholder="请选择巡检路线">
                  {patrolList?.map((item) => (
                    <Option key={item.Id} value={item.Id}>
                      {item?.Name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Form>
          </Modal>
        </div>
      </Spin>
    </PageContent>
  );
};

export default connect(({ eqSelfInspection, loading }) => ({
  autoReport: eqSelfInspection.autoReport,
  patrolList: eqSelfInspection.patrolList,
  loading: loading.models['eqSelfInspection'],
}))(EqSelfInspection);

const Item = (props) => {
  const { name, children, warningText = '', status = 0 } = props;
  const renderRight = (status) => {
    switch (status) {
      case 0:
        return <div className={`${styles.iconSuccess} ${styles.right}`}></div>;
      case 1:
        return (
          <div className={styles.right} style={{ color: '#FE5850' }}>
            异常
          </div>
        );
      case 2:
        return (
          <div className={styles.right} style={{ color: '#FFE26D' }}>
            警告
          </div>
        );
      // return <SyncOutlined className={styles.right} spin />;
      default:
        return <div className={`${styles.iconSuccess} ${styles.right}`}></div>;
    }
  };
  return (
    <div className={`${styles.itemMain} card-box`}>
      <div className={styles.item} style={{ height: children ? 80 : '' }}>
        <span className={styles.itemName}>{name}</span>
        {/* <span className={styles.warningText}>{warningText}</span> */}
        {renderRight(status)}
      </div>
      {children}
    </div>
  );
};

const WarningItem = (props) => {
  const { label, status } = props;
  return (
    <div className={styles.warningItem}>
      <span>{label}</span>

      {status === 0 ? (
        <div className={styles.iconSuccess}></div>
      ) : (
        <span
          style={{
            color: '#FE5850',
          }}
        >
          异常
        </span>
      )}
    </div>
  );
};
