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

/**
 * 基础级联组件（不建议直接使用此组件，二次继承使用）
 */
function BasicCascader(props) {
  const {
    onGetData,
    onChange,
    onGetNodePaths,
    onGetNodePathsIsIncludeOneself = true,
    placeholder = "",
    data = [],
    nameKey = "name",
    idKey = "id",
    childrenKey = "children",
    level,
    ...restProps
  } = props;

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

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

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

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

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

BasicCascader.displayName = "BasicCascader";

export default BasicCascader;
