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, useRequest } from '@umijs/max';

import TopFilter from '@/pages/TaskManage/components/TopFilter';
import { IMandateType } from '@/pages/TaskManage/index.types';
import { useNavigate } from '@@/exports';
import { DownOutlined } from '@ant-design/icons';
import {
  Button,
  Col,
  Collapse,
  CollapseProps,
  Divider,
  List,
  Row,
  Spin,
} from 'antd';

import { getMandateList } from '@/services/TaskManage';
import moment from 'moment';
import { useEffect, useState } from 'react';
import styles from './taskList.less';

const TaskList: React.FC<IPropsType> = (props) => {
  const { userList, loading, dispatch } = props;
  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[]>([]);
  // 顶部选择器配置
  const [topFiltersConfig, setTopFiltersConfig] = useState<ITopFilter[]>([]);
  const [mandateList, setMandateList] = useState<IMandateType[]>([]);
  const [mandatePage, setMandatePage] = useState({
    pageSize: 20,
    total: 0,
    current: 1,
  });
  const [currentParams, setCurrentParams] = useState({
    project_id,
    mandate_type: mandateType,
    pageSize: 20,
    currentPage: 2,
  });

  const { run: getList, loading: loadData } = useRequest(getMandateList, {
    defaultParams: [
      {
        project_id,
        mandate_type: mandateType,
        pageSize: mandatePage.pageSize,
        currentPage: mandatePage.current,
      },
    ],
    formatResult: (result) => {
      if (result.data.pagination.current === 1) {
        setMandateList(result.data.list);
      } else {
        setMandateList([...mandateList, ...result.data.list]);
      }
      const pageInfo = result.data.pagination;
      pageInfo.current += 1;
      setMandatePage(pageInfo);
    },
  });

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

  // 首次获取任务数据

  useEffect(() => {
    setMandateListShow(mandateList);
  }, [mandateList]);

  // 顶部下拉过滤器配置
  useEffect(() => {
    const filters: ITopFilter[] = [];
    filters.push({
      key: 'mandate_class',
      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,
        };
      }),
    });
    setTopFiltersConfig(filters);
    // setMandateListShow(
    //   mandateList.filter((item) => item.MandateType === mandateType),
    // );
  }, [mandateType]);

  /**
   * 处理选择器变化
   * @param value 选择的值，当清空时等于null
   */
  const onTopFilterChange = (value: any) => {
    if (topFiltersConfig.length === 0) {
      return;
    }
    const params: any = {
      project_id,
      mandate_type: mandateType,
      pageSize: mandatePage.pageSize,
      currentPage: 1,
    };
    for (let i = 0; i < value.length; i++) {
      if (value[i] !== null && topFiltersConfig[i] !== undefined) {
        params[topFiltersConfig[i].key] = value[i];
      }
    }
    getList(params);
    params.currentPage += 1;
    setCurrentParams(params);
  };

  const loadMoreMandate =
    !loadData && mandateListShow.length > mandatePage.total ? (
      <div
        style={{
          textAlign: 'center',
          marginTop: 12,
          height: 32,
          lineHeight: '32px',
          fontSize: '28px',
        }}
      >
        <Button
          type="text"
          size="large"
          style={{ fontSize: '28px', height: '56px', width: '160px' }}
        >
          加载更多
        </Button>
      </div>
    ) : null;

  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,
      ),
      CreateTime: moment(item.CreateTime).format('YYYY-MM-DD HH:mm'),
    };

    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),
        CreateTime: moment(record.CreateTime).format('YYYY-MM-DD HH:mm'),
      };
    });

    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 #D5D5D5',
            }}
          >
            <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
              expandIcon={({ isActive }) => (
                <DownOutlined
                  style={{ color: '#5697e4' }}
                  rotate={isActive ? 180 : 0}
                />
              )}
              items={collapseData}
            />
          </Row>
        </div>
      </List.Item>
    );
  };

  return (
    <PageContent closeable={false}>
      <PageTitle returnable>
        {MandateType.find((item) => item.value === mandateType)?.label}
      </PageTitle>
      <TopFilter filters={topFiltersConfig} onChange={onTopFilterChange} />
      <Spin spinning={loading || loadData}>
        <List
          itemLayout="horizontal"
          dataSource={mandateListShow}
          renderItem={buildTaskList}
          loadMore={loadMoreMandate}
        />
      </Spin>
    </PageContent>
  );
};
export default connect(
  ({
    taskUser,
    mandate,
    loading,
  }: any): {
    userList: IUserType[];
    loading: boolean;
  } => {
    return {
      userList: taskUser.userList,
      loading: loading.models['taskUser'],
    };
  },
)(TaskList);
