import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import {
  getCraftRecordList,
  getMaintainRecordList,
  getPatrolMandateRecord,
  getReagentOrderList,
  getRepairRecordList,
} from '@/services/TaskManage';
import { connect, useLocation, useNavigate, useRequest } from '@umijs/max';
import { Button, Col, Empty, Row, Spin, Tabs } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { OrderStatus, OrderType } from '../../constent';
import styles from './WorkOrderList.less';

const { TabPane } = Tabs;

const WorkOrderList = (props) => {
  const { userList, dispatch } = props;
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const project_id = Number(queryParams.get('project_id'));
  const order_type = Number(queryParams.get('order_type'));

  const navigate = useNavigate();

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

  const [activedStatus, setActivedStatus] = useState();
  const [pagination, setPagination] = useState({
    pageSize: 20,
    currentPage: 1,
    total: 0,
  });
  const [recordList, setRecordList] = useState([]);
  const [workOrderListDOM, setWorkOrderList] = useState(null);

  const goWorkOrderDetail = (order) => {
    const orderID = order.id || order.Id;
    navigate(
      `/task-manage/list/order-detail?project_id=${project_id}&order_id=${orderID}&order_type=${order_type}`,
    );
  };

  const renderTabPannal = (list) => {
    if (list?.length === 0) {
      setWorkOrderList(<Empty />);
      return;
    }
    const tempNode = list.map((workOrder) => {
      return (
        <div
          key={workOrder.id || workOrder.Id}
          className={styles.workOrderCard}
        >
          <Row justify="space-between" style={{ marginBottom: '20px' }}>
            <Col className={styles.fontS24}>{workOrder?.CreateTime}</Col>
            <Col className={styles.fontS24}>
              工单负责人：{workOrder?.Repairman?.CName || '-'}
            </Col>
          </Row>
          <Row justify="space-between">
            <Col className={styles.fontS24}>
              工单状态：{workOrder?.OrderStatus?.label}
            </Col>
            <Col className={styles.detailBtnContainer}>
              <Button
                type="primary"
                style={{ height: '40px', fontSize: '24px' }}
                onClick={() => goWorkOrderDetail(workOrder)}
              >
                工单详情
              </Button>
            </Col>
          </Row>
        </div>
      );
    });
    setWorkOrderList(tempNode);
  };

  const formatCreateTime = (order) => {
    if (order_type === 1 || order_type === 6 || order_type === 7) {
      if (order?.start_time) {
        return dayjs(order.start_time).format('YYYY-MM-DD HH:mm');
      }
    } else if (order_type === 2 || order_type === 3) {
      if (order?.CreateTime) {
        return dayjs(order.CreateTime).format('YYYY-MM-DD HH:mm');
      }
    } else if (order_type === 4) {
      if (order?.CreatedTime) {
        return dayjs(order.CreatedTime).format('YYYY-MM-DD HH:mm');
      }
    } else if (order_type === 5) {
      if (order?.start_time?.Valid) {
        return dayjs(order.start_time.Time).format('YYYY-MM-DD HH:mm');
      }
    }
    return '-';
  };

  const { run: getWorkOrderList, loading } = useRequest(
    (status, pageInfo) => {
      switch (order_type) {
        case 1:
        case 6:
        case 7:
          return getCraftRecordList({
            project_id,
            status: status || 0,
            types: order_type === 1 ? 0 : order_type === 6 ? 1 : 2,
            pageSize: pageInfo?.pageSize || pagination.pageSize,
            currentPage: pageInfo?.currentPage || pagination.currentPage,
          });
        case 2:
          return getRepairRecordList({
            project_id,
            acceptanceStatus: status || 0,
            pageSize: pageInfo?.pageSize || pagination.pageSize,
            currentPage: pageInfo?.currentPage || pagination.currentPage,
          });
        case 3:
          return getMaintainRecordList({
            project_id,
            status: status || 0,
            pageSize: pageInfo?.pageSize || pagination.pageSize,
            currentPage: pageInfo?.currentPage || pagination.currentPage,
          });
        case 4:
          return getPatrolMandateRecord({
            project_id,
            status: status || 0,
            pageSize: pageInfo?.pageSize || pagination.pageSize,
            currentPage: pageInfo?.currentPage || pagination.currentPage,
          });
        case 5:
          return getReagentOrderList({
            project_id,
            status: status || 0,
            pageSize: pageInfo?.pageSize || pagination.pageSize,
            currentPage: pageInfo?.currentPage || pagination.currentPage,
          });
      }
    },
    {
      throwOnError: true,
      formatResult: (result) => {
        let temp = [];
        if (result?.data?.list) {
          temp = result.data.list.map((item) => {
            return {
              ...item,
              CreateTime: formatCreateTime(item),
              Repairman: userList.find((user) => {
                let temp = -1;
                if (order_type === 2) {
                  temp = item.Repairman;
                } else if (order_type === 3) {
                  temp = item.MaintenancePerson;
                } else if (order_type === 4) {
                  temp = '-';
                } else if (order_type === 5) {
                  temp = '-';
                } else {
                  temp = item.operator_id;
                }
                return temp === user.ID;
              }),
              OrderStatus: OrderStatus.find((status) => {
                let temp = -1;
                if (order_type === 2) {
                  temp = item.AcceptanceStatus;
                } else if (order_type === 3) {
                  temp = item.Status;
                } else {
                  temp = item.status;
                }
                return status.value === temp;
              }),
            };
          });
        }

        if (result?.data?.pagination) {
          const tempPageInfo = {
            pageSize:
              result.data.pagination?.PageSize ||
              result.data.pagination?.pageSize,
            current:
              result.data.pagination?.Current ||
              result.data.pagination?.current,
            total:
              result.data.pagination?.Total || result.data.pagination?.total,
          };
          if (tempPageInfo.current === 1) {
            setRecordList(temp);
          } else {
            setRecordList([...recordList, ...temp]);
          }

          if ([...recordList, ...temp].length < tempPageInfo.total) {
            tempPageInfo.current++;
          }

          setPagination({
            pageSize: tempPageInfo.pageSize,
            currentPage: tempPageInfo.current,
            total: tempPageInfo.total,
          });
        }
      },
    },
  );

  useEffect(() => {
    renderTabPannal(recordList);
  }, [recordList]);

  const onTabChange = (key) => {
    setActivedStatus(key);
    setRecordList([]);
    setPagination({ pageSize: 20, currentPage: 1, total: 0 });
    getWorkOrderList(Number(key), { pageSize: 20, currentPage: 1, total: 0 });
  };

  return (
    <PageContent closeable={false}>
      <PageTitle returnable>
        {OrderType.find((item) => item.value === order_type)?.label || ''}
      </PageTitle>
      <Tabs
        size="large"
        activeKey={activedStatus}
        defaultActiveKey={String(OrderStatus[0].value)}
        className={styles.identifyTab}
        onChange={onTabChange}
      >
        {OrderStatus.map((item) => {
          return (
            <TabPane tab={item.label} key={String(item.value)}>
              <Spin spinning={loading}>
                <div
                  style={{ height: 'calc(100vh - 180px)', overflowY: 'auto' }}
                >
                  {workOrderListDOM}
                  <div className={styles.loadMoreBtn}>
                    {recordList.length < pagination.total && (
                      <Button
                        style={{ fontSize: '24px' }}
                        type="link"
                        onClick={() => {
                          getWorkOrderList(activedStatus);
                        }}
                      >
                        加载更多
                      </Button>
                    )}
                  </div>
                </div>
              </Spin>
            </TabPane>
          );
        })}
      </Tabs>
    </PageContent>
  );
};

export default connect(({ taskUser }) => {
  return {
    userList: taskUser.userList,
  };
})(WorkOrderList);
