/**
 * 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, toRefs, inject, computed, onMounted, onBeforeUnmount } from '@vue/composition-api';
import isFunction from 'lodash/isFunction';
import { useLNodeJSX } from '../../hooks/lnode.js';
import { renderLNodeJSXDefault } from '../../utils/render-node.js';
import { useConfig, usePrefixClass } from '../config-provider/useConfig.js';
import useVirtualScroll from '../../hooks/useVirtualScroll.js';
import _Option from './option.js';
import { flattenOptions } from './utils.js';
import '../../chunks/_commonjsHelpers.js';
import 'lodash/isEmpty';
import 'lodash/camelCase';
import 'lodash/kebabCase';
import '../../hooks/render-lnode.js';
import 'lodash';
import 'vue';
import '../config-provider/context.js';
import 'lodash/merge';
import 'lodash/mergeWith';
import '../../chunks/zh_CN.js';
import '../config-provider/type.js';
import '../../utils/ripple.js';
import '../../chunks/set-style.js';
import '../../config.js';
import '../config-provider/config-receiver.js';
import '../checkbox/index.js';
import '../../utils/map-props.js';
import '../../utils/withInstall.js';
import 'lodash/capitalize';
import '../checkbox/group.js';
import 'lodash/intersection';
import '../../chunks/index.js';
import '../../chunks/log.js';
import '../../chunks/_commonjsHelpers-fe796db6.js';
import '../../utils/event.js';
import '../../utils/helper.js';
import '../../utils/mixins.js';
import '../checkbox/checkbox.js';
import '../checkbox/props.js';
import '../checkbox/style';
import '../checkbox/type.js';
import '../../hooks/useLazyLoad.js';
import '../../chunks/observe.js';
import '../../hooks/useCommonClassName.js';
import '../../hooks/useFormDisabled.js';
import './props.js';
import 'lodash/cloneDeep';

const sizeClassMap = {
  small: "s",
  medium: "m",
  large: "l"
};
var SelectPanel = defineComponent({
  name: "LSelectPanel",
  components: {
    TOption: _Option
  },
  props: ["inputValue", "panelTopContent", "panelBottomContent", "size", "options", "empty", "filter", "loading", "loadingText", "multiple", "scroll", "creatable", "filterable"],
  setup(props) {
    const {
      options,
      inputValue
    } = toRefs(props);
    const renderTNode = useLNodeJSX();
    const {
      t,
      global
    } = useConfig("select");
    const selectProvider = inject("tSelect");
    const COMPONENT_NAME = usePrefixClass("select");
    const panelContentRef = computed(() => selectProvider.getOverlayElm());
    const {
      type,
      rowHeight = 28,
      bufferSize = 20,
      isFixedRowHeight = false,
      threshold = 100
    } = props.scroll || {};
    const displayOptions = computed(() => {
      if (!inputValue.value || !(props.filterable || isFunction(props.filter))) return options.value;
      const filterMethods = option => {
        if (isFunction(props.filter)) return props.filter(`${props.inputValue}`, option);
        return option.label?.toLowerCase?.().indexOf(`${props.inputValue}`.toLowerCase()) > -1;
      };
      const res = [];
      let groupIndex = isCreateOptionShown.value ? 1 : 0;
      props.options.forEach(option => {
        if (option.group && option.children) {
          res.push({
            ...option,
            children: option.children.filter(filterMethods).reduce((pre, cur) => {
              pre.push({
                ...cur,
                index: groupIndex
              });
              groupIndex += 1;
              return pre;
            }, [])
          });
        }
        if (filterMethods(option)) res.push({
          ...option,
          index: groupIndex + res.length
        });
      });
      return res;
    });
    const getDisplayOptions = () => {
      const arr = [];
      if (isCreateOptionShown.value) arr.push({
        label: String(inputValue.value),
        value: String(inputValue.value),
        isCreated: true
      });
      arr.push(...displayOptions.value);
      return arr;
    };
    const isCreateOptionShown = computed(() => !!(props.creatable && props.filterable && props.inputValue && flattenOptions(options.value).find(v => v.label === props.inputValue) === void 0));
    const isEmpty = computed(() => !(displayOptions.value.length > 0));
    const isVirtual = computed(() => props.scroll?.type === "virtual" && props.options?.length > (props.scroll?.threshold || 100));
    const {
      trs = null,
      visibleData = null,
      handleScroll: handleVirtualScroll = null,
      scrollHeight = null,
      translateY = null,
      handleRowMounted = null
    } = type === "virtual" ? useVirtualScroll({
      container: panelContentRef,
      data: displayOptions,
      fixedHeight: isFixedRowHeight,
      lineHeight: rowHeight,
      bufferSize,
      threshold
    }) : {};
    let lastScrollY = -1;
    const onInnerVirtualScroll = e => {
      if (!isVirtual.value) return;
      const target = e.target || e.srcElement;
      const top = target.scrollTop;
      if (Math.abs(lastScrollY - top) > 5) {
        handleVirtualScroll();
        lastScrollY = top;
      } else {
        lastScrollY = -1;
      }
    };
    onMounted(() => {
      if (props.scroll?.type === "virtual") selectProvider.getOverlayElm().addEventListener("scroll", onInnerVirtualScroll);
    });
    onBeforeUnmount(() => {
      if (props.scroll?.type === "virtual") selectProvider.getOverlayElm().removeEventListener("scroll", onInnerVirtualScroll);
    });
    return {
      t,
      global,
      isEmpty,
      renderTNode,
      selectProvider,
      isCreateOptionShown,
      trs,
      isVirtual,
      onInnerVirtualScroll,
      visibleData,
      scrollHeight,
      translateY,
      scrollType: props.scroll?.type,
      handleRowMounted,
      bufferSize,
      threshold,
      displayOptions,
      getDisplayOptions,
      componentName: COMPONENT_NAME
    };
  },
  methods: {
    renderEmptyContent() {
      const h = this.$createElement;
      if (this.empty && typeof this.empty === "string") return h("div", {
        "class": `${this.componentName}__empty`
      }, [this.empty]);
      return renderLNodeJSXDefault(this, "empty", h("div", {
        "class": `${this.componentName}__empty`
      }, [this.t(this.global.empty)]));
    },
    renderLoadingContent() {
      const h = this.$createElement;
      if (this.loadingText && typeof this.loadingText === "string") return h("div", {
        "class": `${this.componentName}__loading-tips`
      }, [this.loadingText]);
      return renderLNodeJSXDefault(this, "loadingText", h("div", {
        "class": `${this.componentName}__loading-tips`
      }, [this.t(this.global.loadingText)]));
    },
    renderCreateOption() {
      const h = this.$createElement;
      const on = this.isVirtual ? {
        onRowMounted: this.handleRowMounted
      } : {};
      return h("ul", {
        "class": [`${this.componentName}__create-option`, `${this.componentName}__list`]
      }, [h("t-option", helper([{
        "attrs": {
          "multiple": this.multiple,
          "index": 0,
          "isCreatedOption": true,
          "value": this.inputValue,
          "label": this.inputValue,
          "trs": this.trs,
          "scrollType": this.scrollType,
          "isVirtual": this.isVirtual,
          "bufferSize": this.bufferSize
        },
        "class": `${this.componentName}__create-option--special`
      }, {
        "on": on
      }]))]);
    },
    renderOptionsContent(options) {
      const h = this.$createElement;
      const on = this.isVirtual ? {
        onRowMounted: this.handleRowMounted
      } : {};
      return h("ul", {
        "class": `${this.componentName}__list`
      }, [options.map((item, index) => {
        if (item.group) {
          return h("t-option-group", {
            "attrs": {
              "label": item.group,
              "divider": item.divider
            }
          }, [this.renderOptionsContent(item.children)]);
        }
        const scrollProps = this.isVirtual ? {
          rowIndex: item.$index,
          trs: this.trs,
          scrollType: this.scrollType,
          isVirtual: this.isVirtual,
          bufferSize: this.bufferSize
        } : {
          key: index
        };
        return h("t-option", helper([{
          "class": item.class,
          "style": item.style,
          "props": {
            ...{
              ...item,
              ...scrollProps
            }
          },
          "attrs": {
            "multiple": this.multiple
          },
          "scopedSlots": {
            default: item.slots
          },
          "key": `${item.$index || ""}_${index}`
        }, {
          "on": on
        }]));
      })]);
    },
    renderPanelContent() {
      let innerStyle = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      const h = this.$createElement;
      const {
        loading
      } = this;
      return h("div", {
        "class": [`${this.componentName}__dropdown-inner`, `${this.componentName}__dropdown-inner--size-${sizeClassMap[this.size]}`],
        "style": innerStyle
      }, [this.renderTNode("panelTopContent"), this.isCreateOptionShown && this.renderCreateOption(), loading && this.renderLoadingContent(), !loading && this.isEmpty && !this.isCreateOptionShown && this.renderEmptyContent(), !loading && !this.isEmpty && this.renderOptionsContent(this.isVirtual && this.visibleData ? this.visibleData : this.displayOptions), this.renderTNode("panelBottomContent")]);
    }
  },
  render() {
    const h = arguments[0];
    if (this.isVirtual) {
      const cursorTranslate = `translate(0, ${this.scrollHeight}px)`;
      const cursorTranslateStyle = {
        "position": "absolute",
        "width": "1px",
        "height": "1px",
        "transition": "transform 0.2s",
        "transform": cursorTranslate,
        "-ms-transform": cursorTranslate,
        "-moz-transform": cursorTranslate,
        "-webkit-transform": cursorTranslate
      };
      const translate = `translate(0, ${this.translateY}px)`;
      const virtualStyle = {
        "transform": translate,
        "-ms-transform": translate,
        "-moz-transform": translate,
        "-webkit-transform": translate
      };
      return h("div", [h("div", {
        "style": {
          ...cursorTranslateStyle
        }
      }), this.renderPanelContent(virtualStyle)]);
    }
    return this.renderPanelContent();
  }
});

export { SelectPanel as default };
//# sourceMappingURL=select-panel.js.map
