import { queryMandate } from '@/services/SmartOps';
import { UnityAction } from '@/utils/utils';
import { connect, useRequest } from '@umijs/max';
import {
  Button,
  Checkbox,
  Col,
  ConfigProvider,
  DatePicker,
  Divider,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Table,
  message,
} from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import {
  MandateClass,
  MandateStatus,
  MandateType,
  OrderStatus,
  OrderType,
  ignoreReason,
} from '../constent';
import styles from './MandateDetail.less';

import zhCN from 'antd/es/locale/zh_CN';

const MandateDetail = (props) => {
  const {
    projectID,
    mandateID,
    userList,
    ignoreTask,
    dispatchTask,
    autoHandleTask,
    dispatch,
  } = props;

  useEffect(() => {
    if (userList.length === 0) {
      dispatch({
        type: 'taskUser/fetchUserList',
        payload: { project_id: projectID },
      });
    }
  }, []);

  const [mandateDetail, setMandateDetail] = useState();
  const [mandateChild, setMandateChild] = useState([]);
  const [handledWorkOrder, setHandledWorkOrder] = useState([]);

  const [ignoreModalOpen, setIgnoreModalOpen] = useState(false);
  const [autoHandleModalOpen, setAutoHandleModalOpen] = useState(false);
  const [mandateSelectModalOpen, setMandateSelectModalOpen] = useState(false);
  const [selectedTask, setSelectedTask] = useState([]);
  const [dispatchModalOpen, setDispatchModalOpen] = useState(false);

  const columns = [
    {
      title: '参数',
      dataIndex: 'Title',
    },
    {
      title: '调整内容',
      dataIndex: 'Content',
    },
  ];

  const { run: getMandateInfo } = useRequest(queryMandate, {
    manual: true,
    formatResult: (result) => {
      if (result?.data) {
        const tempMandate = {
          ...result.data,
          Status: MandateStatus.find(
            (item) => item.value === result.data.Status,
          ),
          MandateClass: MandateClass.find(
            (item) => item.value === result.data.MandateClass,
          ),
          MandateType: MandateType.find(
            (item) => item.value === result.data.MandateType,
          ),
          ResponsiblePeople: userList.find(
            (item) => item.ID === result.data.ResponsiblePeople,
          ),
          CreateTime: dayjs(result.data.CreateTime).format('YYYY-MM-DD HH:mm'),
        };
        const workOrder = result.data.Records.map((item) => {
          return {
            ...item,
            CreateTime: dayjs(item.CreateTime).format('YYYY-MM-DD HH:mm'),
            Status: OrderStatus.find((status) => status.value === item.Status),
            RecordType: OrderType.find(
              (type) => type.value === item.RecordType,
            ),
            Responsible: userList.find((user) => user.ID === item.Responsible),
          };
        });
        setMandateDetail(tempMandate);
        setMandateChild(tempMandate.MandateChild);
        setHandledWorkOrder(workOrder);
      }
    },
  });

  // 打开指定弹窗
  const openSpecifiedModal = (type) => {
    switch (type) {
      case 'ignore':
        setIgnoreModalOpen(true);
        break;
      case 'manual':
        UnityAction.sendMsg('menuItem', '工艺监控');
        break;
      case 'auto':
        setAutoHandleModalOpen(true);
        break;
      case 'dispatch':
        setMandateSelectModalOpen(true);
        break;
    }
  };

  // 忽略
  const onIgnoreConfirm = async (reason) => {
    const result = await ignoreTask(mandateID, reason);
    if (result) {
      setIgnoreModalOpen(false);
      getMandateInfo({ mandate_id: mandateID });
    }
  };

  const onAutoHandleConfirm = async (pw) => {
    const result = await autoHandleTask(pw, mandateDetail);
    if (result) {
      setAutoHandleModalOpen(false);
      getMandateInfo({ mandate_id: mandateID });
    }
  };

  const onManualHandleConfirm = () => {
    console.log('manual handle Confirm');
  };

  const onMandateSelected = (records) => {
    // 打开派单Form弹窗将选中的任务进行派遣
    if (records?.length === 0) {
      message.warning('请先选择要派遣的任务');
      return;
    }
    setSelectedTask(records);
    setDispatchModalOpen(true);
  };

  const onDispatchConfirm = async (value) => {
    const params = {
      ...value,
      m_id: Number(mandateID),
      mc_id: selectedTask.join(),
      plan_end_time: dayjs(value.plan_end_time).format('YYYY-MM-DD HH:mm:ss'),
    };
    if (params.type === 5) {
      if (params.mc_id.split(',').length > 1) {
        message.warning('加药工单不可批量派遣');
        return;
      }
      params.note = `${
        mandateChild
          .find((mandate) => mandate.Id === Number(params.mc_id))
          ?.Title?.split('：')[1] + '，请及时加药'
      }`;
    } else {
      params.note = mandateDetail.Summary;
    }
    const result = await dispatchTask(params);
    if (result) {
      setDispatchModalOpen(false);
      getMandateInfo({ mandate_id: mandateID });
    }
  };

  const openWorkOrderModal = (record) => {
    UnityAction.sendMsg(
      'OpenWorkOrderModal',
      `order_id=${record.Id}&order_type=${record.RecordType.value}`,
    );
  };

  useEffect(() => {
    getMandateInfo({ mandate_id: mandateID });
  }, []);

  return (
    <div>
      <div className={styles.mandate}>
        <Row>
          <Col className={styles.fontS28}>任务内容：</Col>
          <Col className={styles.fontS28} span={21}>
            <Table
              columns={columns}
              dataSource={mandateChild}
              pagination={false}
            />
          </Col>
        </Row>
        <Row>
          <Col className={styles.fontS28} span={14}>
            任务时间：{mandateDetail?.CreateTime || '-'}
          </Col>
          <Col className={styles.fontS28}>
            任务类别：{mandateDetail?.MandateClass?.label || '-'}
          </Col>
        </Row>
        <Row>
          <Col className={styles.fontS28} span={14}>
            任务状态：{' '}
            <span style={{ color: ' #5697e4' }}>
              {mandateDetail?.Status.label}
            </span>
          </Col>
          <Col className={styles.fontS28}>
            任务负责人：{mandateDetail?.ResponsiblePeople?.CName || '-'}
          </Col>
        </Row>
      </div>
      {handledWorkOrder?.length > 0 && <Divider />}
      {handledWorkOrder?.map((item) => {
        return (
          <div key={item.Id} className={styles.relatedOrder}>
            <div className={styles.leftInfo}>
              <Row>
                <Col span={12} className={styles.fontS28}>
                  工单类型：{item?.RecordType?.label}
                </Col>
                <Col className={styles.fontS28}>时间：{item?.CreateTime}</Col>
              </Row>
              <Row>
                <Col span={12} className={styles.fontS28}>
                  工单状态：
                  <span style={{ color: ' #5697e4' }}>
                    {item?.Status?.label}
                  </span>
                </Col>
                <Col className={styles.fontS28}>
                  工单负责人：{item?.Responsible?.CName}
                </Col>
              </Row>
            </div>
            <Divider type="vertical" style={{ height: '40px' }} />
            <div
              className={styles.rightButton}
              onClick={() => openWorkOrderModal(item)}
            >
              查看工单
            </div>
          </div>
        );
      })}
      {mandateDetail?.Status?.value === 0 && <Divider />}
      {mandateDetail?.Status?.value === 0 && (
        <div className={styles.footerConstainer}>
          <Button
            className={styles.footerBtn}
            shape="round"
            onClick={() => {
              openSpecifiedModal('ignore');
            }}
          >
            忽略
          </Button>
          {(mandateDetail?.MandateClass?.value === 1 ||
            mandateDetail?.MandateClass?.value === 2) &&
            mandateDetail?.Status?.value === 0 && (
              <>
                <Button
                  className={styles.footerBtn}
                  shape="round"
                  onClick={() => {
                    openSpecifiedModal('manual');
                  }}
                >
                  手动处理
                </Button>
                <Button
                  className={styles.footerBtn}
                  shape="round"
                  onClick={() => {
                    openSpecifiedModal('auto');
                  }}
                >
                  自动处理
                </Button>
              </>
            )}
          <Button
            className={styles.footerBtn}
            shape="round"
            onClick={() => {
              openSpecifiedModal('dispatch');
            }}
          >
            派单
          </Button>
        </div>
      )}
      {/* 弹窗 */}
      <ConfigProvider locale={zhCN}>
        <IgnoreTaskModal
          open={ignoreModalOpen}
          onCancel={() => setIgnoreModalOpen(false)}
          onOk={onIgnoreConfirm}
        />
        <AutoHandleModal
          open={autoHandleModalOpen}
          onCancel={() => setAutoHandleModalOpen(false)}
          onOk={onAutoHandleConfirm}
        />
        <MandateSelectModal
          open={mandateSelectModalOpen}
          onCancel={() => setMandateSelectModalOpen(false)}
          selectedTask={selectedTask}
          setSelectedTask={setSelectedTask}
          onOk={onMandateSelected}
          list={mandateChild}
        />
        <DispatchTaskModal
          open={dispatchModalOpen}
          userList={userList}
          onCancel={() => {
            setDispatchModalOpen(false);
          }}
          onOK={onDispatchConfirm}
        />
      </ConfigProvider>
    </div>
  );
};

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

