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,
} from '@/pages/TaskManage/constent';
import {
  getDiagnosticDetail,
  getMandateDetail,
  withdrawOrderRequest,
} from '@/services/TaskManage';
import { useLocation } from '@@/exports';
import { CaretDownFilled } from '@ant-design/icons';
import { connect, useRequest } from '@umijs/max';
import {
  Col,
  Collapse,
  CollapseProps,
  Divider,
  Form,
  Input,
  Modal,
  Row,
  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 styles from './taskDetail.less';

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

  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 base64ToImageUrl = (base64String: string) => {
    const byteCharacters = atob(base64String);
    const byteArrays = [];

    for (let i = 0; i < byteCharacters.length; i++) {
      byteArrays.push(byteCharacters.charCodeAt(i));
    }

    const byteArray = new Uint8Array(byteArrays);
    const blob = new Blob([byteArray], { type: 'image/png' });
    return URL.createObjectURL(blob);
  };

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

  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.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>
              <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>
          </div>
          <div className={styles.relatedOrder}>
            <Collapse
              className={styles.collapseLabel}
              ghost
              expandIcon={({ isActive }) => (
                <CaretDownFilled
                  style={{ color: '#ffffff' }}
                  rotate={isActive ? 180 : 0}
                />
              )}
              items={handledWorkOrder}
            />
          </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>
    </PageContent>
  );
}

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