import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import { OrderStatus, OrderType } from '@/pages/TaskManage/constent';
import { getUserWorkOrderList } 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 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 userID = queryParams.get('user_id');

  const navigate = useNavigate();

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

  const [activedStatus, setActivedStatus] = useState();

  const [workOrderListDOM, setWorkOrderList] = useState(null);

  const goWorkOrderDetail = (order) => {
    const orderID = order.id || order.Id;
    navigate(
      `/center/my-task/work-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 === 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) => {
      return getUserWorkOrderList({
        project_id,
        work_type: order_type,
        status: status || 0,
        user_id: Number(userID),
      });
    },
    {
      throwOnError: true,
      formatResult: (result) => {
        if (result) {
          const temp = result.map((item) => {
            return {
              ...item,
              CreateTime: item.CreateTime
                ? dayjs(item.CreateTime).format('YYYY-MM-DD HH:mm')
                : '-',
              Repairman: userList.find((user) => item.Responsible === user.ID),
              OrderStatus: OrderStatus.find(
                (status) => status.value === item.Status,
              ),
            };
          });
          renderTabPannal(temp);
        }
      },
    },
  );

  const onTabChange = (key) => {
    setActivedStatus(key);
    getWorkOrderList(Number(key));
  };

  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>
              </Spin>
            </TabPane>
          );
        })}
      </Tabs>
    </PageContent>
  );
};

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