const IgnoreTaskModal = (params) => {
  const { open, onCancel, onOk } = params;

  const [ignoreReasonText, setIgnoreReasonText] = useState('');
  const [selectedReason, setSelectedReason] = useState({});
  const [showInput, setShowInput] = useState(false);

  const onReasonChange = (reason, option) => {
    if (reason !== 4) {
      setSelectedReason(option);
      setShowInput(false);
    } else {
      setShowInput(true);
    }
  };

  const onReasonTextChange = (e) => {
    setIgnoreReasonText(e.target.value);
  };

  const handleCancle = () => {
    setSelectedReason({});
    setIgnoreReasonText('');
    setShowInput(false);
    onCancel();
  };

  const confirmIgnore = () => {
    if (showInput) {
      if (!ignoreReasonText.length) {
        message.warning('请输入忽略理由');
      } else {
        onOk(ignoreReasonText);
      }
    } else {
      if (selectedReason?.label) {
        onOk(selectedReason.label);
      } else {
        message.warning('请选择忽略理由');
      }
    }
  };

  return (
    <Modal
      className={styles.handleModal}
      title="忽略"
      open={open}
      onCancel={handleCancle}
      onOk={confirmIgnore}
      width="60%"
      destroyOnClose
    >
      <div style={{ padding: '15px' }}>
        <Form>
          <Form.Item label="忽略理由:">
            <Select
              className={styles.fontS28}
              options={ignoreReason}
              onChange={onReasonChange}
              allowClear
            />
          </Form.Item>
          {showInput && (
            <Form.Item label="输入理由:">
              <Input placeholder="请输入理由" onChange={onReasonTextChange} />
            </Form.Item>
          )}
        </Form>
      </div>
    </Modal>
  );
};

