import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import {
  IColumn,
  IMandateChildTypes,
} from '@/pages/TaskManage/Detail/TaskDetail/taskDetail.types';
import {
  IMandateDetailType,
  IUserType,
  IWorkOrderType,
} from '@/pages/TaskManage/Detail/TaskList/taskList.types';
import {
  MandateClass,
  MandateStatus,
  MandateType,
  OrderStatus,
  OrderType,
  ignoreReason,
} from '@/pages/TaskManage/constent';
import {
  dispatchOrder,
  getDiagnosticDetail,
  getMandateDetail,
  ignoreTaskRequest,
  setTaskAutomation,
  withdrawOrderRequest,
} from '@/services/TaskManage';
import { useLocation } from '@@/exports';
import { CaretDownFilled } from '@ant-design/icons';
import { connect, useRequest } from '@umijs/max';
import {
  Button,
  Checkbox,
  Col,
  Collapse,
  CollapseProps,
  ConfigProvider,
  DatePicker,
  Divider,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Table,
  message,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
// @ts-ignore
import ReactZmage from 'react-zmage';
import { useNavigate } from 'umi';

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

import { UnityAction } from '@/utils/utils';
import styles from './taskDetail.less';

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

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

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

  const onReasonTextChange = (e: any) => {
    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="忽略"
      maskStyle={{ borderRadius: 0 }}
      open={open}
      onCancel={handleCancle}
      onOk={confirmIgnore}
      width="60%"
      destroyOnClose
    >
      <div style={{ padding: '0.15rem' }}>
        <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: any) => {
  const { open, onCancel, onOk } = props;

  const [automation, setAutomation] = useState<string>();

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

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

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

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

  useEffect(() => {
    setCheckOptions(
      list.map((mandate: any, index: number) => {
        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: any) => {
    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: any) => {
  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: 8 }}
        wrapperCol={{ span: 14 }}
      >
        <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>
  );
};

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

function TaskDetail(props: IPropsType) {
  const { userList, dispatch } = props;

  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const project_id = Number(queryParams.get('project_id'));
  const mandate_id = Number(queryParams.get('mandate_id'));

  const navigate = useNavigate();

  const [mandateDetail, setMandateDetail] = useState<IMandateDetailType>();
  const [mandateChild, setMandateChild] = useState<IMandateChildTypes[]>([]);
  const [handledWorkOrder, setHandledWorkOrder] = useState<
    CollapseProps['items']
  >([]);
  const [mandateTable, setMandateTable] = useState<IColumn[]>([]);
  const [withdrawReason, setWithdrawReason] = useState('');
  const [withdrawOrderOpen, setWithdrawOrderOpen] = useState(false);
  const [clickedOrder, setClickedOrder] = useState<any>({});

  const [flodWorkOrder, setFlodWorkOrder] = useState(true);
  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 columnDef: ColumnsType<IColumn> = [
    {
      title: '详情',
      dataIndex: 'detail',
      key: 'key',
      render: (value, _record, index) => {
        return (
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div style={{ width: '100%' }}>
              {index + 1}、{value.text}
            </div>
          </div>
        );
      },
    },
  ];

  const { refresh: refreshDetail } = useRequest(getMandateDetail, {
    defaultParams: [
      {
        mandate_id,
        project_id,
      },
    ],
    formatResult: async (result) => {
      const tempMandate: IMandateDetailType = {
        ...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: IWorkOrderType) => {
        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),
        };
      });
      const children = result.data.MandateChild;

      const tempOrder = [
        {
          key: '1',
          label: (
            <span style={{ color: '#ffffff', marginRight: '0.05rem' }}>
              关联工单({workOrder.length})
            </span>
          ),
          children: workOrder.map((record: IWorkOrderType) => {
            return (
              <div key={record.Id} className={styles.workOrderCard}>
                <div className={styles.leftInfo}>
                  <Row style={{ marginBottom: '0.15rem' }}>
                    <Col className={styles.fontS30} span={10}>
                      <>
                        工单类型：
                        {record.RecordType?.label?.replace('工单', '')}
                      </>
                    </Col>
                    <Col className={styles.fontS30} span={14}>
                      时间：{record.CreateTime || '-'}
                    </Col>
                  </Row>
                  <Row>
                    <Col className={styles.fontS30} span={10}>
                      工单状态：
                      <span style={{ color: '#5697e4' }}>
                        {typeof record.Status === 'number'
                          ? '-'
                          : record.Status?.label}
                      </span>
                    </Col>
                    <Col className={styles.fontS30} span={14}>
                      工单负责人：
                      {typeof record.Responsible === 'number'
                        ? '-'
                        : record.Responsible?.CName}
                    </Col>
                  </Row>
                </div>
                <Divider type="vertical" style={{ height: '0.4rem' }} />
                <div className={styles.rightButtonContainer}>
                  <div
                    className={styles.rightButton}
                    style={{
                      marginBottom: `${
                        record.Status.value === 0 ? '0.15rem' : '0'
                      }`,
                    }}
                    onClick={() => {
                      if (typeof record.RecordType === 'number') {
                        return;
                      }
                      // @ts-ignore
                      goTaskOrder(
                        record.Id,
                        record.RecordType?.value,
                        tempMandate?.MandateClass.value,
                      );
                    }}
                  >
                    查看
                  </div>
                  {record?.Status?.value === 0 && (
                    <div
                      className={styles.rightButton}
                      onClick={() => {
                        setWithdrawOrderOpen(true);
                        setClickedOrder(record);
                      }}
                    >
                      关闭
                    </div>
                  )}
                </div>
              </div>
            );
          }),
        },
      ];

      if (
        tempMandate.MandateClass &&
        tempMandate.ExtendId &&
        /* @ts-ignore */
        tempMandate.MandateClass.value === 7
      ) {
        const image = await getDiagnosticDetail(tempMandate.ExtendId);
        tempMandate.img = image.path;
      }
      setMandateDetail(tempMandate);
      setHandledWorkOrder(tempOrder);
      if (children && children.length) {
        setMandateChild(children);
      }
    },
  });

  const { run: runIgnore } = useRequest(ignoreTaskRequest, {
    manual: true,
  });

  const { run: runDispatch } = useRequest(dispatchOrder, {
    manual: true,
  });

  const { run: runAutomate } = useRequest(setTaskAutomation, {
    manual: true,
  });

  // 忽略
  const onIgnoreTaskConfirm = async (id: any, reason: string) => {
    const params = {
      Id: id,
      Status: 4,
      note: reason,
    };
    const result = await runIgnore(params);
    if (result) {
      return true;
    }
  };
  // 派单
  const onDispatchTaskConfirm = async (params: any) => {
    const result = await runDispatch(params);
    if (result) {
      return true;
    }
  };
  // 自动处理
  const onAutoHandleTaskConfirm = async (pw: any, mandate: any) => {
    const params = {
      mandate_id: mandate.Id,
      pw,
    };
    const result = runAutomate(params, mandate);
    if (result) {
      return true;
    }
  };

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

  // 忽略
  const onIgnoreModalOk = async (reason: any) => {
    const result = await onIgnoreTaskConfirm(mandate_id, reason);
    if (result) {
      setIgnoreModalOpen(false);
      refreshDetail();
    }
  };

  const onAutoHandleModalOk = async (pw: any) => {
    const result = await onAutoHandleTaskConfirm(pw, mandateDetail);
    if (result) {
      setAutoHandleModalOpen(false);
      refreshDetail();
    }
  };

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

  const onDispatchModalOk = async (value: any) => {
    const params = {
      ...value,
      m_id: Number(mandate_id),
      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 onDispatchTaskConfirm(params);
    if (result) {
      setMandateSelectModalOpen(false);
      setDispatchModalOpen(false);
      setFlodWorkOrder(false);
      refreshDetail();
    }
  };

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

  useEffect(() => {
    if (!mandateChild.length) {
      return;
    }

    if (mandateDetail?.MandateClass?.value === 2) {
      const dataSource = [];
      dataSource.push({
        detail: {
          text: `${mandateChild[0].Content}: ${mandateChild[0].Content}`,
          key: 'title',
        },
      });
      console.log(mandateChild[0]);
      setMandateTable(dataSource);
      return;
    }

    const dataSource = mandateChild.map((item, index) => {
      if (item.MandateClass === 3 || item.MandateClass === 6) {
        return {
          detail: {
            text: item.Content,
            key: item.Title + index + item.Content,
          },
        };
      }
      return {
        detail: {
          text: item.Title + item.Content,
          key: item.Title + index + item.Content,
        },
      };
    });
    setMandateTable(dataSource);
  }, [mandateChild]);

  const goTaskOrder = (
    orderID: number,
    orderType: number,
    mandateClass: number,
  ) => {
    navigate(
      `/task-manage/list/order-detail?project_id=${project_id}&order_id=${orderID}&order_type=${orderType}&mandate_class=${mandateClass}`,
    );
  };

  const withdrawOrderConfirm = async () => {
    if (!withdrawReason) {
      message.warning('请输入关闭理由');
      return;
    }
    const res = await withdrawOrderRequest({
      record_id: clickedOrder?.Id,
      note: withdrawReason,
      type: clickedOrder?.RecordType?.value,
    });
    if (res.code === 200) {
      message.success('关闭工单成功');
      setClickedOrder({});
      setWithdrawOrderOpen(false);
      refreshDetail();
    }
  };

  return (
    <PageContent closeable={false}>
      <PageTitle returnable>任务详情</PageTitle>
      <div className=" content-title">
        <div className={`${styles.cardContainer}`}>
          <div className={styles.normalInfo}>
            <Row className={styles.infoRow}>
              <Col span={14} className={styles.fontS30}>
                时间：{mandateDetail?.CreateTime}
              </Col>
              {/*// @ts-ignore*/}
              <Col className={styles.fontS30}>
                {/*//@ts-ignore*/}
                任务类别：{mandateDetail?.MandateClass?.label}
              </Col>
            </Row>
            <Row>
              <Col span={14} className={styles.fontS30}>
                {/*//@ts-ignore*/}
                任务状态：{mandateDetail?.Status?.label}
              </Col>
              <Col className={styles.fontS30}>
                {/*// @ts-ignore*/}
                任务负责人：{mandateDetail?.ResponsiblePeople?.CName}
              </Col>
            </Row>
          </div>
          <div className={styles.detailInfo}>
            <Row className={styles.infoRow}>
              <Col
                className={styles.fontS30}
                span={4}
                style={{ fontWeight: 600 }}
              >
                任务总结
              </Col>
              <Col
                span={20}
                className={styles.fontS30}
                style={{ color: 'rgba(97, 93, 93, 1)' }}
              >
                {mandateDetail?.Summary ||
                  '根据水质相关数据．建议您调节以下参数，水厂运行可达较优状态'}
              </Col>
            </Row>
            {mandateDetail?.img && (
              <Row className={styles.infoRow}>
                <Col
                  className={styles.fontS30}
                  span={4}
                  style={{ fontWeight: 600 }}
                >
                  预警图片
                </Col>
                <Col className={styles.fontS30}>
                  <ReactZmage
                    controller={{
                      // 关闭按钮
                      close: true,
                      // 缩放按钮
                      zoom: false,
                      // 下载按钮
                      download: false,
                      // 翻页按钮
                      flip: false,
                      // 多页指示
                      pagination: false,
                    }}
                    backdrop="rgba(255,255,255,0.5)"
                    style={{ width: '3.5rem' }}
                    src={mandateDetail?.img}
                  />
                </Col>
              </Row>
            )}

            {mandateDetail?.Files !== undefined &&
              mandateDetail?.Files?.length > 0 && (
                <Row className={styles.infoRow}>
                  <Col
                    className={styles.fontS30}
                    span={4}
                    style={{ fontWeight: 600 }}
                  >
                    截图
                  </Col>
                  <Col className={styles.fontS30}>
                    <ReactZmage
                      controller={{
                        // 关闭按钮
                        close: true,
                        // 缩放按钮
                        zoom: false,
                        // 下载按钮
                        download: false,
                        // 翻页按钮
                        flip: true,
                        // 多页指示
                        pagination: true,
                      }}
                      backdrop="rgba(255,255,255,0.5)"
                      style={{ width: '3.5rem' }}
                      src={mandateDetail?.Files[0].url}
                      set={mandateDetail?.Files.map((item) => {
                        if (item) {
                          return {
                            src: item.url,
                          };
                        }
                        return {};
                      })}
                    />
                  </Col>
                </Row>
              )}

            <Row className={styles.infoRow}>
              <Col
                className={styles.fontS30}
                span={4}
                style={{ fontWeight: 600 }}
              >
                任务内容
              </Col>
              <Col className={styles.fontS30} span={20}>
                {/*{mandateDetail?.Detail}*/}
                <Table
                  className={styles.taskTable}
                  rowKey="key"
                  columns={columnDef}
                  dataSource={mandateTable}
                  pagination={false}
                />
              </Col>
            </Row>
            <Row justify="end" gutter={10}>
              <Col>
                {mandateDetail?.Status?.value === 0 && (
                  <Button
                    className={styles.footerBtn}
                    shape="round"
                    onClick={() => {
                      openSpecifiedModal('ignore');
                    }}
                  >
                    忽略
                  </Button>
                )}
              </Col>
              <Col>
                {(mandateDetail?.MandateClass?.value === 1 ||
                  mandateDetail?.MandateClass?.value === 2) &&
                  mandateDetail?.Status?.value === 0 && (
                    <Button
                      className={styles.footerBtn}
                      shape="round"
                      onClick={() => {
                        openSpecifiedModal('manual');
                      }}
                    >
                      手动处理
                    </Button>
                  )}
              </Col>
              <Col>
                {(mandateDetail?.MandateClass?.value === 1 ||
                  mandateDetail?.MandateClass?.value === 2) &&
                  mandateDetail?.Status?.value === 0 && (
                    <Button
                      className={styles.footerBtn}
                      shape="round"
                      onClick={() => {
                        openSpecifiedModal('auto');
                      }}
                    >
                      自动处理
                    </Button>
                  )}
              </Col>
              <Col>
                {mandateChild?.filter((item) => item.Status === 0)?.length >
                  0 && (
                  <Button
                    className={styles.footerBtn}
                    shape="round"
                    onClick={() => {
                      openSpecifiedModal('dispatch');
                    }}
                  >
                    派单
                  </Button>
                )}
              </Col>
            </Row>
          </div>
          <div className={styles.relatedOrder}>
            <Collapse
              className={styles.collapseLabel}
              activeKey={flodWorkOrder ? '' : '1'}
              ghost
              expandIcon={({ isActive }) => (
                <CaretDownFilled
                  style={{ color: '#ffffff' }}
                  rotate={isActive ? 180 : 0}
                />
              )}
              items={handledWorkOrder}
              onChange={() => {
                setFlodWorkOrder(!flodWorkOrder);
              }}
            />
          </div>
        </div>
      </div>
      <Modal
        className={styles.handleModal}
        title="关闭工单"
        open={withdrawOrderOpen}
        onCancel={() => {
          setWithdrawOrderOpen(false);
        }}
        onOk={withdrawOrderConfirm}
      >
        <Form>
          <Form.Item label="关闭原因">
            <Input
              onChange={(e) => {
                setWithdrawReason(e.target.value);
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
      <ConfigProvider locale={zhCN}>
        <IgnoreTaskModal
          open={ignoreModalOpen}
          onCancel={() => setIgnoreModalOpen(false)}
          onOk={onIgnoreModalOk}
        />
        <AutoHandleModal
          open={autoHandleModalOpen}
          onCancel={() => setAutoHandleModalOpen(false)}
          onOk={onAutoHandleModalOk}
        />
        <MandateSelectModal
          open={mandateSelectModalOpen}
          onCancel={() => setMandateSelectModalOpen(false)}
          selectedTask={selectedTask}
          setSelectedTask={setSelectedTask}
          onOk={onMandateSelected}
          list={mandateChild}
        />
        <DispatchTaskModal
          open={dispatchModalOpen}
          userList={userList}
          onCancel={() => {
            setDispatchModalOpen(false);
          }}
          onOK={onDispatchModalOk}
        />
      </ConfigProvider>
    </PageContent>
  );
}

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