import { Cascader } from "antd";
import { useEffect, useMemo } from "react";
import { processTreeDataByLevel } from "../../../utils";

/**
 * 基础级联组件
 */
function BasicCascader(props) {
  const {
    onGetData,
    onChange,
    onGetNodePaths,
    onGetNodePathsIsIncludeOneself,
    getNodePathsIsIncludeOneself = true,
    placeholder = "",
    data = [],
    nameKey = "name",
    idKey = "id",
    childrenKey = "children",
    level,
    ...restProps
  } = props;

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

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

  // 根据 level 处理树数据
  const processedData = useMemo(() => {
    return level
      ? processTreeDataByLevel({
          data,
          level,
          childrenKey,
          currentLevel: 1,
        })
      : data;
  }, [data, level, childrenKey]);

  const getNodePaths = (selectedOptions) => {
    let nodePaths = selectedOptions;
    if (!finalGetNodePathsIsIncludeOneself && selectedOptions) {
      nodePaths = selectedOptions.slice(0, -1);
    }
    return nodePaths || [];
  };

  const handleChange = (value, selectedOptions) => {
    if (selectedOptions && onGetNodePaths) {
      const parentNodes = getNodePaths(selectedOptions);
      onGetNodePaths?.(parentNodes);
    }
    onChange?.(value, selectedOptions);
  };

  const handleClear = () => {
    onGetNodePaths?.([]);
  };

  useEffect(() => {
    onGetData?.(data, processedData);
  }, [data, processedData]);

  return (
    <Cascader
      options={processedData}
      placeholder={`请选择${placeholder}`}
      onChange={handleChange}
      onClear={handleClear}
      fieldNames={{ label: nameKey, value: idKey, children: childrenKey }}
      {...restProps}
    />
  );
}

BasicCascader.displayName = "BasicCascader";

export default BasicCascader;
