/* eslint-disable react/destructuring-assignment */
import React from "react";
import { CascaderSingle } from "./CascaderSingle";
import { CascaderMultiple } from "./CascaderMultiple";
import {
  CascaderProps,
  CascaderData,
  CascaderMenuOption,
} from "./CascaderProps";
import { forwardRefWithStatics } from "../_util/forward-ref-with-statics";
import { deepCopy } from "../_util/deep-copy";

function isCascaderData(data: any): data is CascaderData {
  return !Array.isArray(data) && typeof data === "object";
}

export function transformData(
  data: CascaderData | CascaderMenuOption[]
): CascaderData {
  const result: CascaderData = isCascaderData(data)
    ? data
    : { title: "", options: data };
  if (result.options) {
    result.options = result.options.map(option => {
      if (option.child || (option as CascaderMenuOption).children) {
        option.child = transformData(
          (option as CascaderMenuOption).children || option.child
        );
      }
      // 兼容菜单模式动态加载
      if (!option.child && (option as CascaderMenuOption).isLeaf === false) {
        option.child = { title: "" };
      }
      return option;
    });
  }
  return result;
}

export const Cascader = forwardRefWithStatics(
  function Cascader(props: CascaderProps, ref: React.Ref<HTMLDivElement>) {
    if (props.multiple) {
      return (
        <CascaderMultiple
          ref={ref}
          {...props}
          data={transformData(deepCopy(props.data))}
          multiple
        />
      );
    }

    return (
      <CascaderSingle
        ref={ref}
        {...(props as any)}
        data={transformData(deepCopy(props.data))}
      />
    );
  },
  {
    defaultLabelAlign: "middle",
  }
);

Cascader.displayName = "Cascader";
