/**
 * ldesign v0.2.22
 * (c) 2022/12/7 16:21 built by swimly
 * @license MIT
 */

import { h as helper } from '../../chunks/helper.js';
import { defineComponent, getCurrentInstance, ref, toRefs, computed, nextTick, watch, provide } from '@vue/composition-api';
import isFunction from 'lodash/isFunction';
import debounce from 'lodash/debounce';
import get from 'lodash/get';
import cloneDeep from 'lodash/cloneDeep';
import isArray from 'lodash/isArray';
import isObject from 'lodash/isObject';
import '../../chunks/index.js';
import useDefaultValue from '../../hooks/useDefaultValue.js';
import useVModel from '../../hooks/useVModel.js';
import { useLNodeJSX } from '../../hooks/lnode.js';
import { useConfig, usePrefixClass } from '../config-provider/useConfig.js';
import { Loading } from '../loading/index.js';
import { Popup } from '../popup/index.js';
import { Input } from '../input/index.js';
import { Tag } from '../tag/index.js';
import { SelectInput } from '../select-input/index.js';
import FakeArrow from '../common/fake-arrow.js';
import { on, off } from '../../utils/dom.js';
import useFormDisabled from '../../hooks/useFormDisabled.js';
import _Option from './option.js';
import SelectPanel from './select-panel.js';
import { getSingleContent, getMultipleContent, flattenOptions, getNewMultipleValue } from './utils.js';
import useSelectOptions from './hooks/use-select-options.js';
import { SelectProps } from './props.js';
import { l as log } from '../../chunks/log.js';
import '../../chunks/_commonjsHelpers.js';
import '../../chunks/_commonjsHelpers-fe796db6.js';
import 'lodash/kebabCase';
import 'lodash/isEmpty';
import 'lodash/camelCase';
import '../../hooks/render-lnode.js';
import 'lodash';
import '../config-provider/context.js';
import 'lodash/merge';
import 'lodash/mergeWith';
import '../../chunks/zh_CN.js';
import '../config-provider/type.js';
import '../../utils/withInstall.js';
import 'vue';
import 'lodash/capitalize';
import '../../config.js';
import '../loading/loading.js';
import '../../utils/render-node.js';
import '../../utils/transfer-dom.js';
import '../config-provider/config-receiver.js';
import '../../utils/mixins.js';
import '../loading/props.js';
import '../loading/icon/gradient.js';
import '../../chunks/defineProperty-19da3d4c.js';
import '../../chunks/set-style.js';
import '../../chunks/helper2.js';
import 'raf';
import 'lodash/isString';
import '../../utils/easing.js';
import '../loading/style/css.js';
import '../loading/type.js';
import '../loading/plugin.js';
import '../../utils/map-props.js';
import '../popup/popup.js';
import '@popperjs/core';
import '../../utils/helper.js';
import '../popup/props.js';
import '../popup/container.js';
import '../popup/style/css.js';
import '../popup/type.js';
import '../input/input.js';
import '@ldesign/icons-vue';
import '../../utils/event.js';
import '../input/props.js';
import '../input/group.js';
import '../input/style/css.js';
import '../input/type.js';
import '../tag/tag.js';
import '../tag/props.js';
import '../tag/check-tag.js';
import '../tag/style/css.js';
import '../tag/type.js';
import '../select-input/select-input.js';
import '../select-input/props.js';
import '../select-input/hooks/use-single.js';
import 'lodash/pick';
import '../../hooks/useConfig.js';
import '../select-input/hooks/use-multiple.js';
import '../tag-input/index.js';
import '../tag-input/tag-input.js';
import '../../hooks/useGlobalIcon.js';
import '../tag-input/props.js';
import '../tag-input/hooks/use-tag-scroll.js';
import '../tag-input/hooks/use-tag-list.js';
import '../tag-input/hooks/use-hover.js';
import '../tag-input/hooks/use-drag-sorter.js';
import '../tag-input/style/css.js';
import '../tag-input/type.js';
import '../select-input/hooks/use-overlay-innerstyle.js';
import '../select-input/style/css.js';
import '../select-input/type.js';
import '../../utils/ripple.js';
import '../checkbox/index.js';
import '../checkbox/group.js';
import 'lodash/intersection';
import '../checkbox/checkbox.js';
import '../checkbox/props.js';
import '../checkbox/style/css.js';
import '../checkbox/type.js';
import '../../hooks/useLazyLoad.js';
import '../../chunks/observe.js';
import '../../hooks/useCommonClassName.js';
import '../../hooks/useVirtualScroll.js';

