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

/**
 * 隐患级别下拉树组件（港务局版本）
 */
function HiddenLevelSelectTree(props) {
  const {
    isShowNeglect = true,
    isShowLarger = true,
    isShowMajor = true,
    ...restProps
  } = props;

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

  // 过滤隐患级别的树数据
  const filterTreeData = (treeData) => {
    // 隐患级别的特定ID
    const HIDDEN_LEVEL_IDS = {
      neglect: "hiddenLevel1001", // 忽略隐患
      larger: "jdyh001", // 较大隐患
      major: "hiddenLevel0002", // 重大隐患
    };

    // 递归过滤树数据
    const filterTree = (nodes) => {
      if (!nodes || !Array.isArray(nodes))
        return [];

      return nodes.filter((node) => {
        // 根据不同的ID和对应的props来决定是否显示
        if (node.dictValue === HIDDEN_LEVEL_IDS.neglect)
          return isShowNeglect;
        if (node.dictValue === HIDDEN_LEVEL_IDS.larger)
          return isShowLarger;
        if (node.dictValue === HIDDEN_LEVEL_IDS.major)
          return isShowMajor;

        // 如果有子节点，递归过滤子节点
        if (node.children && node.children.length > 0)
          node.children = filterTree(node.children);

        // 默认显示其他节点
        return true;
      });
    };

    return filterTree(treeData);
  };

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

    const { data } = await request("/config/dict-trees/list/by/dictValues", "get", { appKey: DICTIONARY_APP_KEY_ENUM.GWJ, dictValue: "hiddenLevel" });
    const filterData = filterTreeData(data);
    setTreeData(filterData);
  };

  useEffect(() => {
    getData();
  }, []);

  return (
    <BasicSelectTree treeData={treeData} placeholder="隐患级别" onlyLastLevel={true} nameKey="dictLabel" idKey="dictValue" {...restProps} />
  );
}

HiddenLevelSelectTree.displayName = "HiddenLevelSelectTree";

export default HiddenLevelSelectTree;
