import PageContent from '@/components/PageContent';
import TabsContent from '@/components/TabsContent';
import styles from '@/pages/TaskManage/index.less';
import { getMandateList } from '@/services/TaskManage';
import { CaretRightFilled } from '@ant-design/icons';
import { connect, useParams } from '@umijs/max';
import { List, Spin } from 'antd';
import { BaseOptionType } from 'rc-select/es/Select';
import { useEffect, useState } from 'react';
import { useNavigate } from 'umi';
import { MandateType, OrderType } from './constent';

const TaskManage = (props) => {
  const { userList, dispatch } = props;
  const { projectID } = useParams();
  const project_id = Number(projectID === '' ? '0' : projectID);

  const navigate = useNavigate();

  const [mandateCount, setMandateCount] = useState<number[]>([0, 0, 0]);
  const [loading, setLoading] = useState(false);
  const [tab, setTab] = useState(localStorage.taskTab || '1');

  useEffect(() => {
    const requests = [];
    for (let i = 0; i < 4; i++) {
      requests.push(
        getMandateList({
          project_id,
          pageSize: 1,
          currentPage: 1,
          mandate_type: i + 1,
        }),
      );
    }
    setLoading(true);
    Promise.all(requests)
      .then((resList) => {
        if (resList.filter((item) => item.code !== 200).length) {
          throw new Error('请求错误');
        }
        const typeCount = [0, 0, 0, 0];
        resList.forEach((item, index) => {
          typeCount[index] = item.data.pagination?.total;
        });
        setMandateCount(typeCount);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

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

  const goTaskList = (item: number) => {
    navigate(`/task-manage/list?project_id=${project_id}&mandateType=${item}`);
  };
  const goWorkOrderList = (item: number) => {
    navigate(
      `/task-manage/work-order/list?project_id=${project_id}&order_type=${item}`,
    );
  };

  const makeTaskList = (item: BaseOptionType, index: number) => {
    return (
      <List.Item
        className={styles.listItem}
        onClick={() => {
          goTaskList(item.value);
        }}
      >
        <List.Item.Meta
          title={<span className={styles.itemLabel}>{item.label}</span>}
        />

        <div className={styles.itemCount}>
          <div className={styles.countNumber}>{mandateCount[index]}</div>
          <div className={styles.counterText}>任务数量</div>
        </div>

        <CaretRightFilled style={{ fontSize: '0.3rem', color: '#BCBABA' }} />
      </List.Item>
    );
  };

  const makeWorkOrderList = (item: BaseOptionType) => {
    return (
      <List.Item
        className={styles.listItem}
        onClick={() => {
          goWorkOrderList(item.value);
        }}
      >
        <List.Item.Meta
          title={<span className={styles.itemLabel}>{item.label}</span>}
        />
        <CaretRightFilled style={{ fontSize: '0.3rem', color: '#BCBABA' }} />
      </List.Item>
    );
  };

  const onTabChange = (key: string) => {
    setTab(key);
    localStorage.setItem('taskTab', key);
  };

  return (
    <PageContent tabs>
      <TabsContent
        defaultActiveKey={tab}
        onChange={onTabChange}
        items={[
          {
            label: `任务管理`,
            key: '1',
            children: (
              <div className={styles.container}>
                <Spin spinning={loading}>
                  <List
                    className={styles.taskList}
                    bordered
                    itemLayout="horizontal"
                    dataSource={MandateType}
                    renderItem={makeTaskList}
                    pagination={false}
                  />
                </Spin>
              </div>
            ),
          },
          {
            label: `工单管理`,
            key: '2',
            children: (
              <div className={styles.container}>
                <Spin spinning={loading}>
                  <List
                    className={styles.taskList}
                    bordered
                    itemLayout="horizontal"
                    dataSource={OrderType}
                    renderItem={makeWorkOrderList}
                    pagination={false}
                  />
                </Spin>
              </div>
            ),
          },
        ]}
      />
    </PageContent>
  );
};

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