import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import {
  IPropsType,
  ITopFilter,
  IUserType,
} from '@/pages/TaskManage/Detail/TaskList/taskList.types';
import {
  MandateClass,
  MandateStatus,
  MandateType,
  OrderStatus,
  OrderType,
} from '@/pages/TaskManage/constent';
import { connect, useLocation } from '@umijs/max';

import TopFilter from '@/pages/TaskManage/components/TopFilter';
import { IMandateType } from '@/pages/TaskManage/index.types';
import { useNavigate } from '@@/exports';
import { Col, Collapse, CollapseProps, Divider, List, Row, Spin } from 'antd';
import React, { useEffect, useState } from 'react';
import styles from './taskList.less';

const TaskList: React.FC<IPropsType> = (props) => {
  const { userList, mandateList, loading, dispatch } = props;
  // const md5 = require('md5');
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const project_id = Number(queryParams.get('project_id'));
  const mandateType = Number(queryParams.get('mandateType'));

  const navigate = useNavigate();

  // 用于展示的任务列表
  const [mandateListShow, setMandateListShow] = useState<IMandateType[]>([
    ...mandateList.filter((item) => item.MandateType === mandateType),
  ]);
  // 顶部选择器配置
  const [topFilters, setTopFilters] = useState<ITopFilter[]>([]);

  /**
   * 处理选择器变化
   * @param value 选择的值，当清空时等于null
   */
  const onTopFilterChange = (value: any) => {
    if (topFilters.length === 0) {
      return;
    }
    let tempList = mandateList.filter(
      (item) => item.MandateType === mandateType,
    );

    for (let i = 0; i < value.length; i++) {
      if (value[i] !== null) {
        tempList = tempList.filter(
          // @ts-ignore
          (item) => item[topFilters[i].key] === value[i],
        );
        console.log(tempList.length);
      }
    }

    setMandateListShow(tempList);
  };

  // 获取用户
  useEffect(() => {
    if (userList.length === 0) {
      dispatch({
        type: 'taskUser/fetchUserList',
        payload: { project_id },
      });
    }
    if (mandateList.length === 0) {
      dispatch({
        type: 'mandate/fetchMandateList',
        payload: { project_id, mandate_type: mandateType, pageSize: 9999 },
      });
    }
  }, []);

  // 获取列表
  useEffect(() => {
    setMandateListShow(
      mandateList.filter((item) => item.MandateType === mandateType),
    );
  }, [mandateList]);

  // 顶部下拉过滤器
  useEffect(() => {
    const filters: ITopFilter[] = [];
    filters.push({
      key: 'MandateClass',
      placeholder: '任务类别',
      // @ts-ignore
      options: MandateClass.map((item) => {
        if (item.MandateType === mandateType) {
          return {
            value: item.value,
            label: item.label,
            key: item.value + '任务类别',
          };
        }
        return undefined;
      }).filter((item) => item),
    });

    filters.push({
      key: 'Status',
      placeholder: '任务状态',
      options: MandateStatus.map((item) => {
        return {
          ...item,
        };
      }),
    });
    setTopFilters(filters);
    setMandateListShow(
      mandateList.filter((item) => item.MandateType === mandateType),
    );
  }, [mandateType]);

  const goTaskDetail = (mandate: IMandateType) => {
    navigate(
      `/task-manage/list/detail?project_id=${project_id}&mandate_id=${mandate.Id}`,
    );
  };

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

  const buildTaskList = (item: IMandateType) => {
    const formatItem = {
      ...item,
      Status: MandateStatus.find((status) => status.value === item.Status),
      MandateType: MandateType.find((type) => type.value === item.MandateType),
      MandateClass: MandateClass.find(
        (itemClass) => itemClass.value === item.MandateClass,
      ),
      ResponsiblePeople: userList.find(
        (user) => user.ID === item.ResponsiblePeople,
      ),
    };

    const workOrder = item.Records.map((record) => {
      return {
        ...record,
        key: record.Id,
        Status: OrderStatus.find((status) => status.value === record.Status),
        RecordType: OrderType.find((type) => type.value === record.RecordType),
        Responsible: userList.find((user) => user.ID === record.Responsible),
      };
    });

    const collapseData: CollapseProps['items'] = [
      {
        key: '1',
        label: (
          <span style={{ color: '#5697e4' }}>关联工单({workOrder.length})</span>
        ),
        children: workOrder.map((order) => {
          return (
            <div key={order.Id} className={styles.workOrderCard}>
              <div className={styles.leftInfo}>
                <Row style={{ marginBottom: '15px' }}>
                  <Col className={styles.fontS24} span={12}>
                    工单编号：{order.Id}
                  </Col>
                  <Col className={styles.fontS24} span={12}>
                    时间：{order.CreateTime}
                  </Col>
                </Row>
                <Row>
                  <Col className={styles.fontS24} span={12}>
                    工单状态：
                    <span style={{ color: '#5697e4' }}>
                      {order.Status?.label}
                    </span>
                  </Col>
                  <Col className={styles.fontS24} span={12}>
                    工单负责人：{order.Responsible?.CName}
                  </Col>
                </Row>
              </div>
              <Divider type="vertical" style={{ height: '40px' }} />
              <div
                className={styles.rightButton}
                style={{ color: '#5697e4' }}
                onClick={() => {
                  goTaskOrder(order.Id, order.RecordType?.value);
                }}
              >
                查看工单
              </div>
            </div>
          );
        }),
      },
    ];

    return (
      <List.Item>
        <div className={`${styles.cardContainer} card-box`}>
          <Row justify="space-between" style={{ marginBottom: '20px' }}>
            <Col className={styles.fontS24}>时间：{formatItem.CreateTime}</Col>
            <Col className={styles.fontS24}>
              任务类别：{formatItem.MandateClass?.label}
            </Col>
            <Col className={styles.fontS24}>
              任务负责人：{formatItem.ResponsiblePeople?.CName || '-'}
            </Col>
          </Row>
          <Row
            justify="space-between"
            style={{ paddingBottom: '10px', borderBottom: '1px solid gray' }}
          >
            <Col className={styles.fontS24}>
              任务状态：{formatItem.Status?.label || '-'}
            </Col>
            <Col>
              <div
                className={styles.fontS24}
                style={{
                  backgroundColor: '#f5a623',
                  color: 'white',
                  width: '150px',
                  height: '50px',
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                }}
                onClick={() => {
                  goTaskDetail(item);
                }}
              >
                任务详情
              </div>
            </Col>
          </Row>
          <Row>
            <Collapse
              className={styles.collapseLabel}
              ghost
              items={collapseData}
            />
          </Row>
        </div>
      </List.Item>
    );
  };

  return (
    <PageContent>
      <PageTitle returnable>
        {MandateType.find((item) => item.value === mandateType)?.label}
      </PageTitle>
      <TopFilter filters={topFilters} onChange={onTopFilterChange} />
      <Spin spinning={loading}>
        <List
          itemLayout="horizontal"
          dataSource={mandateListShow}
          renderItem={buildTaskList}
        />
      </Spin>
    </PageContent>
  );
};

export default connect(
  ({
    taskUser,
    mandate,
    loading,
  }: any): {
    userList: IUserType[];
    mandateList: IMandateType[];
    loading: boolean;
  } => {
    return {
      userList: taskUser.userList,
      mandateList: mandate.mandateList,
      loading: loading.models['taskUser'] || loading.models['mandate'],
    };
  },
)(TaskList);