var _Select = defineComponent({
  name: "LSelect",
  components: {
    TInput: Input,
    TLoading: Loading,
    Tag,
    Popup,
    TOption: _Option,
    FakeArrow,
    SelectPanel
  },
  props: {
    ...SelectProps
  },
  setup(props2, context) {
    const {
      t,
      global
    } = useConfig("select");
    const renderTNode = useLNodeJSX();
    const instance = getCurrentInstance();
    const selectInputRef = ref(null);
    const selectPanelRef = ref();
    const popupOpenTime = ref(250);
    const {
      formDisabled
    } = useFormDisabled();
    const COMPONENT_NAME = usePrefixClass("select");
    const {
      classPrefix
    } = useConfig("classPrefix");
    const {
      valueType,
      disabled,
      size,
      value: valueProps,
      multiple,
      placeholder,
      loading,
      max,
      reserveKeyword,
      inputValue,
      popupVisible,
      minCollapsedNum,
      creatable
    } = toRefs(props2);
    const keys = computed(() => ({
      label: props2.keys?.label || "label",
      value: props2.keys?.value || "value"
    }));
    const {
      options: innerOptions,
      optionsMap,
      optionsList
    } = useSelectOptions(props2, instance, keys);
    const [value, setValue] = useVModel(valueProps, props2.defaultValue, props2.onChange, "change");
    const innerValue = computed(() => {
      const isObjValue = valueType.value === "object";
      let _value = value.value;
      if (!multiple.value && isArray(_value)) {
        log.warn("Select", 'Invalid value for "value" props: got an Array when multiple was set to false');
        _value = isObjValue ? {} : "";
      }
      if (multiple.value && !isArray(_value)) {
        log.warn("Select", 'Invalid value for "value" props: expected an Array when multiple was set to true');
        _value = [];
      }
      if (isObjValue) {
        if (multiple.value) {
          return _value.filter(option => {
            const isObj2 = isObject(option);
            if (!isObj2) log.warn("Select", `Invalid value for "value" props: expected an Object, but got ${typeof option}`);
            return isObj2;
          }).map(option => option[keys.value.value]);
        }
        const isObj = isObject(_value);
        if (!isObj) {
          log.warn("Select", `Invalid value for "value" props: expected an Object, but got ${typeof _value}`);
          return "";
        }
        return _value[keys.value.value];
      }
      return _value;
    });
    const setInnerValue = (newVal, context2, optionValue) => {
      if (newVal === value.value) return;
      const selectedOptions = [];
      const {
        value: valueOfKeys,
        label: labelOfKeys
      } = keys.value;
      const oldValueMap = /* @__PURE__ */new Map();
      if (multiple.value) {
        const mapValue = value.value || [];
        mapValue.forEach?.(option => {
          oldValueMap.set(option[valueOfKeys], option);
        });
      }
      const getOriginOptions = val => {
        const option = optionsMap.value.get(val);
        if (option) delete option.index;
        return option;
      };
      const getFormatOption = val => {
        const option = optionsMap.value.get(val) || oldValueMap.get(val);
        if (option) delete option.index;
        return {
          [valueOfKeys]: get(option, valueOfKeys),
          [labelOfKeys]: get(option, labelOfKeys)
        };
      };
      if (multiple.value) newVal.forEach(v => selectedOptions.push(getOriginOptions(v)));else selectedOptions.push(getOriginOptions(newVal));
      if (valueType.value === "object") {
        newVal = multiple.value ? newVal.map(val => getFormatOption(val)) : getFormatOption(newVal);
      }
      const outputContext = {
        ...context2,
        selectedOptions
      };
      if (optionValue) {
        outputContext["option"] = getOriginOptions(optionValue);
      }
      setValue(newVal, outputContext);
    };
    const [tInputValue, setTInputValue] = useDefaultValue(inputValue, props2.defaultInputValue || "", props2.onInputChange, "inputValue", "input-change");
    const [innerPopupVisible, setInnerPopupVisible] = useDefaultValue(popupVisible, props2.defaultPopupVisible, (visible, context2) => {
      props2.onPopupVisibleChange?.(visible, context2);
      instance.emit("visible-change", visible);
    }, "popupVisible", "popup-visible-change");
    const isDisabled = computed(() => formDisabled.value || disabled.value);
    const isLoading = computed(() => loading.value && !isDisabled.value);
    const isFilterable = computed(() => Boolean(props2.filterable || global.value.filterable || isFunction(props2.filter)));
    const isReachMaxLimit = computed(() => multiple.value && max.value !== 0 && max.value <= innerValue.value.length);
    const placeholderText = computed(() => (!multiple.value && innerPopupVisible.value && (valueType.value === "object" && (value.value?.[keys.value.label] || innerValue.value) || getSingleContent(innerValue.value, optionsList.value)) || placeholder.value) ?? t(global.value.placeholder));
    const displayText = computed(() => {
      if (multiple.value) {
        if (valueType.value === "object") return value.value.map(v => v[keys.value.label]);
        return getMultipleContent(innerValue.value, optionsList.value);
      }
      if (valueType.value === "object") return value.value?.[keys.value.label] || innerValue.value;
      return getSingleContent(innerValue.value, optionsList.value);
    });
    const valueDisplayParams = computed(() => {
      const val = multiple.value ? innerValue.value.map(value2 => ({
        value: value2,
        label: optionsMap.value.get(value2)?.label
      })) : innerValue.value;
      return {
        value: val,
        onClose: multiple.value ? index => removeTag(index) : () => {}
      };
    });
    const collapsedItemsParams = computed(() => multiple.value ? {
      value: innerValue.value,
      collapsedSelectedItems: innerValue.value.slice(minCollapsedNum.value),
      count: innerValue.value.length - minCollapsedNum.value
    } : {});
    const removeTag = (index, context2) => {
      const {
        e
      } = context2 || {};
      e?.stopPropagation();
      if (isDisabled.value) return;
      const selectValue = cloneDeep(innerValue.value);
      const value2 = selectValue[index];
      selectValue.splice(index, 1);
      setInnerValue(selectValue, {
        e,
        trigger: "tag-remove"
      });
      const evtObj = {
        value: value2,
        data: optionsMap.value.get(value2),
        e
      };
      instance.emit("remove", evtObj);
      props2.onRemove?.(evtObj);
    };
    const handleCreate = () => {
      if (!tInputValue.value) return;
      const createVal = tInputValue.value;
      multiple.value && setTInputValue("");
      instance.emit("create", createVal);
      props2.onCreate?.(createVal);
    };
    const handleClear = _ref => {
      let {
        e
      } = _ref;
      e?.stopPropagation();
      if (multiple.value) setInnerValue([], {
        trigger: "clear",
        e
      });else setInnerValue("", {
        trigger: "clear",
        e
      });
      instance.emit("clear", {
        e
      });
      props2.onClear?.({
        e
      });
    };
    const handleTInputValueChange = (val, context2) => {
      if (context2.trigger === "blur" || !innerPopupVisible.value) return;
      setTInputValue(val);
      debounceSearch();
    };
    const handleTagChange = (currentTags, context2) => {
      const {
        trigger,
        index,
        e
      } = context2;
      if (trigger === "clear") setInnerValue([], {
        trigger: "tag-remove",
        e
      });
      if (["tag-remove", "backspace"].includes(trigger)) removeTag(index);
    };
    const handleFocus = (value2, context2) => {
      instance.emit("focus", {
        value: value2,
        e: context2?.e
      });
      props2.onFocus?.({
        value: value2,
        e: context2?.e
      });
    };
    const handleBlur = (value2, context2) => {
      instance.emit("blur", {
        value: value2,
        e: context2?.e
      });
      props2.onBlur?.({
        value: value2,
        e: context2?.e
      });
    };
    const handleEnter = (value2, context2) => {
      instance.emit("enter", {
        value: value2,
        e: context2?.e,
        inputValue: tInputValue.value
      });
      props2.onEnter?.({
        value: value2,
        e: context2?.e,
        inputValue: tInputValue.value.toString()
      });
    };
    const debounceSearch = debounce(() => {
      instance.emit("search", tInputValue.value);
      props2.onSearch?.(tInputValue.value.toString());
    }, 300);
    const getOverlayElm = () => {
      let r;
      try {
        const popupRefs = context.refs.selectInputRef.$refs.selectInputRef.$refs;
        r = popupRefs.overlay || popupRefs.component.$refs.overlay;
      } catch (e) {
        log.warn("Select", e);
      }
      return r;
    };
    const updateScrollTop = content => {
      if (props2.scroll?.type === "virtual") return;
      const overlayEl = getOverlayElm();
      if (!overlayEl) return;
      const firstSelectedNode = overlayEl?.querySelector(`.${classPrefix.value}-is-selected`);
      nextTick(() => {
        if (firstSelectedNode && content) {
          const {
            paddingBottom
          } = getComputedStyle(firstSelectedNode);
          const {
            marginBottom
          } = getComputedStyle(content);
          const elementBottomHeight = parseInt(paddingBottom, 10) + parseInt(marginBottom, 10);
          const updateValue = firstSelectedNode.offsetTop - content.offsetTop - (content.clientHeight - firstSelectedNode.clientHeight) + elementBottomHeight;
          content.scrollTop = updateValue;
        }
      });
    };
    const hoverIndex = ref(-1);
    const keydownEvent = e => {
      const displayOptions = flattenOptions(selectPanelRef.value?.getDisplayOptions());
      const displayOptionsLength = displayOptions.length;
      const arrowDownOption = () => {
        let count = 0;
        while (hoverIndex.value < displayOptionsLength) {
          if (!displayOptions[hoverIndex.value]?.disabled) break;
          if (hoverIndex.value === displayOptionsLength - 1) hoverIndex.value = 0;else hoverIndex.value += 1;
          count += 1;
          if (count >= displayOptionsLength) break;
        }
      };
      const arrowUpOption = () => {
        let count = 0;
        while (hoverIndex.value > -1) {
          if (!displayOptions[hoverIndex.value]?.disabled) break;
          if (hoverIndex.value === 0) hoverIndex.value = displayOptionsLength - 1;else hoverIndex.value -= 1;
          count += 1;
          if (count >= displayOptionsLength) break;
        }
      };
      if (displayOptionsLength === 0) return;
      const preventKeys = ["ArrowDown", "ArrowUp", "Enter", "Escape", "Tab"];
      if (preventKeys.includes(e.code)) e.preventDefault();
      switch (e.code) {
        case "ArrowDown":
          if (hoverIndex.value === -1) {
            hoverIndex.value = 0;
            return;
          }
          if (hoverIndex.value < displayOptionsLength - 1) {
            hoverIndex.value += 1;
            arrowDownOption();
          } else {
            hoverIndex.value = 0;
            arrowDownOption();
          }
          break;
        case "ArrowUp":
          if (hoverIndex.value === -1) {
            hoverIndex.value = 0;
            return;
          }
          if (hoverIndex.value > 0) {
            hoverIndex.value -= 1;
            arrowUpOption();
          } else {
            hoverIndex.value = displayOptionsLength - 1;
            arrowUpOption();
          }
          break;
        case "Enter":
          if (creatable.value && hoverIndex.value < 1 && displayOptions?.[0]?.isCreated) {
            handleCreate();
          } else if (hoverIndex.value === -1) {
            return;
          }
          if (!multiple.value) {
            const optionValue = displayOptions[hoverIndex.value].value;
            setInnerValue(optionValue, {
              e,
              trigger: "check"
            }, optionValue);
            setInnerPopupVisible(false, {
              e
            });
          } else {
            const optionValue = displayOptions[hoverIndex.value]?.value;
            if (!optionValue) return;
            const newValue = getNewMultipleValue(innerValue.value, optionValue);
            setInnerValue(newValue.value, {
              e,
              trigger: newValue.isCheck ? "check" : "uncheck"
            }, optionValue);
          }
          break;
        case "Escape":
        case "Tab":
          setInnerPopupVisible(false, {
            trigger: "keydown-esc",
            e
          });
          setTInputValue("");
          break;
      }
    };
    watch(innerPopupVisible, val => {
      val && on(document, "keydown", keydownEvent);
      !val && off(document, "keydown", keydownEvent);
    }, {
      flush: "sync"
    });
    watch(innerPopupVisible, value2 => {
      if (value2) {
        hoverIndex.value = -1;
      } else {
        tInputValue.value && setTInputValue("");
      }
    });
    provide("tSelect", {
      size,
      multiple,
      popupOpenTime,
      hoverIndex,
      selectValue: innerValue,
      reserveKeyword,
      isReachMaxLimit,
      getOverlayElm,
      handleCreate,
      handleValueChange: setInnerValue,
      handlerInputChange: setTInputValue,
      handlePopupVisibleChange: setInnerPopupVisible
    });
    return {
      isFilterable,
      isDisabled,
      isLoading,
      innerOptions,
      placeholderText,
      selectInputRef,
      selectPanelRef,
      innerPopupVisible,
      displayText,
      tInputValue,
      collapsedItemsParams,
      valueDisplayParams,
      handleFocus,
      handleBlur,
      handleEnter,
      handleClear,
      handleTagChange,
      handleTInputValueChange,
      setInnerPopupVisible,
      removeTag,
      renderTNode,
      updateScrollTop,
      componentName: COMPONENT_NAME
    };
  },
  methods: {
    renderSuffixIcon() {
      const h = this.$createElement;
      const {
        isLoading,
        showArrow,
        innerPopupVisible,
        isDisabled
      } = this;
      if (isLoading) {
        return h("t-loading", {
          "class": [`${this.componentName}__right-icon`, `${this.componentName}__active-icon`],
          "attrs": {
            "size": "small"
          }
        });
      }
      return showArrow ? h("fake-arrow", {
        "attrs": {
          "overlayClassName": `${this.componentName}__right-icon`,
          "isActive": innerPopupVisible && !isDisabled
        }
      }) : null;
    }
  },
  render() {
    const h = arguments[0];
    const {
      renderTNode
    } = this;
    const prefixIcon = () => renderTNode("prefixIcon");
    const valueDisplay = () => renderTNode("valueDisplay", {
      params: this.valueDisplayParams
    });
    const collapsedItems = () => renderTNode("collapsedItems", {
      params: this.collapsedItemsParams
    });
    const {
      overlayClassName,
      ...restPopupProps
    } = this.popupProps || {};
    return h("div", {
      "ref": "select",
      "class": `${this.componentName}__wrap`
    }, [h(SelectInput, helper([{
      "ref": "selectInputRef",
      "class": this.componentName,
      "attrs": {
        "autoWidth": this.autoWidth,
        "borderless": this.borderless,
        "readonly": this.readonly,
        "allowInput": this.isFilterable,
        "multiple": this.multiple,
        "keys": this.keys,
        "status": this.status,
        "tips": this.tips,
        "value": this.displayText,
        "valueDisplay": valueDisplay,
        "clearable": this.clearable,
        "disabled": this.isDisabled,
        "label": prefixIcon,
        "suffixIcon": this.renderSuffixIcon,
        "placeholder": this.placeholderText,
        "inputValue": this.tInputValue,
        "inputProps": {
          size: this.size,
          ...this.inputProps
        },
        "tagInputProps": {
          autoWidth: true,
          ...this.tagInputProps
        },
        "tagProps": this.tagProps,
        "minCollapsedNum": this.minCollapsedNum,
        "collapsedItems": collapsedItems,
        "popupVisible": this.innerPopupVisible,
        "popupProps": {
          overlayClassName: [`${this.componentName}__dropdown`, overlayClassName],
          ...restPopupProps
        }
      }
    }, {
      "on": {
        "focus": this.handleFocus,
        "blur": this.handleBlur,
        "enter": this.handleEnter,
        "clear": this.handleClear,
        "input-change": this.handleTInputValueChange,
        "popup-visible-change": this.setInnerPopupVisible,
        "tag-change": this.handleTagChange
      }
    }, {}, this.selectInputProps, {
      "attrs": {
        "updateScrollTop": this.updateScrollTop
      }
    }]), [h("select-panel", {
      "ref": "selectPanelRef",
      "slot": "panel",
      "scopedSlots": this.$scopedSlots,
      "attrs": {
        "size": this.size,
        "options": this.innerOptions,
        "inputValue": this.tInputValue,
        "multiple": this.multiple,
        "empty": this.empty,
        "filter": this.filter,
        "filterable": this.isFilterable,
        "creatable": this.creatable,
        "scroll": this.scroll,
        "loading": this.isLoading,
        "loadingText": this.loadingText,
        "panelTopContent": this.panelTopContent,
        "panelBottomContent": this.panelBottomContent
      }
    })])]);
  }
});

export { _Select as default };
//# sourceMappingURL=select.js.map
