import { defineComponent, ref, computed, nextTick, watch, resolveComponent, createElementBlock, openBlock, normalizeClass, unref, normalizeStyle, createBlock, createCommentVNode, Fragment, renderList, withCtx, createElementVNode, toDisplayString, createTextVNode, withKeys } from 'vue';
import { checkableTagProps } from './checkable-tag.mjs';
import '../../../utils/index.mjs';
import { cloneDeep } from 'lodash-es';
import { createNamespace } from '../../../utils/create-namespace.mjs';

"use strict";
var _sfc_main = /* @__PURE__ */ defineComponent({
  ...{ name: "LlCheckableTag" },
  __name: "checkable-tag",
  props: checkableTagProps,
  emits: ["update:value", "change"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emits = __emit;
    const bem = createNamespace("checkable-tag");
    const inputRef = ref();
    const inputValue = ref("");
    const inputVisible = ref(false);
    const newTags = ref([]);
    const labelKey = computed(() => props.fieldNames?.label || "label");
    const valueKey = computed(() => props.fieldNames?.value || "value");
    const newValue = computed({
      get() {
        return Array.isArray(props.value) ? props.value : [];
      },
      set(val) {
        emits("update:value", val);
        emits("change", val);
      }
    });
    const isDisabledAddTag = computed(() => {
      return props.disabled || props.disabledAddTag || props.maxAddableTags && newTags.value.length >= props.maxAddableTags || props.selectionMode === "multiple" && props.addAutoSelect && props.maxChecked && newValue.value.length >= props.maxChecked;
    });
    const isChecked = computed(() => {
      return (tag) => {
        return newValue.value.includes(tag[valueKey.value]);
      };
    });
    const showCloseIcon = computed(() => {
      return (idx) => {
        if (props.deleteRule === "all") {
          return true;
        } else if (props.deleteRule === "none") {
          return false;
        } else if (props.deleteRule === "exceptFirstN") {
          return idx >= props.exceptCount;
        }
        return false;
      };
    });
    const handleClose = (tag) => {
      if (props.disabled || props.disabledCloseTag) return;
      newTags.value = newTags.value.filter(
        (item) => item[valueKey.value] !== tag[valueKey.value]
      );
      if (newValue.value.includes(tag[valueKey.value])) {
        newValue.value = newValue.value.filter(
          (item) => item !== tag[valueKey.value]
        );
      }
    };
    const handleCheck = (tag, checked) => {
      if (props.disabled) return;
      if (props.selectionMode === "single") {
        newValue.value = checked ? [tag[valueKey.value]] : [];
        return;
      }
      if (checked && props.maxChecked && newValue.value.length >= props.maxChecked) {
        return;
      }
      newValue.value = checked ? [...newValue.value, tag[valueKey.value]] : newValue.value.filter((item) => item !== tag[valueKey.value]);
    };
    const showInput = () => {
      if (isDisabledAddTag.value) return;
      inputVisible.value = true;
      nextTick(() => {
        inputRef.value.focus();
      });
    };
    const handleInputConfirm = () => {
      const val = inputValue.value.trim();
      if (val && !newTags.value.some((t) => t[valueKey.value] === val)) {
        newTags.value.push({ [labelKey.value]: val, [valueKey.value]: val });
        if (props.addAutoSelect) {
          if (props.selectionMode === "single") {
            newValue.value = [val];
          } else {
            newValue.value = [...newValue.value, val];
          }
        }
      }
      inputVisible.value = false;
      inputValue.value = "";
    };
    const mergeTags = (tags, value) => {
      if (!Array.isArray(value)) return tags;
      const existValues = new Set(tags.map((t) => t[valueKey.value]));
      const result = [...tags];
      value.forEach((v) => {
        if (!existValues.has(v)) {
          result.push({ [labelKey.value]: v, [valueKey.value]: v });
          existValues.add(v);
        }
      });
      return result;
    };
    watch(
      () => props.options,
      (options) => {
        const baseTags = cloneDeep(options);
        newTags.value = mergeTags(baseTags, props.value);
      },
      { immediate: true, deep: true }
    );
    watch(
      () => props.value,
      (value) => {
        const next = mergeTags(newTags.value, value);
        if (next.length !== newTags.value.length) {
          newTags.value = next;
        }
      },
      { immediate: true, deep: true }
    );
    return (_ctx, _cache) => {
      const _component_ll_icon = resolveComponent("ll-icon");
      const _component_a_checkable_tag = resolveComponent("a-checkable-tag");
      const _component_ll_tag = resolveComponent("ll-tag");
      const _component_ll_input = resolveComponent("ll-input");
      return openBlock(), createElementBlock(
        "div",
        {
          style: normalizeStyle({ gap: `${_ctx.tagGap}px` }),
          class: normalizeClass([unref(bem).b(), unref(bem).is(_ctx.size), unref(bem).is(_ctx.disabled ? "disabled" : "")])
        },
        [
          (openBlock(true), createElementBlock(
            Fragment,
            null,
            renderList(newTags.value, (tag, idx) => {
              return openBlock(), createBlock(_component_a_checkable_tag, {
                key: idx,
                style: normalizeStyle(_ctx.tagMaxWidth ? { maxWidth: `${_ctx.tagMaxWidth}px` } : {}),
                class: normalizeClass([unref(bem).e("tag-content"), unref(bem).is(isChecked.value(tag) ? "checked" : "")]),
                checked: isChecked.value(tag),
                onChange: (checked) => handleCheck(tag, checked)
              }, {
                default: withCtx(() => [
                  createElementVNode(
                    "div",
                    {
                      class: normalizeClass(unref(bem).e("tag"))
                    },
                    [
                      createElementVNode(
                        "span",
                        null,
                        toDisplayString(tag[labelKey.value]),
                        1
                        /* TEXT */
                      ),
                      showCloseIcon.value(idx) ? (openBlock(), createBlock(_component_ll_icon, {
                        key: 0,
                        "icon-name": "icon-close2",
                        onClick: ($event) => handleClose(tag)
                      }, null, 8, ["onClick"])) : createCommentVNode("v-if", true)
                    ],
                    2
                    /* CLASS */
                  )
                ]),
                _: 2
                /* DYNAMIC */
              }, 1032, ["style", "class", "checked", "onChange"]);
            }),
            128
            /* KEYED_FRAGMENT */
          )),
          !_ctx.enableAdd && newTags.value.length === 0 ? (openBlock(), createBlock(_component_ll_tag, {
            key: 0,
            shape: "round"
          }, {
            default: withCtx(() => [
              createTextVNode(
                toDisplayString(_ctx.emptyText || "\u6682\u65E0\u6807\u7B7E"),
                1
                /* TEXT */
              )
            ]),
            _: 1
            /* STABLE */
          })) : createCommentVNode("v-if", true),
          createCommentVNode(" \u65B0\u589E\u6807\u7B7E "),
          _ctx.enableAdd ? (openBlock(), createElementBlock(
            Fragment,
            { key: 1 },
            [
              !inputVisible.value ? (openBlock(), createBlock(_component_ll_tag, {
                key: 0,
                shape: "round",
                icon: {
                  iconName: "icon-add"
                },
                class: normalizeClass([unref(bem).e("add-tag"), unref(bem).is(isDisabledAddTag.value ? "disabled" : "")]),
                onClick: showInput
              }, {
                default: withCtx(() => [
                  createTextVNode(
                    toDisplayString(_ctx.addTagText),
                    1
                    /* TEXT */
                  )
                ]),
                _: 1
                /* STABLE */
              }, 8, ["class"])) : (openBlock(), createBlock(_component_ll_input, {
                key: 1,
                ref_key: "inputRef",
                ref: inputRef,
                value: inputValue.value,
                "onUpdate:value": _cache[0] || (_cache[0] = ($event) => inputValue.value = $event),
                valueModifiers: { trim: true },
                placeholder: _ctx.placeholder,
                size: "small",
                style: normalizeStyle({ width: `${_ctx.inputWidth}px` }),
                class: normalizeClass([unref(bem).e("input")]),
                onBlur: handleInputConfirm,
                onKeyup: withKeys(handleInputConfirm, ["enter"])
              }, null, 8, ["value", "placeholder", "style", "class"]))
            ],
            64
            /* STABLE_FRAGMENT */
          )) : createCommentVNode("v-if", true)
        ],
        6
        /* CLASS, STYLE */
      );
    };
  }
});

export { _sfc_main as default };
//# sourceMappingURL=checkable-tag.vue2.mjs.map
