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 { CaretDownFilled } from '@ant-design/icons';
import {
  Col,
  Collapse,
  CollapseProps,
  Form,
  Input,
  List,
  Modal,
  Row,
  message,
} from 'antd';

import ScrollLoading from '@/components/ScrollLoading';
import { getMandateList, withdrawOrderRequest } from '@/services/TaskManage';
import dayjs from 'dayjs';
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 [topFiltersConfig, setTopFiltersConfig] = useState<ITopFilter[]>([]);
  const [mandateList, setMandateList] = useState<IMandateType[]>([]);
  const [currentParams, setCurrentParams] = useState({
    project_id,
    mandate_type: mandateType,
    pageSize: 20,
    currentPage: 1,
  });
  const [pagination, setPagination] = useState({
    current: 1,
    total: 0,
    pageSize: 20,
  });
  const [withdrawOrderOpen, setWithdrawOrderOpen] = useState(false);
  const [clickedOrder, setClickedOrder] = useState({});
  const [withdrawReason, setWithdrawReason] = useState('');

  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);
    },
  });

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

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

  /**
   * 处理选择器变化
   * @param value 选择的值，当清空时等于null
   */
  const onTopFilterChange = (value: any) => {
    if (topFiltersConfig.length === 0) {
      return;
    }
    const params: any = {
      project_id,
      mandate_type: mandateType,
      pageSize: 20,
      currentPage: 1,
    };

    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 goTaskDetail = (mandate: IMandateType) => {
    navigate(
      `/task-manage/list/detail?project_id=${project_id}&mandate_id=${mandate.Id}`,
    );
  };

  const goTaskOrder = (
    orderID: number,
    orderType: number | undefined,
    mandateClass: number,
  ) => {
    if (orderType === undefined) {
      return;
    }
    navigate(
      `/task-manage/list/order-detail?project_id=${project_id}&order_id=${orderID}&order_type=${orderType}&mandate_class=${mandateClass}`,
    );
  };

  const withdrawOrder = (order: any) => {
    setWithdrawOrderOpen(true);
    setClickedOrder(order);
  };

  const withdrawOrderConfirm = async () => {
    if (!withdrawReason) {
      message.warning('请输入关闭理由');
      return;
    }
    const res = await withdrawOrderRequest({
      record_id: clickedOrder.Id,
      note: withdrawReason,
      type: clickedOrder.RecordType.value,
    });
    if (res.code === 200) {
      message.success('关闭工单成功');
      setClickedOrder({});
      setWithdrawOrderOpen(false);
      getList(currentParams);
    }
  };

  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: 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: CollapseProps['items'] = [
      {
        key: '1',
        label: (
          <span style={{ color: '#ffffff', marginRight: '0.05rem' }}>
            关联工单({workOrder.length})
          </span>
        ),
        children: workOrder.map((order) => {
          return (
            <div key={order.Id} className={styles.workOrderCard}>
              <div className={styles.leftInfo}>
                <Row style={{ marginBottom: '0.15rem' }}>
                  <Col className={styles.fontS30} span={11}>
                    工单类型：{order.RecordType?.label || '-'}
                  </Col>
                  <Col className={styles.fontS30} span={13}>
                    时间：{order.CreateTime}
                  </Col>
                </Row>
                <Row>
                  <Col className={styles.fontS30} span={11}>
                    工单状态：
                    <span style={{ color: '#5697e4' }}>
                      {order.Status?.label}
                    </span>
                  </Col>
                  <Col className={styles.fontS30} span={13}>
                    工单负责人：{order.Responsible?.CName}
                  </Col>
                </Row>
              </div>
              <div className={styles.rightButtonContainer}>
                <div
                  className={styles.rightButton}
                  style={{
                    marginBottom: `${
                      order.Status?.value === 0 ? '0.15rem' : '0'
                    }`,
                  }}
                  onClick={() => {
                    goTaskOrder(
                      order.Id,
                      order.RecordType?.value,
                      item.MandateClass,
                    );
                  }}
                >
                  查看
                </div>
                {order.Status?.value === 0 && (
                  <div
                    className={styles.rightButton}
                    onClick={() => {
                      withdrawOrder(order);
                    }}
                  >
                    关闭
                  </div>
                )}
              </div>
            </div>
          );
        }),
      },
    ];

    return (
      <List.Item style={{ borderBottom: '0' }}>
        <div className={`${styles.cardContainer} `}>
          <span
            style={{
              width: '0.2rem',
              height: '2.05rem',
              position: 'absolute',
              background: 'rgba(23, 85, 255, 0.20)',
            }}
          />
          <div className={styles.cardInfo}>
            <Row
              justify="start"
              style={{
                padding: '0.2rem 0.2rem 0 0.4rem',
                maxHeight: '0.7rem',
              }}
            >
              <Col span={11} className={styles.fontS30}>
                时间: {formatItem.CreateTime}
              </Col>
              <Col className={styles.fontS30}>
                任务类别: {formatItem.MandateClass?.label}
              </Col>
            </Row>
            <Row
              justify="start"
              style={{
                padding: '0.2rem 0.2rem 0 0.4rem',
                maxHeight: '0.75rem',
              }}
            >
              <Col span={11} className={styles.fontS30}>
                任务负责人: {formatItem.ResponsiblePeople?.CName || '-'}
              </Col>
              <Col span={8} className={styles.fontS30}>
                任务状态: {formatItem.Status?.label || '-'}
              </Col>
              <Col>
                <div
                  className={styles.fontS28}
                  style={{
                    backgroundColor: '#f5a623',
                    color: 'white',
                    width: '1.7rem',
                    letterSpacing: '0.025rem',
                    height: '0.55rem',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    borderRadius: '0.5rem',
                  }}
                  onClick={() => {
                    goTaskDetail(item);
                  }}
                >
                  任务详情
                </div>
              </Col>
            </Row>
            <Row>
              <Collapse
                className={styles.collapseLabel}
                ghost
                expandIcon={({ isActive }) => (
                  <CaretDownFilled
                    style={{ color: '#ffffff' }}
                    rotate={isActive ? 180 : 0}
                  />
                )}
                items={collapseData}
              />
            </Row>
          </div>
        </div>
      </List.Item>
    );
  };

  return (
    <PageContent closeable={false}>
      <PageTitle returnable>
        {MandateType.find((item) => item.value === mandateType)?.label}
      </PageTitle>
      <TopFilter filters={topFiltersConfig} onChange={onTopFilterChange} />

      <ScrollLoading
        height={190}
        loading={loading || loadData}
        pagination={pagination}
        handleLoadData={(current: number) =>
          getList({ ...currentParams, currentPage: current })
        }
      >
        <List
          itemLayout="horizontal"
          dataSource={mandateList}
          renderItem={buildTaskList}
        />
      </ScrollLoading>
      <Modal
        className={styles.handleModal}
        title="关闭工单"
        open={withdrawOrderOpen}
        onCancel={() => {
          setWithdrawOrderOpen(false);
        }}
        onOk={withdrawOrderConfirm}
      >
        <Form>
          <Form.Item label="关闭原因">
            <Input
              onChange={(e) => {
                setWithdrawReason(e.target.value);
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </PageContent>
  );
};
export default connect(
  ({
    taskUser,
    loading,
  }: any): {
    userList: IUserType[];
    loading: boolean;
  } => {
    return {
      userList: taskUser.userList,
      loading: loading.models['taskUser'],
    };
  },
)(TaskList);
