import "../../../../../node_modules/element-plus/es/index.mjs";
/* empty css                                                             */
/* empty css                                                                               */
/* empty css                                                                */
/* empty css                                                                     */
/* empty css                                                                 */
/* empty css                                                                        */
/* empty css                                                                  */
/* empty css                                                                     */
/* empty css                                                                  */
/* empty css                                                                             */
import "../../../../../node_modules/element-plus/theme-chalk/el-date-picker.css.mjs";
/* empty css                                                                    */
/* empty css                                                                          */
/* empty css                                                                           */
/* empty css                                                                */
import "../../../../../node_modules/element-plus/theme-chalk/el-tab-pane.css.mjs";
import { computed, ref, watch, resolveDirective, createElementBlock, openBlock, createElementVNode, createVNode, createCommentVNode, withCtx, unref, createTextVNode, toDisplayString, Fragment, renderList, createBlock, createSlots, withDirectives, normalizeStyle, resolveDynamicComponent, mergeProps, vShow } from "vue";
import { ArrowLeftBold as arrow_left_bold_default, Search as search_default, Edit as edit_default, Delete as delete_default, Plus as plus_default, Setting as setting_default, Download as download_default, Refresh as refresh_default } from "../../../../../node_modules/@element-plus/icons-vue/dist/index.mjs";
import { VxeToolbar } from "vxe-table";
import { Text } from "../forms/text/index.mjs";
import { Select } from "../forms/select/index.mjs";
import { MultipleSelection } from "../forms/multipleSelection/index.mjs";
import { Date } from "../forms/date/index.mjs";
import { Number } from "../forms/number/index.mjs";
import { reverseHandleSearchData, handleSearchData } from "../../utils/common.mjs";
import { checkFilterMatch } from "../../utils/parseFilterConfig.mjs";
import { getCurrentVueInstance } from "../../utils/getInstance.mjs";
/* empty css                   */
import _export_sfc from "../../../../../_virtual/_plugin-vue_export-helper.mjs";
import { ElIcon } from "../../../../../node_modules/element-plus/es/components/icon/index.mjs";
import { ElTabs, ElTabPane } from "../../../../../node_modules/element-plus/es/components/tabs/index.mjs";
import { ElInput } from "../../../../../node_modules/element-plus/es/components/input/index.mjs";
import { ElButton } from "../../../../../node_modules/element-plus/es/components/button/index.mjs";
import { ElCollapseTransition } from "../../../../../node_modules/element-plus/es/components/collapse-transition/index.mjs";
import { ElForm, ElFormItem } from "../../../../../node_modules/element-plus/es/components/form/index.mjs";
import { ElCheckboxGroup, ElCheckboxButton } from "../../../../../node_modules/element-plus/es/components/checkbox/index.mjs";
import { ElDatePicker } from "../../../../../node_modules/element-plus/es/components/date-picker/index.mjs";
import { ElInputNumber } from "../../../../../node_modules/element-plus/es/components/input-number/index.mjs";
const _hoisted_1 = { class: "dynamic-mode-config" };
const _hoisted_2 = { class: "dynamic-row" };
const _hoisted_3 = {
  key: 0,
  class: "back-icon"
};
const _hoisted_4 = {
  key: 1,
  class: "template-name"
};
const _hoisted_5 = {
  key: 2,
  class: "tab-display-section"
};
const _hoisted_6 = { class: "search-display-section" };
const _hoisted_7 = {
  key: 0,
  class: "search-input-group"
};
const _hoisted_8 = { class: "expand-filter-section" };
const _hoisted_9 = { class: "filter-form-section" };
const _hoisted_10 = { class: "form-items-draggable" };
const _hoisted_11 = {
  key: 1,
  style: { "display": "flex", "align-items": "center", "gap": "8px", "width": "100%" }
};
const _sfc_main = {
  __name: "DynamicQuery",
  props: {
    localConfig: {
      type: Object,
      default: () => ({})
    },
    fieldsData: {
      type: Array,
      default: () => []
    },
    isSubTable: {
      type: Boolean,
      default: false
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    hiddenFormData: {
      type: Object,
      default: {}
    },
    isCache: {
      type: Boolean,
      default: false
    }
  },
  emits: ["click", "search"],
  setup(__props, { emit: __emit }) {
    var _a;
    const props = __props;
    const emit = __emit;
    const queryConfig = computed(() => {
      var _a2;
      return ((_a2 = props.localConfig) == null ? void 0 : _a2.queryConfig) || {};
    });
    const dynamicConfig = computed(() => {
      var _a2;
      return ((_a2 = queryConfig.value) == null ? void 0 : _a2.dynamicConfig) || {};
    });
    const activeTab = ref("");
    const tabConfigs = computed(() => {
      var _a2, _b, _c, _d;
      activeTab.value = ((_b = (_a2 = dynamicConfig.value) == null ? void 0 : _a2.tabConfigs) == null ? void 0 : _b.length) > 0 ? (_c = dynamicConfig.value) == null ? void 0 : _c.tabActive : "";
      return ((_d = dynamicConfig.value) == null ? void 0 : _d.tabConfigs) || [];
    });
    const fieldsData = computed(() => {
      var _a2, _b;
      return [
        ...((_a2 = props.localConfig) == null ? void 0 : _a2.fieldsData) || [],
        ...((_b = props.localConfig) == null ? void 0 : _b.hiddenFields) || []
      ];
    });
    const rightButtons = computed(() => {
      var _a2;
      return (((_a2 = props.localConfig) == null ? void 0 : _a2.customBtns.right) || []).filter((item) => {
        if (!item.showCondition) return true;
        return checkFilterMatch(
          item.showCondition,
          props.hiddenFormData,
          fieldsData.value
        );
      });
    });
    const getBtnIcon = (btnType) => {
      const iconMap = {
        refresh: refresh_default,
        export: download_default,
        personalize: setting_default,
        add: plus_default,
        delete: delete_default,
        edit: edit_default,
        search: search_default
      };
      return iconMap[btnType] || null;
    };
    const getBtnType = (btn) => {
      if (btn.btnType === "custom") {
        return "primary";
      }
      return btn.btnStyle || "default";
    };
    const handleClick = (btn, event) => {
      emit("click", {
        btn,
        event,
        type: "custom"
      });
    };
    const getFieldConfig = (fieldId) => {
      return props.fieldsData.find((field) => field.id === fieldId) || {};
    };
    const filterFields = ref([]);
    filterFields.value = props.localConfig.queryConfig.filterFields.map(
      (filterField) => {
        const fieldConfig = getFieldConfig(filterField.fieldId);
        return {
          ...filterField,
          ...fieldConfig
        };
      }
    );
    const filterValues = ref({});
    const searchInputValue = ref("");
    const ctx = getCurrentVueInstance();
    const route = (_a = ctx.$route) == null ? void 0 : _a.path;
    if (route && props.isCache) {
      const routeParams = JSON.parse(sessionStorage.getItem(route));
      const filters = JSON.parse((routeParams == null ? void 0 : routeParams.filters) || "{}");
      searchInputValue.value = (filters == null ? void 0 : filters.dynamicFilter) || "";
      filterValues.value = reverseHandleSearchData(filters, filterFields.value);
    }
    const showAdvancedFilter = ref(false);
    const toggleAdvancedFilter = () => {
      const willShow = !showAdvancedFilter.value;
      showAdvancedFilter.value = willShow;
    };
    const handleSearch = () => {
      const filters = handleSearchData(filterValues.value, filterFields.value);
      const filterData = {
        ...currentTab.value,
        dynamicFilter: searchInputValue.value,
        ...filters
      };
      console.log("🚀 ~ 开始执行查询", filterData);
      emit("search", {
        filters: JSON.stringify(filterData)
      });
    };
    const currentTab = ref({});
    watch(
      activeTab,
      (newVal, oldVal) => {
        console.log("🚀 ~ Tab切换:", tabConfigs.value, "->", newVal);
        const tab = tabConfigs.value.find((item) => item.id == newVal);
        if (tab) {
          currentTab.value[tab.fieldName] = tab.fixedValue;
          handleSearch();
        }
      },
      {
        immediate: true
      }
    );
    const onSearchInputKeyup = (event) => {
      if (event.key === "Enter") {
        console.log("🚀 ~ 搜索输入框回车");
        handleSearch();
      }
    };
    const debounce = (fn, delay = 500) => {
      let timer = null;
      return (...args) => {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
          fn(...args);
        }, delay);
      };
    };
    const debouncedSearch = debounce(handleSearch, 500);
    watch(
      filterValues,
      (newVal) => {
        console.log("🚀 ~ 筛选值变化:", newVal);
        debouncedSearch();
      },
      { deep: true }
    );
    const getFilterComponent = (fieldType) => {
      const componentMap = {
        text: Text,
        select: Select,
        date: Date,
        number: Number,
        multipleSelection: MultipleSelection,
        switch: Select
      };
      return componentMap[fieldType] || Text;
    };
    const getComponentConfig = (field) => {
      return { ...field };
    };
    const getPlaceholder = (field, type = "default") => {
      const placeholderMap = {
        text: "请输入",
        select: "请选择",
        date: type === "start" ? "开始日期" : type === "end" ? "结束日期" : "请选择日期",
        number: "请输入",
        number_min: "最小值",
        number_max: "最大值",
        radio: "请选择",
        checkbox: "请选择",
        switch: "请选择"
      };
      if (field.fieldType === "date") {
        return placeholderMap.date;
      }
      if (field.fieldType === "number") {
        return type === "min" ? placeholderMap.number_min : type === "max" ? placeholderMap.number_max : placeholderMap.number;
      }
      return `${placeholderMap[field.fieldType] || "请输入"}${field.label || ""}`;
    };
    const dynamicPlaceholder = computed(() => {
      const searchFields = dynamicConfig.value.searchFields || [];
      if (searchFields.length == 0) {
        return "请输入筛选条件";
      }
      const labelArr = searchFields.map((item) => item.label);
      return `搜索${labelArr.join("/")}`;
    });
    return (_ctx, _cache) => {
      const _component_el_icon = ElIcon;
      const _component_el_tab_pane = ElTabPane;
      const _component_el_tabs = ElTabs;
      const _component_el_button = ElButton;
      const _component_el_input = ElInput;
      const _component_el_checkbox_button = ElCheckboxButton;
      const _component_el_checkbox_group = ElCheckboxGroup;
      const _component_el_date_picker = ElDatePicker;
      const _component_el_input_number = ElInputNumber;
      const _component_el_form_item = ElFormItem;
      const _component_el_form = ElForm;
      const _component_el_collapse_transition = ElCollapseTransition;
      const _directive_fec_auth = resolveDirective("fec-auth");
      return openBlock(), createElementBlock("div", _hoisted_1, [
        createElementVNode("div", _hoisted_2, [
          __props.localConfig.showReturn ? (openBlock(), createElementBlock("div", _hoisted_3, [
            createVNode(_component_el_icon, null, {
              default: withCtx(() => [
                createVNode(unref(arrow_left_bold_default))
              ]),
              _: 1
            })
          ])) : createCommentVNode("", true),
          __props.localConfig.showTitle ? (openBlock(), createElementBlock("div", _hoisted_4, [
            _cache[2] || (_cache[2] = createElementVNode("div", { class: "template-name-line" }, null, -1)),
            createTextVNode(" " + toDisplayString(__props.localConfig.templateName), 1)
          ])) : createCommentVNode("", true),
          queryConfig.value.enabled && tabConfigs.value.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_5, [
            createVNode(_component_el_tabs, {
              modelValue: activeTab.value,
              "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => activeTab.value = $event),
              class: "dynamic-tabs"
            }, {
              default: withCtx(() => [
                (openBlock(true), createElementBlock(Fragment, null, renderList(tabConfigs.value, (tab) => {
                  return openBlock(), createBlock(_component_el_tab_pane, {
                    key: tab.id,
                    label: tab.label,
                    name: tab.id
                  }, null, 8, ["label", "name"]);
                }), 128))
              ]),
              _: 1
            }, 8, ["modelValue"])
          ])) : createCommentVNode("", true),
          createElementVNode("div", _hoisted_6, [
            queryConfig.value.enabled ? (openBlock(), createElementBlock("div", _hoisted_7, [
              createVNode(_component_el_input, {
                modelValue: searchInputValue.value,
                "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => searchInputValue.value = $event),
                placeholder: dynamicPlaceholder.value,
                title: dynamicPlaceholder.value,
                class: "search-input",
                clearable: "",
                size: "default",
                onKeyup: onSearchInputKeyup
              }, createSlots({
                suffix: withCtx(() => [
                  createVNode(_component_el_icon, {
                    class: "el-input__icon search",
                    onClick: handleSearch
                  }, {
                    default: withCtx(() => [
                      createVNode(unref(search_default))
                    ]),
                    _: 1
                  })
                ]),
                _: 2
              }, [
                dynamicConfig.value.advancedSearch ? {
                  name: "append",
                  fn: withCtx(() => [
                    createVNode(_component_el_button, {
                      type: "primary",
                      onClick: toggleAdvancedFilter
                    }, {
                      default: withCtx(() => [
                        createTextVNode(toDisplayString(showAdvancedFilter.value ? "隐藏高级搜索" : "高级搜索"), 1)
                      ]),
                      _: 1
                    })
                  ]),
                  key: "0"
                } : void 0
              ]), 1032, ["modelValue", "placeholder", "title"])
            ])) : createCommentVNode("", true),
            !__props.readOnly && !__props.isSubTable && rightButtons.value.length > 0 ? (openBlock(), createBlock(unref(VxeToolbar), {
              key: 1,
              ref: "toolbarRef"
            }, {
              tools: withCtx(() => [
                !__props.isSubTable && rightButtons.value.length ? (openBlock(true), createElementBlock(Fragment, { key: 0 }, renderList(rightButtons.value, (btn) => {
                  return withDirectives((openBlock(), createBlock(_component_el_button, {
                    key: btn.id,
                    type: getBtnType(btn),
                    icon: getBtnIcon(btn.btnType),
                    onClick: ($event) => handleClick(btn, $event)
                  }, {
                    default: withCtx(() => [
                      createTextVNode(toDisplayString(btn.label), 1)
                    ]),
                    _: 2
                  }, 1032, ["type", "icon", "onClick"])), [
                    [_directive_fec_auth, btn.permission]
                  ]);
                }), 128)) : createCommentVNode("", true)
              ]),
              _: 1
            }, 512)) : createCommentVNode("", true)
          ])
        ]),
        createVNode(_component_el_collapse_transition, null, {
          default: withCtx(() => [
            withDirectives(createElementVNode("div", _hoisted_8, [
              createElementVNode("div", _hoisted_9, [
                createVNode(_component_el_form, {
                  ref: "formRef",
                  model: filterValues.value,
                  class: "filter-form",
                  "label-width": "100px",
                  inline: "",
                  size: "default"
                }, {
                  default: withCtx(() => [
                    createElementVNode("div", _hoisted_10, [
                      (openBlock(true), createElementBlock(Fragment, null, renderList(filterFields.value, (field) => {
                        return openBlock(), createElementBlock("div", {
                          key: field.id,
                          style: normalizeStyle(field.isExclusiveRow ? "width:100%" : "")
                        }, [
                          createVNode(_component_el_form_item, {
                            label: field.label
                          }, {
                            default: withCtx(() => [
                              field.isButtonStyle ? (openBlock(), createBlock(_component_el_checkbox_group, {
                                key: 0,
                                modelValue: filterValues.value[field.fieldId],
                                "onUpdate:modelValue": ($event) => filterValues.value[field.fieldId] = $event
                              }, {
                                default: withCtx(() => [
                                  (openBlock(true), createElementBlock(Fragment, null, renderList(field.optionConfig.options, (option) => {
                                    return openBlock(), createBlock(_component_el_checkbox_button, {
                                      key: option.value,
                                      value: option.value
                                    }, {
                                      default: withCtx(() => [
                                        createTextVNode(toDisplayString(option.label), 1)
                                      ]),
                                      _: 2
                                    }, 1032, ["value"]);
                                  }), 128))
                                ]),
                                _: 2
                              }, 1032, ["modelValue", "onUpdate:modelValue"])) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
                                field.fieldType == "date" ? (openBlock(), createBlock(_component_el_date_picker, {
                                  key: 0,
                                  modelValue: filterValues.value[field.fieldId],
                                  "onUpdate:modelValue": ($event) => filterValues.value[field.fieldId] = $event,
                                  type: "daterange",
                                  "start-placeholder": getPlaceholder(field, "start"),
                                  "end-placeholder": getPlaceholder(field, "end"),
                                  format: "YYYY-MM-DD",
                                  "value-format": "YYYYMMDD",
                                  clearable: "",
                                  style: { "width": "100%" }
                                }, null, 8, ["modelValue", "onUpdate:modelValue", "start-placeholder", "end-placeholder"])) : field.fieldType == "number" ? (openBlock(), createElementBlock("div", _hoisted_11, [
                                  createVNode(_component_el_input_number, {
                                    modelValue: filterValues.value[field.fieldId],
                                    "onUpdate:modelValue": ($event) => filterValues.value[field.fieldId] = $event,
                                    placeholder: getPlaceholder(field, "min"),
                                    controls: false,
                                    "controls-position": "right",
                                    style: { "flex": "1" },
                                    clearable: ""
                                  }, null, 8, ["modelValue", "onUpdate:modelValue", "placeholder"]),
                                  _cache[3] || (_cache[3] = createElementVNode("span", null, "-", -1)),
                                  createVNode(_component_el_input_number, {
                                    modelValue: filterValues.value[`${field.fieldId}_max`],
                                    "onUpdate:modelValue": ($event) => filterValues.value[`${field.fieldId}_max`] = $event,
                                    placeholder: getPlaceholder(field, "max"),
                                    controls: false,
                                    "controls-position": "right",
                                    style: { "flex": "1" },
                                    clearable: ""
                                  }, null, 8, ["modelValue", "onUpdate:modelValue", "placeholder"])
                                ])) : (openBlock(), createBlock(resolveDynamicComponent(getFilterComponent(field.fieldType)), mergeProps({
                                  key: 2,
                                  modelValue: filterValues.value[field.fieldId],
                                  "onUpdate:modelValue": ($event) => filterValues.value[field.fieldId] = $event,
                                  config: { ...field, eventHandlers: {} },
                                  ref_for: true
                                }, getComponentConfig(field), {
                                  placeholder: getPlaceholder(field)
                                }), null, 16, ["modelValue", "onUpdate:modelValue", "config", "placeholder"]))
                              ], 64))
                            ]),
                            _: 2
                          }, 1032, ["label"])
                        ], 4);
                      }), 128))
                    ])
                  ]),
                  _: 1
                }, 8, ["model"])
              ])
            ], 512), [
              [
                vShow,
                showAdvancedFilter.value && dynamicConfig.value.advancedSearch && filterFields.value.length > 0
              ]
            ])
          ]),
          _: 1
        })
      ]);
    };
  }
};
const DynamicQuery = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-84665bac"]]);
export {
  DynamicQuery as default
};
