import { defineComponent, toRef, computed, watchEffect, shallowRef, toRaw, toRefs, ref, 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 OptionList from './OptionList.mjs';
import { SHOW_CHILD, formatStrategyValues } from './utils/strategyUtil.mjs';
import { useProvideSelectContext } from './TreeSelectContext.mjs';
import { useProvideLegacySelectContext } from './LegacyContext.mjs';
import useTreeData from './hooks/useTreeData.mjs';
import { fillFieldNames, toArray, isNil } from './utils/valueUtil.mjs';
import useCache from './hooks/useCache.mjs';
import useDataEntities from './hooks/useDataEntities.mjs';
import { fillAdditionalInfo, fillLegacyProps } from './utils/legacyUtil.mjs';
import useCheckedKeys from './hooks/useCheckedKeys.mjs';
import useFilterTreeData from './hooks/useFilterTreeData.mjs';
import warningProps from './utils/warningPropsUtil.mjs';
import { omit } from '../../../utils/lang/omit.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 { warning } from '../../../utils/log.mjs';
import { toReactive } from '../../../utils/vue/toReactive.mjs';

function treeSelectProps() {
  return {
    ...omit(baseSelectPropsWithoutPrivate(), ["mode"]),
    prefixCls: String,
    id: String,
    value: {
      type: [String, Number, Object, Array]
    },
    defaultValue: {
      type: [String, Number, Object, Array]
    },
    onChange: {
      type: Function
    },
    searchValue: String,
    /** @deprecated Use `searchValue` instead */
    inputValue: String,
    onSearch: {
      type: Function
    },
    autoClearSearchValue: {
      type: Boolean,
      default: void 0
    },
    filterTreeNode: {
      type: [Boolean, Function],
      default: void 0
    },
    treeNodeFilterProp: String,
    // >>> Select
    onSelect: Function,
    onDeselect: Function,
    showCheckedStrategy: {
      type: String
    },
    treeNodeLabelProp: String,
    fieldNames: {
      type: Object
    },
    // >>> Mode
    multiple: {
      type: Boolean,
      default: void 0
    },
    treeCheckable: {
      type: Boolean,
      default: void 0
    },
    treeCheckStrictly: {
      type: Boolean,
      default: void 0
    },
    labelInValue: {
      type: Boolean,
      default: void 0
    },
    // >>> Data
    treeData: {
      type: Array
    },
    treeDataSimpleMode: {
      type: [Boolean, Object],
      default: void 0
    },
    loadData: {
      type: Function
    },
    treeLoadedKeys: {
      type: Array
    },
    onTreeLoad: {
      type: Function
    },
    // >>> Expanded
    treeDefaultExpandAll: {
      type: Boolean,
      default: void 0
    },
    treeExpandedKeys: {
      type: Array
    },
    treeDefaultExpandedKeys: {
      type: Array
    },
    onTreeExpand: {
      type: Function
    },
    // >>> Options
    virtual: {
      type: Boolean,
      default: void 0
    },
    listHeight: Number,
    listItemHeight: Number,
    onDropdownVisibleChange: {
      type: Function
    },
    // >>> Tree
    treeLine: {
      type: [Boolean, Object],
      default: void 0
    },
    treeIcon: PropTypes.any,
    showTreeIcon: {
      type: Boolean,
      default: void 0
    },
    switcherIcon: PropTypes.any,
    treeMotion: PropTypes.any,
    children: Array,
    treeExpandAction: String,
    showArrow: {
      type: Boolean,
      default: void 0
    },
    showSearch: {
      type: Boolean,
      default: void 0
    },
    open: {
      type: Boolean,
      default: void 0
    },
    defaultOpen: {
      type: Boolean,
      default: void 0
    },
    disabled: {
      type: Boolean,
      default: void 0
    },
    placeholder: PropTypes.any,
    maxTagPlaceholder: {
      type: Function
    },
    dropdownPopupAlign: PropTypes.any,
    customSlots: Object
  };
}
function isRawValue(value) {
  return !value || typeof value !== "object";
}
var VcTreeSelect = /* @__PURE__ */ defineComponent({
  compatConfig: {
    MODE: 3
  },
  name: "TreeSelect",
  inheritAttrs: false,
  props: initDefaultProps(treeSelectProps(), {
    treeNodeFilterProp: "value",
    autoClearSearchValue: true,
    showCheckedStrategy: SHOW_CHILD,
    listHeight: 200,
    listItemHeight: 20,
    prefixCls: "vc-tree-select"
  }),
  setup(props, {
    attrs,
    expose,
    slots
  }) {
    const mergedId = useId(toRef(props, "id"));
    const treeConduction = computed(() => props.treeCheckable && !props.treeCheckStrictly);
    const mergedCheckable = computed(() => props.treeCheckable || props.treeCheckStrictly);
    const mergedLabelInValue = computed(() => props.treeCheckStrictly || props.labelInValue);
    const mergedMultiple = computed(() => mergedCheckable.value || props.multiple);
    if (process.env.NODE_ENV !== "production") {
      watchEffect(() => {
        warningProps(props);
      });
    }
    const mergedFieldNames = computed(() => fillFieldNames(props.fieldNames));
    const [mergedSearchValue, setSearchValue] = useMergedState("", {
      value: computed(() => props.searchValue !== void 0 ? props.searchValue : props.inputValue),
      postState: (search) => search || ""
    });
    const onInternalSearch = (searchText) => {
      var _a;
      setSearchValue(searchText);
      (_a = props.onSearch) == null ? void 0 : _a.call(props, searchText);
    };
    const mergedTreeData = useTreeData(toRef(props, "treeData"), toRef(props, "children"), toRef(props, "treeDataSimpleMode"));
    const {
      keyEntities,
      valueEntities
    } = useDataEntities(mergedTreeData, mergedFieldNames);
    const splitRawValues = (newRawValues) => {
      const missingRawValues = [];
      const existRawValues = [];
      newRawValues.forEach((val) => {
        if (valueEntities.value.has(val))
          existRawValues.push(val);
        else
          missingRawValues.push(val);
      });
      return {
        missingRawValues,
        existRawValues
      };
    };
    const filteredTreeData = useFilterTreeData(mergedTreeData, mergedSearchValue, {
      fieldNames: mergedFieldNames,
      treeNodeFilterProp: toRef(props, "treeNodeFilterProp"),
      filterTreeNode: toRef(props, "filterTreeNode")
    });
    const getLabel = (item) => {
      if (item) {
        if (props.treeNodeLabelProp)
          return item[props.treeNodeLabelProp];
        const {
          _title: titleList
        } = mergedFieldNames.value;
        for (let i = 0; i < titleList.length; i += 1) {
          const title = item[titleList[i]];
          if (title !== void 0)
            return title;
        }
      }
    };
    const toLabeledValues = (draftValues) => {
      const values = toArray(draftValues);
      return values.map((val) => {
        if (isRawValue(val))
          return {
            value: val
          };
        return val;
      });
    };
    const convert2LabelValues = (draftValues) => {
      const values = toLabeledValues(draftValues);
      return values.map((item) => {
        let {
          label: rawLabel
        } = item;
        const {
          value: rawValue,
          halfChecked: rawHalfChecked
        } = item;
        let rawDisabled;
        const entity = valueEntities.value.get(rawValue);
        if (entity) {
          rawLabel = rawLabel != null ? rawLabel : getLabel(entity.node);
          rawDisabled = entity.node.disabled;
        }
        return {
          label: rawLabel,
          value: rawValue,
          halfChecked: rawHalfChecked,
          disabled: rawDisabled
        };
      });
    };
    const [internalValue, setInternalValue] = useMergedState(props.defaultValue, {
      value: toRef(props, "value")
    });
    const rawMixedLabeledValues = computed(() => toLabeledValues(internalValue.value));
    const rawLabeledValues = shallowRef([]);
    const rawHalfLabeledValues = shallowRef([]);
    watchEffect(() => {
      const fullCheckValues = [];
      const halfCheckValues = [];
      rawMixedLabeledValues.value.forEach((item) => {
        if (item.halfChecked)
          halfCheckValues.push(item);
        else
          fullCheckValues.push(item);
      });
      rawLabeledValues.value = fullCheckValues;
      rawHalfLabeledValues.value = halfCheckValues;
    });
    const rawValues = computed(() => rawLabeledValues.value.map((item) => item.value));
    const {
      maxLevel,
      levelEntities
    } = useMaxLevel(keyEntities);
    const [rawCheckedValues, rawHalfCheckedValues] = useCheckedKeys(rawLabeledValues, rawHalfLabeledValues, treeConduction, keyEntities, maxLevel, levelEntities);
    const displayValues = computed(() => {
      const displayKeys = formatStrategyValues(rawCheckedValues.value, props.showCheckedStrategy, keyEntities.value, mergedFieldNames.value);
      const values = displayKeys.map((key) => {
        var _a, _b, _c;
        return (_c = (_b = (_a = keyEntities.value[key]) == null ? void 0 : _a.node) == null ? void 0 : _b[mergedFieldNames.value.value]) != null ? _c : key;
      });
      const labeledValues = values.map((val) => {
        const targetItem = rawLabeledValues.value.find((item) => item.value === val);
        return {
          value: val,
          label: targetItem == null ? void 0 : targetItem.label
        };
      });
      const rawDisplayValues = convert2LabelValues(labeledValues);
      const firstVal = rawDisplayValues[0];
      if (!mergedMultiple.value && firstVal && isNil(firstVal.value) && isNil(firstVal.label))
        return [];
      return rawDisplayValues.map((item) => {
        var _a;
        return {
          ...item,
          label: (_a = item.label) != null ? _a : item.value
        };
      });
    });
    const [cachedDisplayValues] = useCache(displayValues);
    const triggerChange = (newRawValues, extra, source) => {
      const labeledValues = convert2LabelValues(newRawValues);
      setInternalValue(labeledValues);
      if (props.autoClearSearchValue)
        setSearchValue("");
      if (props.onChange) {
        let eventValues = newRawValues;
        if (treeConduction.value) {
          const formattedKeyList = formatStrategyValues(newRawValues, props.showCheckedStrategy, keyEntities.value, mergedFieldNames.value);
          eventValues = formattedKeyList.map((key) => {
            const entity = valueEntities.value.get(key);
            return entity ? entity.node[mergedFieldNames.value.value] : key;
          });
        }
        const {
          triggerValue,
          selected
        } = extra || {
          triggerValue: void 0,
          selected: void 0
        };
        let returnRawValues = eventValues;
        if (props.treeCheckStrictly) {
          const halfValues = rawHalfLabeledValues.value.filter((item) => !eventValues.includes(item.value));
          returnRawValues = [...returnRawValues, ...halfValues];
        }
        const returnLabeledValues = convert2LabelValues(returnRawValues);
        const additionalInfo = {
          // [Legacy] Always return as array contains label & value
          preValue: rawLabeledValues.value,
          triggerValue
        };
        let showPosition = true;
        if (props.treeCheckStrictly || source === "selection" && !selected)
          showPosition = false;
        fillAdditionalInfo(additionalInfo, triggerValue, newRawValues, mergedTreeData.value, showPosition, mergedFieldNames.value);
        if (mergedCheckable.value)
          additionalInfo.checked = selected;
        else
          additionalInfo.selected = selected;
        const returnValues = mergedLabelInValue.value ? returnLabeledValues : returnLabeledValues.map((item) => item.value);
        props.onChange(mergedMultiple.value ? returnValues : returnValues[0], mergedLabelInValue.value ? null : returnLabeledValues.map((item) => item.label), additionalInfo);
      }
    };
    const onOptionSelect = (selectedKey, {
      selected,
      source
    }) => {
      var _a, _b, _c;
      const keyEntitiesValue = toRaw(keyEntities.value);
      const valueEntitiesValue = toRaw(valueEntities.value);
      const entity = keyEntitiesValue[selectedKey];
      const node = entity == null ? void 0 : entity.node;
      const selectedValue = (_a = node == null ? void 0 : node[mergedFieldNames.value.value]) != null ? _a : selectedKey;
      if (!mergedMultiple.value) {
        triggerChange([selectedValue], {
          selected: true,
          triggerValue: selectedValue
        }, "option");
      } else {
        let newRawValues = selected ? [...rawValues.value, selectedValue] : rawCheckedValues.value.filter((v) => v !== selectedValue);
        if (treeConduction.value) {
          const {
            missingRawValues,
            existRawValues
          } = splitRawValues(newRawValues);
          const keyList = existRawValues.map((val) => valueEntitiesValue.get(val).key);
          let checkedKeys;
          if (selected) {
            ({
              checkedKeys
            } = conductCheck(keyList, true, keyEntitiesValue, maxLevel.value, levelEntities.value));
          } else {
            ({
              checkedKeys
            } = conductCheck(keyList, {
              checked: false,
              halfCheckedKeys: rawHalfCheckedValues.value
            }, keyEntitiesValue, maxLevel.value, levelEntities.value));
          }
          newRawValues = [...missingRawValues, ...checkedKeys.map((key) => keyEntitiesValue[key].node[mergedFieldNames.value.value])];
        }
        triggerChange(newRawValues, {
          selected,
          triggerValue: selectedValue
        }, source || "option");
      }
      if (selected || !mergedMultiple.value)
        (_b = props.onSelect) == null ? void 0 : _b.call(props, selectedValue, fillLegacyProps(node));
      else
        (_c = props.onDeselect) == null ? void 0 : _c.call(props, selectedValue, fillLegacyProps(node));
    };
    const onInternalDropdownVisibleChange = (open) => {
      if (props.onDropdownVisibleChange) {
        const legacyParam = {};
        Object.defineProperty(legacyParam, "documentClickClose", {
          get() {
            warning(false, "Second param of `onDropdownVisibleChange` has been removed.");
            return false;
          }
        });
        props.onDropdownVisibleChange(open, legacyParam);
      }
    };
    const onDisplayValuesChange = (newValues, info) => {
      const newRawValues = newValues.map((item) => item.value);
      if (info.type === "clear") {
        triggerChange(newRawValues, {}, "selection");
        return;
      }
      if (info.values.length)
        onOptionSelect(info.values[0].value, {
          selected: false,
          source: "selection"
        });
    };
    const {
      treeNodeFilterProp,
      // Data
      loadData,
      treeLoadedKeys,
      onTreeLoad,
      // Expanded
      treeDefaultExpandAll,
      treeExpandedKeys,
      treeDefaultExpandedKeys,
      onTreeExpand,
      // Options
      virtual,
      listHeight,
      listItemHeight,
      // Tree
      treeLine,
      treeIcon,
      showTreeIcon,
      switcherIcon,
      treeMotion,
      customSlots,
      dropdownMatchSelectWidth,
      treeExpandAction
    } = toRefs(props);
    useProvideLegacySelectContext(toReactive({
      checkable: mergedCheckable,
      loadData,
      treeLoadedKeys,
      onTreeLoad,
      checkedKeys: rawCheckedValues,
      halfCheckedKeys: rawHalfCheckedValues,
      treeDefaultExpandAll,
      treeExpandedKeys,
      treeDefaultExpandedKeys,
      onTreeExpand,
      treeIcon,
      treeMotion,
      showTreeIcon,
      switcherIcon,
      treeLine,
      treeNodeFilterProp,
      keyEntities,
      customSlots
    }));
    useProvideSelectContext(toReactive({
      virtual,
      listHeight,
      listItemHeight,
      treeData: filteredTreeData,
      fieldNames: mergedFieldNames,
      onSelect: onOptionSelect,
      dropdownMatchSelectWidth,
      treeExpandAction
    }));
    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);
      }
    });
    return () => {
      var _a;
      const restProps = omit(props, [
        "id",
        "prefixCls",
        "customSlots",
        // Value
        "value",
        "defaultValue",
        "onChange",
        "onSelect",
        "onDeselect",
        // Search
        "searchValue",
        "inputValue",
        "onSearch",
        "autoClearSearchValue",
        "filterTreeNode",
        "treeNodeFilterProp",
        // Selector
        "showCheckedStrategy",
        "treeNodeLabelProp",
        //  Mode
        "multiple",
        "treeCheckable",
        "treeCheckStrictly",
        "labelInValue",
        // FieldNames
        "fieldNames",
        // Data
        "treeDataSimpleMode",
        "treeData",
        "children",
        "loadData",
        "treeLoadedKeys",
        "onTreeLoad",
        // Expanded
        "treeDefaultExpandAll",
        "treeExpandedKeys",
        "treeDefaultExpandedKeys",
        "onTreeExpand",
        // Options
        "virtual",
        "listHeight",
        "listItemHeight",
        "onDropdownVisibleChange",
        // Tree
        "treeLine",
        "treeIcon",
        "showTreeIcon",
        "switcherIcon",
        "treeMotion"
      ]);
      return createVNode(BaseSelect, {
        "ref": selectRef,
        ...attrs,
        ...restProps,
        "id": mergedId,
        "prefixCls": props.prefixCls,
        "mode": mergedMultiple.value ? "multiple" : void 0,
        "displayValues": cachedDisplayValues.value,
        "onDisplayValuesChange": onDisplayValuesChange,
        "searchValue": mergedSearchValue.value,
        "onSearch": onInternalSearch,
        "OptionList": OptionList,
        "emptyOptions": !mergedTreeData.value.length,
        "onDropdownVisibleChange": onInternalDropdownVisibleChange,
        "tagRender": props.tagRender || slots.tagRender,
        "dropdownMatchSelectWidth": (_a = props.dropdownMatchSelectWidth) != null ? _a : true
      }, slots);
    };
  }
});

export { VcTreeSelect as default, treeSelectProps };
//# sourceMappingURL=TreeSelect.mjs.map
