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 } from '@/services/TaskManage';
import { useLocation } from '@@/exports';
import { UpOutlined } from '@ant-design/icons';
import { connect, useRequest } from '@umijs/max';
import { Col, Collapse, CollapseProps, Divider, Row, Table } 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 columnDef: ColumnsType<IColumn> = [
    {
      title: '详情',
      dataIndex: 'detail',
      key: 'key',
      render: (value, record) => {
        return (
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div style={{ width: '100%' }}>{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: '#5697e4' }}>
              关联工单({workOrder.length})
            </span>
          ),
          children: workOrder.map((record: IWorkOrderType) => {
            return (
              <div key={record.Id} className={styles.workOrderCard}>
                <div className={styles.leftInfo}>
                  <Row style={{ marginBottom: '15px' }}>
                    <Col className={styles.fontS24} span={12}>
                      <>
                        工单类型：
                        {record.RecordType?.label?.replace('工单', '')}
                      </>
                    </Col>
                    <Col className={styles.fontS24} span={12}>
                      时间：{record.CreateTime || '-'}
                    </Col>
                  </Row>
                  <Row>
                    <Col className={styles.fontS24} span={12}>
                      工单状态：
                      <span style={{ color: '#5697e4' }}>
                        {typeof record.Status === 'number'
                          ? '-'
                          : record.Status?.label}
                      </span>
                    </Col>
                    <Col className={styles.fontS24} span={12}>
                      工单负责人：
                      {typeof record.Responsible === 'number'
                        ? '-'
                        : record.Responsible?.CName}
                    </Col>
                  </Row>
                </div>
                <Divider type="vertical" style={{ height: '40px' }} />
                <div
                  className={styles.rightButton}
                  style={{ color: '#5697e4' }}
                  onClick={() => {
                    if (typeof record.RecordType === 'number') {
                      return;
                    }
                    // @ts-ignore
                    goTaskOrder(
                      record.Id,
                      record.RecordType?.value,
                      tempMandate?.MandateClass.value,
                    );
                  }}
                >
                  查看工单
                </div>
              </div>
            );
          }),
        },
      ];

      if (
        tempMandate.MandateClass &&
        tempMandate.ExtendId &&
        /* @ts-ignore */
        tempMandate.MandateClass.value === 7
      ) {
        const image = await getDiagnosticDetail(tempMandate.ExtendId);
        if (image?.event_bg) {
          tempMandate.img = base64ToImageUrl(image.event_bg);
        }
      }
      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].Title,
          key: 'title',
        },
      });
      dataSource.push(
        ...Object.entries(JSON.parse(mandateChild[0].Content)).map(
          (item: any) => {
            const [key, value] = item;
            return {
              detail: {
                text:
                  value['item_alias'] +
                  ' 现有数值：' +
                  value['old_value'] +
                  ' 建议调整数值' +
                  value['new_value'],
                key: key,
              },
            };
          },
        ),
      );
      setMandateTable(dataSource);
      return;
    }

    const dataSource = mandateChild.map((item, index) => {
      if (item.MandateClass === 2) {
      }

      return {
        detail: {
          text: item.Title + item.Content,
          key: item.Title + index + item.Content,
        },
      };
    });
    setMandateTable(dataSource);
  }, [mandateChild]);

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

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

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

          <Row>
            <Col className={styles.fontS24} span={4}>
              任务内容
            </Col>
            <Col className={styles.fontS24} span={20}>
              {/*{mandateDetail?.Detail}*/}
              <Table
                rowKey="key"
                columns={columnDef}
                dataSource={mandateTable}
                pagination={false}
              />
            </Col>
          </Row>
        </div>
        <div className={styles.relatedOrder}>
          <Collapse
            className={styles.collapseLabel}
            ghost
            expandIcon={({ isActive }) => (
              <UpOutlined
                style={{ color: '#5697e4' }}
                rotate={isActive ? 180 : 0}
              />
            )}
            items={handledWorkOrder}
          />
        </div>
      </div>
    </PageContent>
  );
}

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