'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var vue = require('vue');
require('../../../utils/index.cjs');
require('../../../hooks/index.cjs');
var BaseSelect = require('../../vc-select/src/BaseSelect.cjs');
var useId = require('../../vc-select/src/hooks/useId.cjs');
var conductUtil = require('../../vc-tree/src/utils/conductUtil.cjs');
var useMaxLevel = require('../../vc-tree/src/useMaxLevel.cjs');
var OptionList = require('./OptionList.cjs');
var strategyUtil = require('./utils/strategyUtil.cjs');
var TreeSelectContext = require('./TreeSelectContext.cjs');
var LegacyContext = require('./LegacyContext.cjs');
var useTreeData = require('./hooks/useTreeData.cjs');
var valueUtil = require('./utils/valueUtil.cjs');
var useCache = require('./hooks/useCache.cjs');
var useDataEntities = require('./hooks/useDataEntities.cjs');
var legacyUtil = require('./utils/legacyUtil.cjs');
var useCheckedKeys = require('./hooks/useCheckedKeys.cjs');
var useFilterTreeData = require('./hooks/useFilterTreeData.cjs');
var warningPropsUtil = require('./utils/warningPropsUtil.cjs');
var omit = require('../../../utils/lang/omit.cjs');
var vueTypes = require('../../../utils/vue/vueTypes.cjs');
var initDefaultProps = require('../../../utils/vue/initDefaultProps.cjs');
var index = require('../../../hooks/use-merged-state/index.cjs');
var log = require('../../../utils/log.cjs');
var toReactive = require('../../../utils/vue/toReactive.cjs');

function treeSelectProps() {
  return {
    ...omit.omit(BaseSelect.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: vueTypes.default.any,
    showTreeIcon: {
      type: Boolean,
      default: void 0
    },
    switcherIcon: vueTypes.default.any,
    treeMotion: vueTypes.default.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: vueTypes.default.any,
    maxTagPlaceholder: {
      type: Function
    },
    dropdownPopupAlign: vueTypes.default.any,
    customSlots: Object
  };
}
function isRawValue(value) {
  return !value || typeof value !== "object";
}
var VcTreeSelect = /* @__PURE__ */ vue.defineComponent({
  compatConfig: {
    MODE: 3
  },
  name: "TreeSelect",
  inheritAttrs: false,
  props: initDefaultProps.initDefaultProps(treeSelectProps(), {
    treeNodeFilterProp: "value",
    autoClearSearchValue: true,
    showCheckedStrategy: strategyUtil.SHOW_CHILD,
    listHeight: 200,
    listItemHeight: 20,
    prefixCls: "vc-tree-select"
  }),
  setup(props, {
    attrs,
    expose,
    slots
  }) {
    const mergedId = useId.default(vue.toRef(props, "id"));
    const treeConduction = vue.computed(() => props.treeCheckable && !props.treeCheckStrictly);
    const mergedCheckable = vue.computed(() => props.treeCheckable || props.treeCheckStrictly);
    const mergedLabelInValue = vue.computed(() => props.treeCheckStrictly || props.labelInValue);
    const mergedMultiple = vue.computed(() => mergedCheckable.value || props.multiple);
    if (process.env.NODE_ENV !== "production") {
      vue.watchEffect(() => {
        warningPropsUtil.default(props);
      });
    }
    const mergedFieldNames = vue.computed(() => valueUtil.fillFieldNames(props.fieldNames));
    const [mergedSearchValue, setSearchValue] = index.useMergedState("", {
      value: vue.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.default(vue.toRef(props, "treeData"), vue.toRef(props, "children"), vue.toRef(props, "treeDataSimpleMode"));
    const {
      keyEntities,
      valueEntities
    } = useDataEntities.default(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.default(mergedTreeData, mergedSearchValue, {
      fieldNames: mergedFieldNames,
      treeNodeFilterProp: vue.toRef(props, "treeNodeFilterProp"),
      filterTreeNode: vue.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 = valueUtil.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] = index.useMergedState(props.defaultValue, {
      value: vue.toRef(props, "value")
    });
    const rawMixedLabeledValues = vue.computed(() => toLabeledValues(internalValue.value));
    const rawLabeledValues = vue.shallowRef([]);
    const rawHalfLabeledValues = vue.shallowRef([]);
    vue.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 = vue.computed(() => rawLabeledValues.value.map((item) => item.value));
    const {
      maxLevel,
      levelEntities
    } = useMaxLevel.default(keyEntities);
    const [rawCheckedValues, rawHalfCheckedValues] = useCheckedKeys.default(rawLabeledValues, rawHalfLabeledValues, treeConduction, keyEntities, maxLevel, levelEntities);
    const displayValues = vue.computed(() => {
      const displayKeys = strategyUtil.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 && valueUtil.isNil(firstVal.value) && valueUtil.isNil(firstVal.label))
        return [];
      return rawDisplayValues.map((item) => {
        var _a;
        return {
          ...item,
          label: (_a = item.label) != null ? _a : item.value
        };
      });
    });
    const [cachedDisplayValues] = useCache.default(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 = strategyUtil.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;
        legacyUtil.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 = vue.toRaw(keyEntities.value);
      const valueEntitiesValue = vue.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
            } = conductUtil.conductCheck(keyList, true, keyEntitiesValue, maxLevel.value, levelEntities.value));
          } else {
            ({
              checkedKeys
            } = conductUtil.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, legacyUtil.fillLegacyProps(node));
      else
        (_c = props.onDeselect) == null ? void 0 : _c.call(props, selectedValue, legacyUtil.fillLegacyProps(node));
    };
    const onInternalDropdownVisibleChange = (open) => {
      if (props.onDropdownVisibleChange) {
        const legacyParam = {};
        Object.defineProperty(legacyParam, "documentClickClose", {
          get() {
            log.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
    } = vue.toRefs(props);
    LegacyContext.useProvideLegacySelectContext(toReactive.toReactive({
      checkable: mergedCheckable,
      loadData,
      treeLoadedKeys,
      onTreeLoad,
      checkedKeys: rawCheckedValues,
      halfCheckedKeys: rawHalfCheckedValues,
      treeDefaultExpandAll,
      treeExpandedKeys,
      treeDefaultExpandedKeys,
      onTreeExpand,
      treeIcon,
      treeMotion,
      showTreeIcon,
      switcherIcon,
      treeLine,
      treeNodeFilterProp,
      keyEntities,
      customSlots
    }));
    TreeSelectContext.useProvideSelectContext(toReactive.toReactive({
      virtual,
      listHeight,
      listItemHeight,
      treeData: filteredTreeData,
      fieldNames: mergedFieldNames,
      onSelect: onOptionSelect,
      dropdownMatchSelectWidth,
      treeExpandAction
    }));
    const selectRef = vue.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.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 vue.createVNode(BaseSelect.default, {
        "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.default,
        "emptyOptions": !mergedTreeData.value.length,
        "onDropdownVisibleChange": onInternalDropdownVisibleChange,
        "tagRender": props.tagRender || slots.tagRender,
        "dropdownMatchSelectWidth": (_a = props.dropdownMatchSelectWidth) != null ? _a : true
      }, slots);
    };
  }
});

exports.default = VcTreeSelect;
exports.treeSelectProps = treeSelectProps;
//# sourceMappingURL=TreeSelect.cjs.map
