import { defineComponent, toRef, computed, ref, watchEffect, toRefs, createVNode } from 'vue';
import '../../../utils/index.mjs';
import '../../../hooks/index.mjs';
import BaseSelect, { baseSelectPropsWithoutPrivate } from '../../vc-select/src/BaseSelect.mjs';
import useId from '../../vc-select/src/hooks/useId.mjs';
import { conductCheck } from '../../vc-tree/src/utils/conductUtil.mjs';
import useMaxLevel from '../../vc-tree/src/useMaxLevel.mjs';
import { SHOW_PARENT, fillFieldNames, toPathKeys, toPathKey } from './utils/commonUtil.mjs';
export { SHOW_CHILD } from './utils/commonUtil.mjs';
import useEntities from './hooks/useEntities.mjs';
import useSearchConfig from './hooks/useSearchConfig.mjs';
import useSearchOptions from './hooks/useSearchOptions.mjs';
import useMissingValues from './hooks/useMissingValues.mjs';
import { formatStrategyValues, toPathOptions } from './utils/treeUtil.mjs';
import useDisplayValues from './hooks/useDisplayValues.mjs';
import { useProvideCascader } from './context.mjs';
import OptionList from './OptionList/index.mjs';
import { omit } from '../../../utils/lang/omit.mjs';
import { objectType } from '../../../utils/vue/propType.mjs';
import PropTypes from '../../../utils/vue/vueTypes.mjs';
import { initDefaultProps } from '../../../utils/vue/initDefaultProps.mjs';
import { useMergedState } from '../../../hooks/use-merged-state/index.mjs';
import { devWarning } from '../../../utils/log.mjs';

