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

/**
 * 部门下拉树组件（港务局版本）
 */
function DepartmentSelectTree(props) {
  const {
    params = {},
    placeholder = "部门",
    isNeedCorpInfoId = false,
    isNeedParentId = false,
    searchType = "current",
    ...restProps
  } = props;

  const [treeData, setTreeData] = useState([]);

  const getData = async () => {
    if (searchType === "current") {
      if (isNeedCorpInfoId && !params.eqCorpinfoId)
        return;
      if (isNeedParentId && !params.eqParentId)
        return;
    }

    let requestUrl = "";
    const actualParams = { ...params, time: new Date().getTime() };
    if (searchType === "current") {
      requestUrl = `/${getBaseGateway()}/department/listTree`;
      delete actualParams.inType;
      delete actualParams.enterpriseType;
    }
    if (searchType === "all") {
      requestUrl = `/${getBaseGateway()}/department/listAllTree`;
      delete actualParams.inType;
      delete actualParams.enterpriseType;
      delete actualParams.eqCorpinfoId;
      delete actualParams.eqParentId;
    }
    if (searchType === "inType") {
      requestUrl = `/${getBaseGateway()}/department/listAllTreeByCorpType`;
      delete actualParams.eqCorpinfoId;
      delete actualParams.eqParentId;
      if (actualParams.enterpriseType && !Array.isArray(actualParams.enterpriseType)) {
        actualParams.enterpriseType = [actualParams.enterpriseType];
      }
    }

    const cacheKey = { searchType, params };

    await executeWithCache(cacheKey, async () => {
      const { data } = await request(requestUrl, "post", actualParams);
      return data;
    }, setTreeData);
  };

  useEffect(() => {
    getData();
  }, [JSON.stringify(params), isNeedCorpInfoId, isNeedParentId, searchType]);

  return (
    <BasicSelectTree treeData={treeData} placeholder={placeholder} childrenKey="childrenList" {...restProps} />
  );
}

DepartmentSelectTree.displayName = "DepartmentSelectTree";

export default DepartmentSelectTree;
