import {
  dispatchOrder,
  ignoreTaskRequest,
  setTaskAutomation,
} from '@/services/TaskManage';
import { UnityAction } from '@/utils/utils';
import { CloseOutlined } from '@ant-design/icons';
import { connect, useLocation, useParams, useRequest } from '@umijs/max';
import { Button, Divider, Tabs } from 'antd';
import { useEffect, useState } from 'react';
import MandateDetail from '../components/MandateDetail';
import styles from './index.less';

const TaskModal = (props) => {
  const { projectID } = useParams();
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);

  const mandateIDs =
    queryParams.get('mandate_id')?.split(',').length === 1
      ? queryParams.get('mandate_id')
      : queryParams.get('mandate_id')?.split(',');

  const { userList, dispatch } = props;

  const [modalTitle, setModalTitle] = useState(null);
  const [tabItems, setTabItems] = useState([]);
  const [activeKey, setActiveKey] = useState();

  const { run: runIgnore } = useRequest(ignoreTaskRequest, {
    manual: true,
  });

  const { run: runDispatch } = useRequest(dispatchOrder, {
    manual: true,
  });

  const { run: runAutomate } = useRequest(setTaskAutomation, {
    manual: true,
  });

  const onTabChange = (key) => {
    setActiveKey(String(key));
  };

  const closePage = () => {
    // send message to unity close this modal page
    UnityAction.sendMsg('CloseTask');
  };
  // 忽略
  const onIgnoreTaskConfirm = async (mandateID, reason) => {
    const params = {
      Id: mandateID,
      Status: 4,
      note: reason,
    };
    const result = await runIgnore(params);
    if (result) {
      return true;
    }
  };
  // 派单
  const onDispatchTaskConfirm = async (params) => {
    const result = await runDispatch(params);
    if (result) {
      return true;
    }
  };
  // 自动处理
  const onAutoHandleTaskConfirm = async (pw, mandate) => {
    console.log(mandate);
    const params = {
      mandate_id: mandate.Id,
      pw,
    };
    const result = runAutomate(params, mandate);
    if (result) {
      return true;
    }
  };

  useEffect(() => {
    if (mandateIDs !== undefined) {
      if (Array.isArray(mandateIDs)) {
        setModalTitle(null);
        setTabItems(
          mandateIDs.map((item, index) => {
            return {
              key: String(item),
              label: <span className={styles.fontS28}>任务{index + 1}</span>,
              children: (
                <MandateDetail
                  key={item}
                  mandateID={item}
                  userList={userList}
                  projectID={projectID}
                  ignoreTask={onIgnoreTaskConfirm}
                  dispatchTask={onDispatchTaskConfirm}
                  autoHandleTask={onAutoHandleTaskConfirm}
                />
              ),
            };
          }),
        );
      } else {
        setModalTitle(<div className={styles.modalTitle}>任务详情</div>);
      }
    }
  }, []);

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

  return (
    <div className={styles.modalContainer}>
      <Button
        className={styles.closeModalBtn}
        type="text"
        icon={<CloseOutlined style={{ fontSize: '28px' }} />}
        onClick={closePage}
      />

      {mandateIDs && Array.isArray(mandateIDs) ? (
        <Tabs
          defaultActiveKey={String(mandateIDs[0])}
          activeKey={activeKey}
          items={tabItems}
          onChange={onTabChange}
        />
      ) : (
        <>
          {modalTitle}
          <Divider style={{ margin: '10px 0' }} />
          <MandateDetail
            mandateID={mandateIDs}
            userList={userList}
            projectID={projectID}
            ignoreTask={onIgnoreTaskConfirm}
            dispatchTask={onDispatchTaskConfirm}
            autoHandleTask={onAutoHandleTaskConfirm}
          />
        </>
      )}
    </div>
  );
};

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