const AutoHandleModal = (props) => {
  const { open, onCancel, onOk } = props;

  const [automation, setAutomation] = useState();

  const confirmAutoHandle = () => {
    if (automation.length) {
      onOk(automation);
    } else {
      message.warning('请输入口令');
    }
  };

  return (
    <Modal
      className={styles.handleModal}
      title="自动处理"
      open={open}
      onCancel={onCancel}
      onOk={confirmAutoHandle}
      width="60%"
      destroyOnClose
    >
      <div style={{ padding: '15px' }}>
        <Form>
          <Form.Item label="用户口令:">
            {
              <Input
                autoFocus
                style={{ width: '100%' }}
                placeholder="请输入口令"
                onChange={(e) => {
                  setAutomation(e.target.value);
                }}
              />
            }
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
};

const MandateSelectModal = (props) => {
  const { open, onCancel, list, onOk, selectedTask, setSelectedTask } = props;

  const [checkOptions, setCheckOptions] = useState([]);

  useEffect(() => {
    setCheckOptions(
      list.map((mandate, index) => {
        return {
          label: (
            <Row className={styles.taskCheckItem}>
              <span
                style={{
                  textDecoration: `${
                    mandate.Status === 0 ? '' : 'line-through'
                  }`,
                }}
              >
                {`${index + 1}. ${mandate.Title}为${mandate.Content}`}
              </span>
            </Row>
          ),
          value: mandate.Id,
          disabled: mandate.Status !== 0,
        };
      }),
    );
  }, [list]);

  const onDispatchClick = () => {
    onOk(selectedTask);
  };

  const handleCheckChange = (checkedValue) => {
    setSelectedTask(checkedValue);
  };

  return (
    <Modal
      className={styles.handleModal}
      title="选择任务"
      open={open}
      onCancel={onCancel}
      width={'80%'}
      destroyOnClose
      footer={[
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button key="dispatch" type="primary" onClick={onDispatchClick}>
          派单
        </Button>,
      ]}
    >
      <Checkbox.Group
        className={styles.taskCheckBox}
        options={checkOptions}
        onChange={handleCheckChange}
      />
    </Modal>
  );
};

const DispatchTaskModal = (props) => {
  const { open, onCancel, onOK, userList } = props;

  const [form] = Form.useForm();

  useEffect(() => {
    if (!open) {
      form.resetFields();
    }
  }, [open]);

  const handleDispatchConfirm = async () => {
    const value = await form.validateFields().catch((err) =>
      err.errorFields.forEach((item) => {
        message.error(item.errors);
      }),
    );
    if (!value) {
      return;
    }
    onOK(value);
  };

  return (
    <Modal
      className={styles.handleModal}
      title="派遣任务"
      onCancel={onCancel}
      open={open}
      destroyOnClose
      width="65%"
      onOk={handleDispatchConfirm}
    >
      <Form
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
      >
        <Form.Item
          label="工单类型"
          name="type"
          rules={[{ required: true, message: '请选择工单类型' }]}
        >
          <Select options={OrderType} placeholder="请选择工单类型" />
        </Form.Item>
        <Form.Item
          label="操作人"
          name="operator_id"
          rules={[{ required: true, message: '请选择操作人' }]}
        >
          <Select
            options={userList.map((item) => {
              return {
                label: item.CName,
                value: item.ID,
              };
            })}
            placeholder="请选择操作人"
          />
        </Form.Item>
        <Form.Item
          label="计划完成时间"
          name="plan_end_time"
          rules={[{ required: true, message: '请选择完成时间' }]}
        >
          <DatePicker
            inputReadOnly
            style={{ width: '100%' }}
            placeholder="请选择完成时间"
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};
