import { defineComponent, ref, useSlots, computed, watch, onMounted, resolveComponent, openBlock, createBlock, resolveDynamicComponent, mergeProps, createSlots, withCtx, createElementBlock, Fragment, createTextVNode, toDisplayString, createCommentVNode, renderList, unref, renderSlot, createVNode, withModifiers, normalizeProps, guardReactiveProps } from 'vue';
import '../../../hooks/index.mjs';
import { useLocale } from '../../../hooks/useLocale.mjs';

const _hoisted_1 = {
  key: 1,
  class: "f_select__pagination"
};
var _sfc_main = /* @__PURE__ */ 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();
    const props = __props;
    const fselectRef = ref();
    const filteredOptionsCount = ref(1);
    const slots = useSlots();
    const selectAllTxtText = computed(() => props.selectAllTxt || t("plus.select.selectAllTxt"));
    const emits = __emit;
    const childSelectedValue = computed({
      get() {
        return props.modelValue;
      },
      set(val) {
        emits("update:modelValue", val);
      }
    });
    const currentOptions = ref(props.optionSource);
    const cachedOptions = ref(/* @__PURE__ */ new Map());
    const mergedOptions = 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];
    });
    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);
          }
        });
      }
    );
    watch(
      () => props.radioSelectValLabel,
      (val) => {
        if (val && props.isRadioEchoLabel && !props.multiple && props.isShowPagination) {
          childSelectedValue.value = val;
        }
      },
      { deep: true }
    );
    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 = 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 = resolveComponent("el-checkbox");
      const _component_el_option = resolveComponent("el-option");
      const _component_el_pagination = resolveComponent("el-pagination");
      return openBlock(), createBlock(resolveDynamicComponent(!__props.useVirtual ? "el-select" : "el-select-v2"), 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
      }), createSlots({
        default: withCtx(() => [
          !__props.useVirtual ? (openBlock(), createElementBlock(
            Fragment,
            { key: 0 },
            [
              __props.multiple && !__props.isShowPagination ? (openBlock(), 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: withCtx(() => [
                  createTextVNode(
                    toDisplayString(selectAllTxtText.value),
                    1
                    /* TEXT */
                  )
                ]),
                _: 1
                /* STABLE */
              }, 8, ["modelValue"])) : createCommentVNode("v-if", true),
              (openBlock(true), createElementBlock(
                Fragment,
                null,
                renderList(mergedOptions.value, (item, index) => {
                  return openBlock(), 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
                  }, createSlots({
                    _: 2
                    /* DYNAMIC */
                  }, [
                    renderList(unref(slots), (_index, name) => {
                      return {
                        name,
                        fn: withCtx((data) => [
                          renderSlot(_ctx.$slots, name, mergeProps({ ref_for: true }, data))
                        ])
                      };
                    })
                  ]), 1032, ["label", "value", "disabled"]);
                }),
                128
                /* KEYED_FRAGMENT */
              )),
              __props.isShowPagination && filteredOptionsCount.value > 0 ? (openBlock(), createElementBlock("div", _hoisted_1, [
                createVNode(_component_el_pagination, 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] = 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"])
              ])) : createCommentVNode("v-if", true)
            ],
            64
            /* STABLE_FRAGMENT */
          )) : createCommentVNode("v-if", true)
        ]),
        _: 2
        /* DYNAMIC */
      }, [
        renderList(unref(slots), (_index, name) => {
          return {
            name,
            fn: withCtx((data) => [
              renderSlot(_ctx.$slots, name, normalizeProps(guardReactiveProps(data)))
            ])
          };
        })
      ]), 1040, ["modelValue", "options", "style"]);
    };
  }
});

export { _sfc_main as default };
