import { TreeSelect } from "antd";
import { useEffect, useMemo } from "react";
import { arrayObjectDeduplication, getDataType, getTreeNodePaths, processTreeDataByLevel, processTreeDataForOnlyLastLevel } from "../../../utils";

/**
 * 基础下拉树组件
 */
function BasicSelectTree(props) {
  const {
    onGetData,
    onChange,
    onGetLabel,
    onGetNodePaths,
    onGetNodePathsIsIncludeOneself,
    getNodePathsIsIncludeOneself = true,
    placeholder = "",
    treeData = [],
    nameKey = "name",
    idKey = "id",
    childrenKey = "children",
    level,
    onlyLastLevel = false,
    ...restProps
  } = props;

  // 如果使用了已弃用的参数给出警告
  if (onGetNodePathsIsIncludeOneself !== undefined) {
    console.warn("【BasicSelectTree】 onGetNodePathsIsIncludeOneself 参数已弃用，请使用 getNodePathsIsIncludeOneself 参数");
  }

  // 向后兼容，如果传入了旧参数，使用旧参数
  const finalGetNodePathsIsIncludeOneself = onGetNodePathsIsIncludeOneself !== undefined ? onGetNodePathsIsIncludeOneself : getNodePathsIsIncludeOneself;

  const processedTreeData = useMemo(() => {
    // 根据 level 处理树数据
    let result = level
      ? processTreeDataByLevel({
          data: treeData,
          level,
          childrenKey,
          currentLevel: 1,
        })
      : treeData;

    // 根据 onlyLastLevel 处理树数据
    result = processTreeDataForOnlyLastLevel({
      data: result,
      childrenKey,
      onlyLastLevel,
    });

    return result;
  }, [treeData, level, childrenKey, onlyLastLevel]);

  const handleChange = (value, label, extra) => {
    if (value) {
      if (getDataType(value) === "Array") {
        if (onGetNodePaths) {
          const parentNodes = [];
          for (let i = 0; i < value.length; i++) {
            const targetId = (restProps.labelInValue || restProps.treeCheckStrictly) ? value[i].value : value[i];
            const currentParentNodes = getTreeNodePaths({
              data: treeData,
              targetId,
              idKey,
              childrenKey,
              isIncludeOneself: finalGetNodePathsIsIncludeOneself,
            });
            parentNodes.push(...currentParentNodes);
          }
          const deduplicationParentNodes = arrayObjectDeduplication(parentNodes, idKey);
          onGetNodePaths?.(deduplicationParentNodes);
        }
        onGetLabel?.((restProps.labelInValue || restProps.treeCheckStrictly) ? value.map(item => item.label) : label);
      }
      else {
        if (onGetNodePaths || onGetLabel) {
          const targetId = (restProps.labelInValue || restProps.treeCheckStrictly) ? value.value : value;
          const parentNodes = getTreeNodePaths({
            data: treeData,
            targetId,
            idKey,
            childrenKey,
            isIncludeOneself: finalGetNodePathsIsIncludeOneself,
          });
          onGetNodePaths?.(parentNodes);
          onGetLabel?.(parentNodes[parentNodes.length - 1][nameKey]);
        }
      }
    }
    else {
      onGetNodePaths?.([]);
      onGetLabel?.("");
    }
    onChange?.((restProps.labelInValue || restProps.treeCheckStrictly) ? value.map(item => item.value) : value, label, extra);
  };

  useEffect(() => {
    onGetData?.(treeData, processedTreeData);
  }, [treeData, processedTreeData]);

  return (
    <TreeSelect
      showSearch
      style={{ width: "100%" }}
      styles={{
        popup: { root: { maxHeight: 400, overflow: "auto" } },
      }}
      placeholder={`请选择${placeholder}`}
      onChange={handleChange}
      allowClear
      treeData={processedTreeData}
      fieldNames={{ label: nameKey, value: idKey, children: childrenKey }}
      treeNodeFilterProp={nameKey}
      showCheckedStrategy={TreeSelect.SHOW_ALL}
      {...restProps}
    />
  );
}

BasicSelectTree.displayName = "BasicSelectTree";

export default BasicSelectTree;
