import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import ScrollLoading from '@/components/ScrollLoading';
import TopFilter from '@/pages/TaskManage/components/TopFilter';
import {
  MandateClass,
  MandateStatus,
  MandateType,
  OrderStatus,
  OrderType,
} from '@/pages/TaskManage/constent';
import { getMandateList } from '@/services/TaskManage';
import { DownOutlined } from '@ant-design/icons';
import { connect, useLocation, useNavigate, useRequest } from '@umijs/max';
import { Col, Collapse, Divider, List, Row } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import styles from './taskList.less';

const MyTaskList = (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 userID = queryParams.get('user_id');

  const navigate = useNavigate();

  const [currentParams, setCurrentParams] = useState({
    project_id,
    mandate_type: mandateType,
    pageSize: 20,
    currentPage: 1,
    responsible_people: userID !== null ? Number(userID) : '',
  });
  const [pagination, setPagination] = useState({
    current: 1,
    total: 0,
    pageSize: 20,
  });
  const [topFiltersConfig, setTopFiltersConfig] = useState([]);
  const [mandateList, setMandateList] = useState([]);

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

  // 配置顶部下拉过滤器
  useEffect(() => {
    const filters = [];
    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);
  }, [mandateType]);

  const { run: getList, loading: loadData } = useRequest(getMandateList, {
    defaultParams: [currentParams],
    formatResult: (result) => {
      const pageInfo = result.data.pagination;
      if (result.data.pagination.current === 1) {
        setMandateList(result.data.list);
      } else {
        if (mandateList.length < pageInfo.total) {
          setMandateList([...mandateList, ...result.data.list]);
        }
      }
      setPagination(pageInfo);
    },
  });

  const onTopFilterChange = (value) => {
    if (topFiltersConfig.length === 0) {
      return;
    }
    const params = {
      project_id,
      mandate_type: mandateType,
      pageSize: 20,
      currentPage: 1,
    };

    if (userID !== null) {
      params.responsible_people = Number(userID);
    }

    for (let i = 0; i < value.length; i++) {
      if (value[i] !== null && topFiltersConfig[i] !== undefined) {
        params[topFiltersConfig[i].key] = value[i];
      }
    }
    setCurrentParams(params);
    getList(params);
  };

  const goMyTaskDetail = (mandate) => {
    navigate(
      `/center/my-task/task-detail?project_id=${project_id}&mandate_id=${mandate.Id}`,
    );
  };

  const goMyWorkOrder = (orderID, orderType, mandateClass) => {
    if (orderType === undefined) {
      return;
    }
    navigate(
      `/center/my-task/work-order-detail?project_id=${project_id}&order_id=${orderID}&order_type=${orderType}&mandate_class=${mandateClass}`,
    );
  };

  const buildTaskList = (item) => {
    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: dayjs(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: dayjs(record.CreateTime).format('YYYY-MM-DD HH:mm'),
      };
    });

    const collapseData = [
      {
        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.RecordType?.label || '-'}
                  </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={() => {
                  goMyWorkOrder(
                    order.Id,
                    order.RecordType?.value,
                    item.MandateClass,
                  );
                }}
              >
                查看工单
              </div>
            </div>
          );
        }),
      },
    ];

    return (
      <List.Item style={{ borderBottom: '0' }}>
        <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={() => {
                  goMyTaskDetail(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} />

      <ScrollLoading
        height={180}
        loading={loading || loadData}
        pagination={pagination}
        handleLoadData={(current) => {
          getList({ ...currentParams, currentPage: current });
        }}
      >
        <List
          itemLayout="horizontal"
          dataSource={mandateList}
          renderItem={buildTaskList}
        />
      </ScrollLoading>
    </PageContent>
  );
};

export default connect(({ taskUser, loading }) => {
  return {
    userList: taskUser.userList,
    loading: loading.models['taskUser'],
  };
})(MyTaskList);