function baseCascaderProps() {
  return {
    ...omit(baseSelectPropsWithoutPrivate(), ["tokenSeparators", "mode", "showSearch"]),
    // MISC
    id: String,
    prefixCls: String,
    fieldNames: objectType(),
    children: Array,
    // Value
    value: {
      type: [String, Number, Array]
    },
    defaultValue: {
      type: [String, Number, Array]
    },
    changeOnSelect: {
      type: Boolean,
      default: void 0
    },
    displayRender: Function,
    checkable: {
      type: Boolean,
      default: void 0
    },
    showCheckedStrategy: {
      type: String,
      default: SHOW_PARENT
    },
    // Search
    showSearch: {
      type: [Boolean, Object],
      default: void 0
    },
    searchValue: String,
    onSearch: Function,
    // Trigger
    expandTrigger: String,
    // Options
    options: Array,
    /** @private Internal usage. Do not use in your production. */
    dropdownPrefixCls: String,
    loadData: Function,
    // Open
    /** @deprecated Use `open` instead */
    popupVisible: {
      type: Boolean,
      default: void 0
    },
    /** @deprecated Use `dropdownClassName` instead */
    popupClassName: String,
    dropdownClassName: String,
    dropdownMenuColumnStyle: {
      type: Object,
      default: void 0
    },
    /** @deprecated Use `dropdownStyle` instead */
    popupStyle: {
      type: Object,
      default: void 0
    },
    dropdownStyle: {
      type: Object,
      default: void 0
    },
    /** @deprecated Use `placement` instead */
    popupPlacement: String,
    placement: String,
    /** @deprecated Use `onDropdownVisibleChange` instead */
    onPopupVisibleChange: Function,
    onDropdownVisibleChange: Function,
    // Icon
    expandIcon: PropTypes.any,
    loadingIcon: PropTypes.any
  };
}
function singleCascaderProps() {
  return {
    ...baseCascaderProps(),
    checkable: Boolean,
    onChange: Function
  };
}
function multipleCascaderProps() {
  return {
    ...baseCascaderProps(),
    checkable: Boolean,
    onChange: Function
  };
}
function internalCascaderProps() {
  return {
    ...baseCascaderProps(),
    onChange: Function,
    customSlots: Object
  };
}
function isMultipleValue(value) {
  return Array.isArray(value) && Array.isArray(value[0]);
}
function toRawValues(value) {
  if (!value)
    return [];
  if (isMultipleValue(value))
    return value;
  return (value.length === 0 ? [] : [value]).map((val) => Array.isArray(val) ? val : [val]);
}
var VcCascader = /* @__PURE__ */ defineComponent({
  compatConfig: {
    MODE: 3
  },
  name: "Cascader",
  inheritAttrs: false,
  props: initDefaultProps(internalCascaderProps(), {}),
  setup(props, {
    attrs,
    expose,
    slots
  }) {
    const mergedId = useId(toRef(props, "id"));
    const multiple = computed(() => !!props.checkable);
    const [rawValues, setRawValues] = useMergedState(props.defaultValue, {
      value: computed(() => props.value),
      postState: toRawValues
    });
    const mergedFieldNames = computed(() => fillFieldNames(props.fieldNames));
    const mergedOptions = computed(() => props.options || []);
    const pathKeyEntities = useEntities(mergedOptions, mergedFieldNames);
    const getValueByKeyPath = (pathKeys) => {
      const keyPathEntities = pathKeyEntities.value;
      return pathKeys.map((pathKey) => {
        const {
          nodes
        } = keyPathEntities[pathKey];
        return nodes.map((node) => node[mergedFieldNames.value.value]);
      });
    };
    const [mergedSearchValue, setSearchValue] = useMergedState("", {
      value: computed(() => props.searchValue),
      postState: (search) => search || ""
    });
    const onInternalSearch = (searchText, info) => {
      setSearchValue(searchText);
      if (info.source !== "blur" && props.onSearch)
        props.onSearch(searchText);
    };
    const {
      showSearch: mergedShowSearch,
      searchConfig: mergedSearchConfig
    } = useSearchConfig(toRef(props, "showSearch"));
    const searchOptions = useSearchOptions(mergedSearchValue, mergedOptions, mergedFieldNames, computed(() => props.dropdownPrefixCls || props.prefixCls), mergedSearchConfig, toRef(props, "changeOnSelect"));
    const missingValuesInfo = useMissingValues(mergedOptions, mergedFieldNames, rawValues);
    const [checkedValues, halfCheckedValues, missingCheckedValues] = [ref([]), ref([]), ref([])];
    const {
      maxLevel,
      levelEntities
    } = useMaxLevel(pathKeyEntities);
    watchEffect(() => {
      const [existValues, missingValues] = missingValuesInfo.value;
      if (!multiple.value || !rawValues.value.length) {
        [checkedValues.value, halfCheckedValues.value, missingCheckedValues.value] = [existValues, [], missingValues];
        return;
      }
      const keyPathValues = toPathKeys(existValues);
      const keyPathEntities = pathKeyEntities.value;
      const {
        checkedKeys,
        halfCheckedKeys
      } = conductCheck(keyPathValues, true, keyPathEntities, maxLevel.value, levelEntities.value);
      [checkedValues.value, halfCheckedValues.value, missingCheckedValues.value] = [getValueByKeyPath(checkedKeys), getValueByKeyPath(halfCheckedKeys), missingValues];
    });
    const deDuplicatedValues = computed(() => {
      const checkedKeys = toPathKeys(checkedValues.value);
      const deduplicateKeys = formatStrategyValues(checkedKeys, pathKeyEntities.value, props.showCheckedStrategy);
      return [...missingCheckedValues.value, ...getValueByKeyPath(deduplicateKeys)];
    });
    const displayValues = useDisplayValues(deDuplicatedValues, mergedOptions, mergedFieldNames, multiple, toRef(props, "displayRender"));
    const triggerChange = (nextValues) => {
      setRawValues(nextValues);
      if (props.onChange) {
        const nextRawValues = toRawValues(nextValues);
        const valueOptions = nextRawValues.map((valueCells) => toPathOptions(valueCells, mergedOptions.value, mergedFieldNames.value).map((valueOpt) => valueOpt.option));
        const triggerValues = multiple.value ? nextRawValues : nextRawValues[0];
        const triggerOptions = multiple.value ? valueOptions : valueOptions[0];
        props.onChange(triggerValues, triggerOptions);
      }
    };
    const onInternalSelect = (valuePath) => {
      setSearchValue("");
      if (!multiple.value) {
        triggerChange(valuePath);
      } else {
        const pathKey = toPathKey(valuePath);
        const checkedPathKeys = toPathKeys(checkedValues.value);
        const halfCheckedPathKeys = toPathKeys(halfCheckedValues.value);
        const existInChecked = checkedPathKeys.includes(pathKey);
        const existInMissing = missingCheckedValues.value.some((valueCells) => toPathKey(valueCells) === pathKey);
        let nextCheckedValues = checkedValues.value;
        let nextMissingValues = missingCheckedValues.value;
        if (existInMissing && !existInChecked) {
          nextMissingValues = missingCheckedValues.value.filter((valueCells) => toPathKey(valueCells) !== pathKey);
        } else {
          const nextRawCheckedKeys = existInChecked ? checkedPathKeys.filter((key) => key !== pathKey) : [...checkedPathKeys, pathKey];
          let checkedKeys;
          if (existInChecked) {
            ({
              checkedKeys
            } = conductCheck(nextRawCheckedKeys, {
              checked: false,
              halfCheckedKeys: halfCheckedPathKeys
            }, pathKeyEntities.value, maxLevel.value, levelEntities.value));
          } else {
            ({
              checkedKeys
            } = conductCheck(nextRawCheckedKeys, true, pathKeyEntities.value, maxLevel.value, levelEntities.value));
          }
          const deDuplicatedKeys = formatStrategyValues(checkedKeys, pathKeyEntities.value, props.showCheckedStrategy);
          nextCheckedValues = getValueByKeyPath(deDuplicatedKeys);
        }
        triggerChange([...nextMissingValues, ...nextCheckedValues]);
      }
    };
    const onDisplayValuesChange = (_, info) => {
      if (info.type === "clear") {
        triggerChange([]);
        return;
      }
      const {
        valueCells
      } = info.values[0];
      onInternalSelect(valueCells);
    };
    if (process.env.NODE_ENV !== "production") {
      watchEffect(() => {
        devWarning(!props.onPopupVisibleChange, "Cascader", "`popupVisibleChange` is deprecated. Please use `dropdownVisibleChange` instead.");
        devWarning(props.popupVisible === void 0, "Cascader", "`popupVisible` is deprecated. Please use `open` instead.");
        devWarning(props.popupClassName === void 0, "Cascader", "`popupClassName` is deprecated. Please use `dropdownClassName` instead.");
        devWarning(props.popupPlacement === void 0, "Cascader", "`popupPlacement` is deprecated. Please use `placement` instead.");
        devWarning(props.popupStyle === void 0, "Cascader", "`popupStyle` is deprecated. Please use `dropdownStyle` instead.");
      });
    }
    const mergedOpen = computed(() => props.open !== void 0 ? props.open : props.popupVisible);
    const mergedDropdownClassName = computed(() => props.dropdownClassName || props.popupClassName);
    const mergedDropdownStyle = computed(() => props.dropdownStyle || props.popupStyle || {});
    const mergedPlacement = computed(() => props.placement || props.popupPlacement);
    const onInternalDropdownVisibleChange = (nextVisible) => {
      var _a, _b;
      (_a = props.onDropdownVisibleChange) == null ? void 0 : _a.call(props, nextVisible);
      (_b = props.onPopupVisibleChange) == null ? void 0 : _b.call(props, nextVisible);
    };
    const {
      changeOnSelect,
      checkable,
      dropdownPrefixCls,
      loadData,
      expandTrigger,
      expandIcon,
      loadingIcon,
      dropdownMenuColumnStyle,
      customSlots
    } = toRefs(props);
    useProvideCascader({
      options: mergedOptions,
      fieldNames: mergedFieldNames,
      values: checkedValues,
      halfValues: halfCheckedValues,
      changeOnSelect,
      onSelect: onInternalSelect,
      checkable,
      searchOptions,
      dropdownPrefixCls,
      loadData,
      expandTrigger,
      expandIcon,
      loadingIcon,
      dropdownMenuColumnStyle,
      customSlots
    });
    const selectRef = ref();
    expose({
      focus() {
        var _a;
        (_a = selectRef.value) == null ? void 0 : _a.focus();
      },
      blur() {
        var _a;
        (_a = selectRef.value) == null ? void 0 : _a.blur();
      },
      scrollTo(arg) {
        var _a;
        (_a = selectRef.value) == null ? void 0 : _a.scrollTo(arg);
      }
    });
    const pickProps = computed(() => {
      return omit(props, [
        "id",
        "prefixCls",
        "fieldNames",
        // Value
        "defaultValue",
        "value",
        "changeOnSelect",
        "onChange",
        "displayRender",
        "checkable",
        // Search
        "searchValue",
        "onSearch",
        "showSearch",
        // Trigger
        "expandTrigger",
        // Options
        "options",
        "dropdownPrefixCls",
        "loadData",
        // Open
        "popupVisible",
        "open",
        "popupClassName",
        "dropdownClassName",
        "dropdownMenuColumnStyle",
        "popupPlacement",
        "placement",
        "onDropdownVisibleChange",
        "onPopupVisibleChange",
        // Icon
        "expandIcon",
        "loadingIcon",
        "customSlots",
        "showCheckedStrategy",
        // Children
        "children"
      ]);
    });
    return () => {
      const emptyOptions = !(mergedSearchValue.value ? searchOptions.value : mergedOptions.value).length;
      const {
        dropdownMatchSelectWidth = false
      } = props;
      const dropdownStyle = mergedSearchValue.value && mergedSearchConfig.value.matchInputWidth || emptyOptions ? {} : {
        minWidth: "auto"
      };
      return createVNode(BaseSelect, {
        ...pickProps.value,
        ...attrs,
        "ref": selectRef,
        "id": mergedId,
        "prefixCls": props.prefixCls,
        "dropdownMatchSelectWidth": dropdownMatchSelectWidth,
        "dropdownStyle": {
          ...mergedDropdownStyle.value,
          ...dropdownStyle
        },
        "displayValues": displayValues.value,
        "onDisplayValuesChange": onDisplayValuesChange,
        "mode": multiple.value ? "multiple" : void 0,
        "searchValue": mergedSearchValue.value,
        "onSearch": onInternalSearch,
        "showSearch": mergedShowSearch.value,
        "OptionList": OptionList,
        "emptyOptions": emptyOptions,
        "open": mergedOpen.value,
        "dropdownClassName": mergedDropdownClassName.value,
        "placement": mergedPlacement.value,
        "onDropdownVisibleChange": onInternalDropdownVisibleChange,
        "getRawInputElement": () => {
          var _a;
          return (_a = slots.default) == null ? void 0 : _a.call(slots);
        }
      }, slots);
    };
  }
});

export { SHOW_PARENT, VcCascader as default, internalCascaderProps, multipleCascaderProps, singleCascaderProps };
//# sourceMappingURL=Cascader.mjs.map
