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

'use strict';

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

var helper = require('../../chunks/helper.js');
var VueCompositionAPI = require('@vue/composition-api');
var isFunction = require('lodash/isFunction');
var hooks_lnode = require('../../hooks/lnode.js');
var utils_renderNode = require('../../utils/render-node.js');
var components_configProvider_useConfig = require('../config-provider/useConfig.js');
var hooks_useVirtualScroll = require('../../hooks/useVirtualScroll.js');
var components_select_option = require('./option.js');
var components_select_utils = require('./utils.js');
require('lodash/isEmpty');
require('lodash/camelCase');
require('lodash/kebabCase');
require('../../hooks/render-lnode.js');
require('lodash');
require('vue');
require('../config-provider/context.js');
require('lodash/merge');
require('lodash/mergeWith');
require('../../chunks/zh_CN.js');
require('../../utils/ripple.js');
require('../../chunks/set-style.js');
require('../../config.js');
require('../config-provider/config-receiver.js');
require('../checkbox/index.js');
require('../../utils/map-props.js');
require('../../utils/withInstall.js');
require('lodash/capitalize');
require('../checkbox/group.js');
require('lodash/intersection');
require('../../chunks/log.js');
require('../../chunks/_commonjsHelpers-fe796db6.js');
require('../../utils/event.js');
require('../../utils/helper.js');
require('../../utils/mixins.js');
require('../checkbox/checkbox.js');
require('../checkbox/props.js');
require('../../hooks/useLazyLoad.js');
require('../../chunks/observe.js');
require('../../hooks/useCommonClassName.js');
require('../../hooks/useFormDisabled.js');
require('./props.js');
require('lodash/cloneDeep');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var isFunction__default = /*#__PURE__*/_interopDefaultLegacy(isFunction);

const sizeClassMap = {
  small: "s",
  medium: "m",
  large: "l"
};
var SelectPanel = VueCompositionAPI.defineComponent({
  name: "LSelectPanel",
  components: {
    TOption: components_select_option["default"]
  },
  props: ["inputValue", "panelTopContent", "panelBottomContent", "size", "options", "empty", "filter", "loading", "loadingText", "multiple", "scroll", "creatable", "filterable"],
  setup(props) {
    const {
      options,
      inputValue
    } = VueCompositionAPI.toRefs(props);
    const renderTNode = hooks_lnode.useLNodeJSX();
    const {
      t,
      global
    } = components_configProvider_useConfig.useConfig("select");
    const selectProvider = VueCompositionAPI.inject("tSelect");
    const COMPONENT_NAME = components_configProvider_useConfig.usePrefixClass("select");
    const panelContentRef = VueCompositionAPI.computed(() => selectProvider.getOverlayElm());
    const {
      type,
      rowHeight = 28,
      bufferSize = 20,
      isFixedRowHeight = false,
      threshold = 100
    } = props.scroll || {};
    const displayOptions = VueCompositionAPI.computed(() => {
      if (!inputValue.value || !(props.filterable || isFunction__default["default"](props.filter))) return options.value;
      const filterMethods = option => {
        if (isFunction__default["default"](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 = VueCompositionAPI.computed(() => !!(props.creatable && props.filterable && props.inputValue && components_select_utils.flattenOptions(options.value).find(v => v.label === props.inputValue) === void 0));
    const isEmpty = VueCompositionAPI.computed(() => !(displayOptions.value.length > 0));
    const isVirtual = VueCompositionAPI.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" ? hooks_useVirtualScroll["default"]({
      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;
      }
    };
    VueCompositionAPI.onMounted(() => {
      if (props.scroll?.type === "virtual") selectProvider.getOverlayElm().addEventListener("scroll", onInnerVirtualScroll);
    });
    VueCompositionAPI.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 utils_renderNode.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 utils_renderNode.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.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.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();
  }
});

exports["default"] = SelectPanel;
//# sourceMappingURL=select-panel.js.map
