import { defineComponent, useAttrs, reactive, computed, ref, watch, onMounted, onUnmounted, resolveComponent, createElementBlock, openBlock, Fragment, createVNode, createBlock, createCommentVNode, mergeProps, unref, withCtx, normalizeClass, createElementVNode, renderList, resolveDynamicComponent, createTextVNode, toDisplayString, renderSlot, withModifiers } from 'vue';
import '../../../utils/index.mjs';
import { cloneDeep } from 'lodash-es';
import { ops } from './config.mjs';
import { customSearcherProps } from './custom-searcher.mjs';
import './scheme-name.vue.mjs';
import { createNamespace } from '../../../utils/create-namespace.mjs';
import { getRandomCode } from '../../../utils/random-code.mjs';
import _sfc_main$1 from './scheme-name.vue2.mjs';

"use strict";
const _hoisted_1 = {
  key: 1,
  style: { minWidth: "250px", flex: 1 }
};
var _sfc_main = /* @__PURE__ */ defineComponent({
  ...{ name: "LlCustomSearcher" },
  __name: "custom-searcher",
  props: customSearcherProps,
  emits: ["update:open", "field-select"],
  setup(__props, { expose: __expose, emit: __emit }) {
    const props = __props;
    const emits = __emit;
    const bem = createNamespace("custom-searcher");
    const attrs = useAttrs();
    const searchList = reactive([
      { key: null, operator: null, value: void 0 }
    ]);
    const localList = computed(() => [...props.fieldList]);
    const storageVersion = ref(0);
    const nameOpen = ref(false);
    const localScheme = computed({
      get: () => {
        storageVersion.value;
        if (props.useLocalStorage && props.localKey) {
          try {
            const item = localStorage.getItem(props.localKey);
            return item ? JSON.parse(item) : [];
          } catch {
            return [];
          }
        } else {
          return [];
        }
      },
      set: (value) => {
        storageVersion.value;
        if (props.useLocalStorage && props.localKey) {
          try {
            return localStorage.setItem(props.localKey, JSON.stringify(value));
          } catch (error) {
            return console.error("\u4FDD\u5B58\u5230\u672C\u5730\u5B58\u50A8\u5931\u8D25:", error);
          }
        }
      }
    });
    const newOpen = computed({
      get() {
        return nameOpen.value || props.open;
      },
      set(o) {
        if (!nameOpen.value) {
          emits("update:open", o);
        }
      }
    });
    const disabledAdd = computed(() => {
      return localList.value.length === searchList.length || props.maxSearchCount > 0 && props.maxSearchCount <= searchList.length;
    });
    const configMap = computed(() => {
      const map = {};
      localList.value.forEach((fieldConfig) => {
        map[fieldConfig.key] = fieldConfig;
      });
      return map;
    });
    const handleAdd = () => {
      searchList.push({ key: null, operator: null, value: void 0 });
    };
    const handleCancel = () => {
      setTimeout(() => {
        nameOpen.value = false;
      }, 100);
    };
    const handleOk = (name) => {
      setTimeout(() => {
        nameOpen.value = false;
      }, 100);
      localScheme.value = [
        ...localScheme.value,
        {
          key: getRandomCode(),
          name,
          value: searchList.filter((item) => item.key)
        }
      ];
      storageVersion.value++;
    };
    const useScheme = (idx) => {
      searchList.length = 0;
      searchList.push(...cloneDeep(localScheme.value[idx].value));
      filterSearchList();
    };
    const clearScheme = (idx) => {
      const copyArr = cloneDeep(localScheme.value);
      copyArr.splice(idx, 1);
      localScheme.value = [...copyArr];
      storageVersion.value++;
    };
    const handleRemove = (idx) => {
      searchList.splice(idx, 1);
    };
    const handleField = (value, option) => {
      const target = searchList.find((item) => item.key === value);
      if (target) {
        if (!props.operatorSelectable) {
          target.operator = option.conditionType || null;
        }
        if (option?.props?.value) {
          target.value = option.props.value;
        } else {
          target.value = void 0;
        }
      }
      emits("field-select", value, option);
    };
    const handleOperator = (value, item) => {
      if (item.operator === "isEmpty" || item.operator === "isNotEmpty" || item.operator === "isNull" || item.operator === "isNotNull" || item.operator === "isNullOrEmpty") {
        item.value = void 0;
      }
    };
    const getValue = () => {
      return searchList;
    };
    const clearValue = (range, fields) => {
      if (range === "field") {
        if (fields && fields?.length > 0) {
          for (let i = searchList.length - 1; i >= 0; i--) {
            if (fields.includes(searchList[i].key)) {
              searchList.splice(i, 1);
            }
          }
        }
      } else {
        searchList.length = 0;
      }
      if (searchList.length === 0) {
        searchList.push({ key: null, operator: null, value: void 0 });
      }
    };
    const setValue = (config) => {
      Object.entries(config).forEach(([key, updates]) => {
        const targetItem = searchList.find((item) => item.key === key);
        if (targetItem && updates) {
          Object.assign(targetItem, updates);
        }
      });
    };
    const handleConfig = (config) => {
      Object.entries(config).forEach(([key, updates]) => {
        const targetObj = localList.value.find((i) => i.key === key);
        if (targetObj && updates) {
          Object.assign(targetObj.props, updates);
        }
      });
    };
    const filterSearchList = () => {
      const validFields = localList.value.map((item) => item.key).filter(Boolean);
      for (let i = searchList.length - 1; i >= 0; i--) {
        if (!validFields.includes(searchList[i].key && searchList[i].key)) {
          searchList.splice(i, 1);
        }
      }
      if (searchList.length === 0) {
        searchList.push({ key: null, operator: null, value: void 0 });
      }
    };
    watch(() => localList.value, filterSearchList, { deep: true });
    watch(
      () => props.operatorSelectable,
      () => {
        searchList.length = 0;
        searchList.push({ key: null, operator: null, value: void 0 });
      }
    );
    __expose({ getValue, clearValue, setValue, handleConfig });
    onMounted(() => {
      nameOpen.value = false;
    });
    onUnmounted(() => {
      if (props.localKey && localScheme.value.length === 0) {
        localStorage.removeItem(props.localKey);
      }
    });
    return (_ctx, _cache) => {
      const _component_ll_icon_base_pro = resolveComponent("ll-icon-base-pro");
      const _component_a_badge = resolveComponent("a-badge");
      const _component_ll_select = resolveComponent("ll-select");
      const _component_ll_input = resolveComponent("ll-input");
      const _component_ll_icon = resolveComponent("ll-icon");
      const _component_ll_button = resolveComponent("ll-button");
      const _component_ll_tag = resolveComponent("ll-tag");
      const _component_a_form_item_rest = resolveComponent("a-form-item-rest");
      const _component_a_popover = resolveComponent("a-popover");
      return openBlock(), createElementBlock(
        Fragment,
        null,
        [
          createVNode(_component_a_popover, mergeProps(unref(attrs), {
            open: newOpen.value,
            "onUpdate:open": _cache[1] || (_cache[1] = ($event) => newOpen.value = $event),
            arrow: false,
            trigger: "click",
            placement: _ctx.placement,
            "overlay-class-name": `${unref(bem).b()}`
          }), {
            content: withCtx(() => [
              createVNode(_component_a_form_item_rest, null, {
                default: withCtx(() => [
                  createElementVNode(
                    "div",
                    {
                      class: normalizeClass(unref(bem).e("content"))
                    },
                    [
                      (openBlock(true), createElementBlock(
                        Fragment,
                        null,
                        renderList(searchList, (item, idx) => {
                          return openBlock(), createElementBlock(
                            "div",
                            {
                              key: idx,
                              class: normalizeClass(unref(bem).e("list-item"))
                            },
                            [
                              createCommentVNode(" \u5B57\u6BB5\u540D "),
                              createVNode(_component_ll_select, {
                                value: item.key,
                                "onUpdate:value": ($event) => item.key = $event,
                                style: { "width": "150px" },
                                placeholder: "\u8BF7\u9009\u62E9\u5B57\u6BB5",
                                size: "small",
                                "field-names": {
                                  label: "title",
                                  value: "key",
                                  options: "options"
                                },
                                options: localList.value.map((i) => ({
                                  ...i,
                                  disabled: searchList.some((y) => y.key === i.key)
                                })),
                                onSelect: handleField
                              }, null, 8, ["value", "onUpdate:value", "options"]),
                              createCommentVNode(" \u8FD0\u7B97\u7B26 "),
                              createVNode(_component_ll_select, {
                                value: item.operator,
                                "onUpdate:value": ($event) => item.operator = $event,
                                style: { "width": "150px" },
                                disabled: !_ctx.operatorSelectable,
                                placeholder: "\u8BF7\u9009\u62E9\u8FD0\u7B97\u7B26",
                                options: item.key ? [...unref(ops).base, ...unref(ops).text, ...unref(ops).compare] : [],
                                size: "small",
                                onSelect: (value) => handleOperator(value, item)
                              }, null, 8, ["value", "onUpdate:value", "disabled", "options", "onSelect"]),
                              createCommentVNode(" \u503C "),
                              item.operator !== "isEmpty" && item.operator !== "isNotEmpty" && item.operator !== "isNull" && item.operator !== "isNotNull" && item.operator !== "isNullOrEmpty" ? (openBlock(), createElementBlock(
                                Fragment,
                                { key: 0 },
                                [
                                  !item.key ? (openBlock(), createBlock(_component_ll_input, {
                                    key: 0,
                                    value: item.value,
                                    "onUpdate:value": ($event) => item.value = $event,
                                    placeholder: "\u8BF7\u8F93\u5165",
                                    style: { minWidth: "250px", flex: 1 },
                                    size: "small"
                                  }, null, 8, ["value", "onUpdate:value"])) : (openBlock(), createBlock(resolveDynamicComponent(configMap.value[item.key].type), mergeProps(
                                    {
                                      key: 1,
                                      ref_for: true
                                    },
                                    Object.fromEntries(
                                      Object.entries(configMap.value[item.key].props).filter(
                                        ([key]) => !key.toLowerCase().includes("formcreate")
                                      )
                                    ),
                                    {
                                      value: item.value,
                                      "onUpdate:value": ($event) => item.value = $event,
                                      style: { minWidth: "250px", flex: 1 },
                                      size: "small"
                                    }
                                  ), null, 16, ["value", "onUpdate:value"]))
                                ],
                                64
                                /* STABLE_FRAGMENT */
                              )) : (openBlock(), createElementBlock("div", _hoisted_1)),
                              createCommentVNode(" \u79FB\u9664\u56FE\u6807 "),
                              searchList.length > 1 ? (openBlock(), createBlock(_component_ll_icon, {
                                key: 2,
                                "icon-name": "icon-remove",
                                class: normalizeClass(unref(bem).e("remove-icon")),
                                size: 14,
                                onClick: ($event) => handleRemove(idx)
                              }, null, 8, ["class", "onClick"])) : createCommentVNode("v-if", true)
                            ],
                            2
                            /* CLASS */
                          );
                        }),
                        128
                        /* KEYED_FRAGMENT */
                      ))
                    ],
                    2
                    /* CLASS */
                  ),
                  createElementVNode(
                    "div",
                    {
                      class: normalizeClass(unref(bem).e("operate"))
                    },
                    [
                      createElementVNode(
                        "div",
                        {
                          class: normalizeClass(unref(bem).e("operate-btn"))
                        },
                        [
                          createVNode(_component_ll_button, {
                            disabled: disabledAdd.value,
                            type: "text",
                            size: "small",
                            "icon-space": 8,
                            onClick: handleAdd
                          }, {
                            default: withCtx(() => [
                              createVNode(_component_ll_icon, { "icon-name": "icon-list-add" }),
                              createTextVNode(
                                " " + toDisplayString(_ctx.addSearchText || "\u6DFB\u52A0\u7B5B\u9009\u6761\u4EF6"),
                                1
                                /* TEXT */
                              )
                            ]),
                            _: 1
                            /* STABLE */
                          }, 8, ["disabled"]),
                          _ctx.useLocalStorage && _ctx.localKey ? (openBlock(), createBlock(_component_ll_button, {
                            key: 0,
                            disabled: !searchList.some((item) => item.key),
                            class: normalizeClass(unref(bem).e("operate-btn")),
                            type: "text",
                            size: "small",
                            "icon-space": 8,
                            onClick: _cache[0] || (_cache[0] = ($event) => nameOpen.value = true)
                          }, {
                            default: withCtx(() => [
                              createVNode(_component_ll_icon, { "icon-name": "icon-add" }),
                              createTextVNode(
                                " " + toDisplayString(_ctx.saveSchemeText || "\u4FDD\u5B58\u65B9\u6848"),
                                1
                                /* TEXT */
                              )
                            ]),
                            _: 1
                            /* STABLE */
                          }, 8, ["disabled", "class"])) : createCommentVNode("v-if", true)
                        ],
                        2
                        /* CLASS */
                      ),
                      createCommentVNode(" \u64CD\u4F5C\u533A\u63D2\u69FD "),
                      createElementVNode(
                        "div",
                        {
                          class: normalizeClass(unref(bem).e("operate-slot"))
                        },
                        [
                          renderSlot(_ctx.$slots, "operate")
                        ],
                        2
                        /* CLASS */
                      )
                    ],
                    2
                    /* CLASS */
                  ),
                  createCommentVNode(" \u672C\u5730\u65B9\u6848\u5C55\u793A\u533A "),
                  _ctx.useLocalStorage && _ctx.localKey && localScheme.value.length > 0 ? (openBlock(), createElementBlock(
                    "div",
                    {
                      key: 0,
                      class: normalizeClass(unref(bem).e("local-scheme"))
                    },
                    [
                      (openBlock(true), createElementBlock(
                        Fragment,
                        null,
                        renderList(localScheme.value, (item, idx) => {
                          return openBlock(), createBlock(_component_ll_tag, {
                            key: idx,
                            shape: "round",
                            onClick: ($event) => useScheme(idx)
                          }, {
                            default: withCtx(() => [
                              createTextVNode(
                                toDisplayString(item.name) + " ",
                                1
                                /* TEXT */
                              ),
                              createVNode(_component_ll_icon, {
                                "icon-name": "icon-close2",
                                onClick: withModifiers(($event) => clearScheme(idx), ["stop"])
                              }, null, 8, ["onClick"])
                            ]),
                            _: 2
                            /* DYNAMIC */
                          }, 1032, ["onClick"]);
                        }),
                        128
                        /* KEYED_FRAGMENT */
                      ))
                    ],
                    2
                    /* CLASS */
                  )) : createCommentVNode("v-if", true)
                ]),
                _: 3
                /* FORWARDED */
              })
            ]),
            default: withCtx(() => [
              createVNode(_component_a_badge, {
                dot: _ctx.useBadge && _ctx.activeState,
                offset: [-2, 2]
              }, {
                default: withCtx(() => [
                  createVNode(_component_ll_icon_base_pro, {
                    class: normalizeClass(`${unref(bem).e("icon")} ${unref(bem).is(
                      newOpen.value || _ctx.activeState ? "active" : ""
                    )}`),
                    "show-tip": false,
                    "icon-name": _ctx.searchIcon || "icon-screen",
                    "bg-color": "var(--color-fill-tertiary)",
                    "hover-bg-color": "var(--color-fill-secondary)",
                    size: _ctx.size,
                    label: _ctx.label,
                    "icon-size": 16
                  }, null, 8, ["class", "icon-name", "size", "label"])
                ]),
                _: 1
                /* STABLE */
              }, 8, ["dot"])
            ]),
            _: 3
            /* FORWARDED */
          }, 16, ["open", "placement", "overlay-class-name"]),
          nameOpen.value ? (openBlock(), createBlock(_sfc_main$1, {
            key: 0,
            open: nameOpen.value,
            "onUpdate:open": _cache[2] || (_cache[2] = ($event) => nameOpen.value = $event),
            onCancel: handleCancel,
            onOk: handleOk
          }, null, 8, ["open"])) : createCommentVNode("v-if", true)
        ],
        64
        /* STABLE_FRAGMENT */
      );
    };
  }
});

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