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

/**
 * 人员下拉组件（港务局版本）
 */
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 () => {
    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 = { params, extraParams: actualExtraParams };

    await executeWithCache(cacheKey, async () => {
      const { data } = await request(`/${getBaseGateway()}/user/listAll`, "get", { ...params, ...actualExtraParams, time: new Date().getTime() });
      return data;
    }, setData);
  };

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

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

PersonnelSelect.displayName = "PersonnelSelect";

export default PersonnelSelect;
