import { request } from "@cqsjjb/jjb-common-lib/http.js";
import { useEffect, useState } from "react";
import BasicSelect from "../../Basic";

// 全局缓存
const cacheMap = new Map();

/**
 * 人员下拉组件（港务局版本）
 */
function PersonnelSelect(props) {
  const {
    params = {},
    placeholder = "人员",
    isNeedCorpInfoId = false,
    isNeedDepartmentId = true,
    isNeedPostId = false,
    extraParams = {},
    ...restProps
  } = props;

  const defaultExtraParams = {
    noMain: "",
    eqEmploymentFlag: 1,
  };

  const [data, setData] = useState([]);

  const getData = async () => {
    setData([]);

    if (!isNeedCorpInfoId && !isNeedDepartmentId && !isNeedPostId) {
      console.error("【PersonnelSelect】 请至少传入一个参数");
      return;
    }

    // 根据参数决定是否发送请求
    if (isNeedCorpInfoId && (!params.corpinfoId || typeof params.corpinfoId !== "string"))
      return;
    if (isNeedDepartmentId && (!params.departmentId || typeof params.departmentId !== "string"))
      return;
    if (isNeedPostId && (!params.postId || typeof params.postId !== "string"))
      return;

    const actualExtraParams = { ...defaultExtraParams, ...extraParams };

    // 生成缓存键
    const cacheKey = JSON.stringify({ params, extraParams: actualExtraParams });

    // 检查缓存，如果存在直接返回缓存结果
    if (cacheMap.has(cacheKey)) {
      setData(cacheMap.get(cacheKey));
      return;
    }

    const { data } = await request("/basicInfo/user/listAll", "get", { ...params, ...actualExtraParams, time: new Date().getTime() });

    // 存入缓存
    cacheMap.set(cacheKey, data);

    setData(data);
  };

  useEffect(() => {
    getData();
  }, [JSON.stringify(params), isNeedCorpInfoId, isNeedDepartmentId, isNeedPostId, JSON.stringify(extraParams)]);

  return (
    <BasicSelect data={data} placeholder={placeholder} {...restProps} />
  );
}

PersonnelSelect.displayName = "PersonnelSelect";

export default PersonnelSelect;
