'use strict';

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

var vue = require('vue');
require('../../../hooks/index.js');
var useLocale = require('../../../hooks/useLocale.js');

const _hoisted_1 = {
  key: 1,
  class: "f_select__pagination"
};
var _sfc_main = /* @__PURE__ */ vue.defineComponent({
  ...{
    name: "FSelect"
  },
  __name: "index",
  props: {
    modelValue: { default: void 0 },
    multiple: { type: Boolean, default: false },
    width: {},
    valueCustom: { default: "key" },
    labelCustom: { default: "label" },
    customLabel: { default: "" },
    optionSource: { default: () => [] },
    filterable: { type: Boolean, default: true },
    isShowPagination: { type: Boolean, default: false },
    paginationOption: { default: () => ({
      pageSize: 6,
      currentPage: 1,
      pagerCount: 5,
      total: 0
    }) },
    useVirtual: { type: Boolean, default: false },
    returnObject: { type: Boolean, default: false },
    isCached: { type: Boolean, default: true },
    isRadioEchoLabel: { type: Boolean, default: true },
    radioSelectValLabel: { default: "" },
    selectAllTxt: { default: "" }
  },
  emits: ["update:modelValue", "change", "input", "select-input"],
  setup(__props, { expose: __expose, emit: __emit }) {
    const { t } = useLocale.useLocale();
    const props = __props;
    const fselectRef = vue.ref();
    const filteredOptionsCount = vue.ref(1);
    const slots = vue.useSlots();
    const selectAllTxtText = vue.computed(() => props.selectAllTxt || t("plus.select.selectAllTxt"));
    const emits = __emit;
    const childSelectedValue = vue.computed({
      get() {
        return props.modelValue;
      },
      set(val) {
        emits("update:modelValue", val);
      }
    });
    const currentOptions = vue.ref(props.optionSource);
    const cachedOptions = vue.ref(/* @__PURE__ */ new Map());
    const mergedOptions = vue.computed(() => {
      const currentValues = currentOptions.value.length > 0 && currentOptions.value.map((item) => item[props.valueCustom]) || [];
      const cached = Array.from(cachedOptions.value.values()).filter(
        (item) => !currentValues.includes(item[props.valueCustom])
      );
      return props.isShowPagination && props.isCached ? [...currentOptions.value, ...cached] : [...currentOptions.value];
    });
    vue.watch(
      () => props.optionSource,
      (newVal) => {
        currentOptions.value = newVal || [];
        newVal.length > 0 && newVal.forEach((item) => {
          const isObject = typeof childSelectedValue.value === "object";
          const condition = isObject ? Array.isArray(childSelectedValue.value) && childSelectedValue.value.includes(item[props.valueCustom]) : childSelectedValue.value === item[props.valueCustom];
          if (condition) {
            cachedOptions.value.set(item[props.valueCustom], item);
          }
        });
      }
    );
    vue.watch(
      () => props.radioSelectValLabel,
      (val) => {
        if (val && props.isRadioEchoLabel && !props.multiple && props.isShowPagination) {
          childSelectedValue.value = val;
        }
      },
      { deep: true }
    );
    vue.onMounted(() => {
      currentOptions.value.forEach((item) => {
        const isObject = typeof childSelectedValue.value === "object";
        const condition = isObject ? Array.isArray(childSelectedValue.value) && childSelectedValue.value.includes(item[props.valueCustom]) : childSelectedValue.value === item[props.valueCustom];
        if (condition) {
          cachedOptions.value.set(item[props.valueCustom], item);
        }
      });
      if (props.radioSelectValLabel && props.isRadioEchoLabel && !props.multiple && props.isShowPagination) {
        childSelectedValue.value = props.radioSelectValLabel;
      }
    });
    const handlesSelectInput = (e) => {
      if (props.filterable) {
        filteredOptionsCount.value = fselectRef.value.filteredOptionsCount;
      }
      emits("select-input", e.target.value);
    };
    const handlesChange = (value) => {
      if (Array.isArray(value)) {
        const newCache = /* @__PURE__ */ new Map();
        value.forEach((val) => {
          const item = mergedOptions.value.find((opt) => opt[props.valueCustom] === val);
          if (item) newCache.set(val, item);
        });
        cachedOptions.value = newCache;
      } else {
        const item = mergedOptions.value.find((opt) => opt[props.valueCustom] === value);
        cachedOptions.value = item ? /* @__PURE__ */ new Map([[value, item]]) : /* @__PURE__ */ new Map();
      }
      emits("change", value);
    };
    const selectChecked = vue.computed({
      get() {
        const _deval = props.modelValue;
        const list = props.optionSource.filter((item) => {
          return !item.disabled;
        });
        return (_deval == null ? void 0 : _deval.length) === list.length;
      },
      set(val) {
        const list = props.optionSource.filter((item) => {
          return !item.disabled;
        });
        return (val == null ? void 0 : val.length) === list.length;
      }
    });
    const selectAll = (val) => {
      let options = JSON.parse(JSON.stringify(props.optionSource));
      options = options.filter((item) => {
        return !item.disabled;
      });
      if (val) {
        const selectedAllValue = options.map((item) => {
          return item[props.valueCustom];
        });
        emits("update:modelValue", selectedAllValue);
      } else {
        emits("update:modelValue", null);
      }
    };
    const customLabelHandler = (_item) => {
      let fun = new Function("_item", "return " + props.customLabel);
      return fun(_item);
    };
    const clear = () => {
      emits("update:modelValue", null);
    };
    __expose({ clear });
    return (_ctx, _cache) => {
      const _component_el_checkbox = vue.resolveComponent("el-checkbox");
      const _component_el_option = vue.resolveComponent("el-option");
      const _component_el_pagination = vue.resolveComponent("el-pagination");
      return vue.openBlock(), vue.createBlock(vue.resolveDynamicComponent(!__props.useVirtual ? "el-select" : "el-select-v2"), vue.mergeProps({
        "popper-class": "f_select",
        ref_key: "fselectRef",
        ref: fselectRef,
        modelValue: childSelectedValue.value,
        "onUpdate:modelValue": _cache[4] || (_cache[4] = ($event) => childSelectedValue.value = $event),
        options: !__props.useVirtual ? null : __props.optionSource,
        style: { width: __props.width || "100%" },
        onChange: handlesChange,
        onInput: handlesSelectInput
      }, {
        clearable: true,
        filterable: __props.filterable,
        multiple: __props.multiple,
        ..._ctx.$attrs
      }), vue.createSlots({
        default: vue.withCtx(() => [
          !__props.useVirtual ? (vue.openBlock(), vue.createElementBlock(
            vue.Fragment,
            { key: 0 },
            [
              __props.multiple && !__props.isShowPagination ? (vue.openBlock(), vue.createBlock(_component_el_checkbox, {
                key: 0,
                modelValue: selectChecked.value,
                "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => selectChecked.value = $event),
                onChange: selectAll,
                class: "all_checkbox"
              }, {
                default: vue.withCtx(() => [
                  vue.createTextVNode(
                    vue.toDisplayString(selectAllTxtText.value),
                    1
                    /* TEXT */
                  )
                ]),
                _: 1
                /* STABLE */
              }, 8, ["modelValue"])) : vue.createCommentVNode("v-if", true),
              (vue.openBlock(true), vue.createElementBlock(
                vue.Fragment,
                null,
                vue.renderList(mergedOptions.value, (item, index) => {
                  return vue.openBlock(), vue.createBlock(_component_el_option, {
                    key: index + "i",
                    label: __props.customLabel ? customLabelHandler(item) : item[__props.labelCustom],
                    value: __props.returnObject ? item : item[__props.valueCustom],
                    disabled: item.disabled
                  }, vue.createSlots({
                    _: 2
                    /* DYNAMIC */
                  }, [
                    vue.renderList(vue.unref(slots), (_index, name) => {
                      return {
                        name,
                        fn: vue.withCtx((data) => [
                          vue.renderSlot(_ctx.$slots, name, vue.mergeProps({ ref_for: true }, data))
                        ])
                      };
                    })
                  ]), 1032, ["label", "value", "disabled"]);
                }),
                128
                /* KEYED_FRAGMENT */
              )),
              __props.isShowPagination && filteredOptionsCount.value > 0 ? (vue.openBlock(), vue.createElementBlock("div", _hoisted_1, [
                vue.createVNode(_component_el_pagination, vue.mergeProps({
                  "current-page": __props.paginationOption.currentPage,
                  "onUpdate:currentPage": _cache[1] || (_cache[1] = ($event) => __props.paginationOption.currentPage = $event),
                  "page-size": __props.paginationOption.pageSize,
                  "onUpdate:pageSize": _cache[2] || (_cache[2] = ($event) => __props.paginationOption.pageSize = $event),
                  layout: __props.paginationOption.layout || "total, prev, pager, next, jumper",
                  "pager-count": __props.paginationOption.pagerCount,
                  total: __props.paginationOption.total,
                  onInput: _cache[3] || (_cache[3] = vue.withModifiers((e) => emits("input", e.target.value), ["stop"]))
                }, {
                  size: "small",
                  background: true,
                  ...__props.paginationOption.bind,
                  ..._ctx.$attrs
                }), null, 16, ["current-page", "page-size", "layout", "pager-count", "total"])
              ])) : vue.createCommentVNode("v-if", true)
            ],
            64
            /* STABLE_FRAGMENT */
          )) : vue.createCommentVNode("v-if", true)
        ]),
        _: 2
        /* DYNAMIC */
      }, [
        vue.renderList(vue.unref(slots), (_index, name) => {
          return {
            name,
            fn: vue.withCtx((data) => [
              vue.renderSlot(_ctx.$slots, name, vue.normalizeProps(vue.guardReactiveProps(data)))
            ])
          };
        })
      ]), 1040, ["modelValue", "options", "style"]);
    };
  }
});

exports.default = _sfc_main;
