import { defineComponent, useSlots, computed, reactive, ref, onMounted, watch, resolveComponent, openBlock, createBlock, mergeProps, withModifiers, unref, withCtx, createElementBlock, Fragment, renderList, createSlots, renderSlot, createCommentVNode, resolveDynamicComponent, toHandlers, createTextVNode, toDisplayString, createVNode, normalizeClass, isRef } from 'vue';
import './renderComp.vue.mjs';
import './moreChoose.vue.mjs';
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue';
import { useComputed } from './useComputed.mjs';
import '../../../hooks/index.mjs';
import { useLocale } from '../../../hooks/useLocale.mjs';
import _sfc_main$1 from './renderComp.vue2.mjs';
import _sfc_main$2 from './moreChoose.vue2.mjs';

var _sfc_main = /* @__PURE__ */ defineComponent({
  ...{
    name: "FQueryCondition"
  },
  __name: "index",
  props: {
    opts: { default: () => ({}) },
    labelWidth: { default: "120px" },
    btnCheckBind: { default: () => ({}) },
    btnResetBind: { default: () => ({}) },
    loading: { type: Boolean, default: false },
    reset: { type: Boolean, default: true },
    boolEnter: { type: Boolean, default: true },
    isShowOpen: { type: Boolean, default: true },
    isExpansion: { type: Boolean, default: false },
    maxVisibleRows: { default: 1 },
    packUpTxt: { default: "" },
    unfoldTxt: { default: "" },
    isFooter: { type: Boolean, default: true },
    configChangedReset: { type: Boolean, default: false },
    isShowWidthSize: { type: Boolean, default: false },
    widthSize: { default: 4 },
    isDropDownSelectMore: { type: Boolean, default: false },
    moreCheckList: { default: () => [] },
    popoverAttrs: { default: () => ({}) },
    labelPosition: { default: "right" }
  },
  emits: ["handleEvent", "submit", "reset", "getCheckList", "getRefs"],
  setup(__props, { expose: __expose, emit: __emit }) {
    const {
      compChildName,
      selectListType,
      compChildLabel,
      compChildValue,
      compChildShowLabel,
      getColLength
    } = useComputed();
    const { t } = useLocale();
    const props = __props;
    const slots = useSlots();
    const isShow = (name) => {
      return Object.keys(slots).includes(name);
    };
    const popoverAttrsBind = computed(() => {
      return {
        showTxt: t("plus.search.popoverAttrs.showTxt"),
        title: t("plus.search.popoverAttrs.title"),
        allTxt: t("plus.search.popoverAttrs.allTxt"),
        reverseTxt: t("plus.search.popoverAttrs.reverseTxt"),
        clearTxt: t("plus.search.popoverAttrs.clearTxt"),
        ...props.popoverAttrs
      };
    });
    let queryState = reactive({
      form: Object.keys(props.opts).reduce((acc, field) => {
        var _a;
        acc[field] = (_a = props.opts[field].defaultVal) != null ? _a : null;
        return acc;
      }, {})
    });
    let colLength = ref(4);
    let showOpen = ref(false);
    let open = ref(false);
    const getPlaceholder = (row) => {
      let placeholder;
      if (row.comp && typeof row.comp == "string") {
        if (row.comp.includes("input")) {
          placeholder = t("plus.search.pleaseEnter") + row.label;
        } else if (row.comp.includes("select") || row.comp.includes("date")) {
          placeholder = t("plus.search.pleaseSelect") + row.label;
        } else {
          placeholder = row.label;
        }
      }
      return placeholder;
    };
    const queryAttrs = computed(() => {
      return {
        btnTxt: t("plus.search.searchText"),
        ...props.btnCheckBind
      };
    });
    const resetAttrs = computed(() => {
      return { btnTxt: t("plus.search.resetText"), ...props.btnResetBind };
    });
    const originCellLength = computed(() => {
      let length = 0;
      Object.keys(props.opts).forEach((key) => {
        let span = props.opts[key].span || 1;
        if (length % colLength.value + span > colLength.value) {
          length += colLength.value - length % colLength.value;
        }
        length += span;
      });
      return length;
    });
    const cOpts = computed(() => {
      let renderSpan = 0;
      return Object.keys(props.opts).reduce((acc, field) => {
        var _a;
        let opt = {
          ...props.opts[field]
        };
        if (showOpen.value) {
          renderSpan += (_a = opt.span) != null ? _a : 1;
          if (!open.value && renderSpan - 1 >= props.maxVisibleRows * colLength.value) {
            return acc;
          }
        }
        opt.dataIndex = field;
        acc[field] = opt;
        return acc;
      }, {});
    });
    const cellLength = computed(() => {
      let length = 0;
      Object.keys(props.opts).forEach((key) => {
        let span = props.opts[key].span > 4 ? 4 : props.opts[key].span || 1;
        length += span;
      });
      return length;
    });
    const gridAreas = computed(() => {
      var _a;
      const fields = Object.keys(cOpts.value);
      let rowIndex = 0;
      let rowSpan = 0;
      const areas = [[]];
      for (let fieldIndex = 0; fieldIndex < fields.length; fieldIndex++) {
        const field = fields[fieldIndex];
        const opt = cOpts.value[field];
        const span = Math.min((_a = opt.span) != null ? _a : 1, Math.min(colLength.value, 4));
        if (rowSpan + span > colLength.value) {
          while (rowSpan < colLength.value) {
            areas[rowIndex].push(".");
            rowSpan += 1;
          }
          rowSpan = 0;
          areas[++rowIndex] = [];
        }
        rowSpan += span;
        for (let index = 0; index < span; index++) {
          areas[rowIndex].push(field);
        }
      }
      if (areas[rowIndex].length === colLength.value) {
        areas.push(Array(colLength.value).fill("submit_btn"));
      } else {
        while (areas[rowIndex].length < colLength.value) {
          areas[rowIndex].push("submit_btn");
        }
      }
      return areas.reduce((acc, cur) => {
        acc += `'${cur.join(" ")}'
`;
        return acc;
      }, "");
    });
    const packUpTxtText = computed(() => props.packUpTxt || t("plus.search.retract"));
    const unfoldTxtText = computed(() => props.unfoldTxt || t("plus.search.expand"));
    const cEvent = computed(() => {
      return (opt) => {
        let event = { ...opt.eventHandle };
        let changeEvent = {};
        Object.keys(event).forEach((v) => {
          changeEvent[v] = (e) => {
            if (opt.comp.includes("select") || opt.comp.includes("picker") || opt.comp.includes("date")) {
              event[v] && event[v](e, queryState.form);
            } else {
              if (e) {
                event[v] && event[v](e, queryState.form);
              } else {
                event[v] && event[v](queryState.form);
              }
            }
          };
        });
        return { ...changeEvent };
      };
    });
    const initForm = (opts, keepVal = false) => {
      return Object.keys(opts).reduce((acc, field) => {
        var _a, _b, _c;
        if (keepVal && queryState.form) {
          acc[field] = (_b = (_a = queryState.form[field]) != null ? _a : opts[field].defaultVal) != null ? _b : null;
        } else {
          acc[field] = (_c = opts[field].defaultVal) != null ? _c : null;
        }
        return acc;
      }, {});
    };
    const emits = __emit;
    const tselecttableref = ref({});
    const handleRef = (el, opt, key) => {
      emits("getRefs", el, opt, key);
      if (el) {
        tselecttableref.value[`tselecttableref-${key}`] = el;
      }
    };
    const getRefs = (el, opt, index) => {
      emits("getRefs", el, opt, index);
    };
    const resetHandle = () => {
      queryState.form = initForm(props.opts);
      const refList = Object.keys(tselecttableref.value).filter(
        (item) => item.includes("tselecttableref")
      );
      if (refList.length > 0 && tselecttableref.value) {
        refList.map((val) => {
          tselecttableref.value[val].clear();
        });
      }
      emits("reset", queryState.form);
      checkHandle("reset");
    };
    const resetData = () => {
      queryState.form = initForm(props.opts);
      const refList = Object.keys(tselecttableref.value).filter(
        (item) => item.includes("tselecttableref")
      );
      if (refList.length > 0 && tselecttableref.value) {
        refList.map((val) => {
          tselecttableref.value[val].clear();
        });
      }
    };
    const handleEvent = ({ isChange = false, type, val }, dataIndex) => {
      if (!isChange) {
        emits("handleEvent", type, val, queryState.form);
      } else if (dataIndex) {
        queryState.form[dataIndex] = val;
      }
    };
    const checkHandle = (flagText = false) => {
      emits("submit", queryState.form, flagText);
    };
    onMounted(() => {
      if (props.isShowOpen) {
        showOpen.value = true;
      } else {
        showOpen.value = false;
      }
      if (props.isExpansion) {
        open.value = true;
      } else {
        open.value = false;
      }
      if (props.isShowWidthSize) {
        colLength.value = props.widthSize;
      } else {
        colLength.value = getColLength();
      }
      if (props.boolEnter) {
        document.onkeyup = (e) => {
          let key = e.keyCode;
          let pagination = document.querySelectorAll(".el-pagination");
          let isPaginationInputFocus = false;
          if (pagination) {
            pagination.forEach((ele) => {
              let paginationInputList = ele.getElementsByTagName("input");
              let paginationInput = paginationInputList[paginationInputList.length - 1];
              if (paginationInput === document.activeElement) {
                isPaginationInputFocus = true;
              }
            });
          }
          if (isPaginationInputFocus) {
            return;
          }
          if (key === 13) {
            checkHandle();
          }
        };
      }
      if (isShow("footerBtn") || !props.isFooter) {
        open.value = true;
      }
      if (props.isDropDownSelectMore) {
        open.value = true;
        showOpen.value = false;
      }
    });
    watch(
      () => props.widthSize,
      (val) => {
        colLength.value = val;
      }
    );
    watch(
      () => props.opts,
      (opts) => {
        queryState.form = initForm(opts, !props.configChangedReset);
      },
      { deep: true }
    );
    __expose({
      queryState,
      props,
      colLength,
      resetData,
      resetHandle,
      checkHandle,
      handleEvent
    });
    return (_ctx, _cache) => {
      const _component_el_form_item = resolveComponent("el-form-item");
      const _component_el_button = resolveComponent("el-button");
      const _component_el_icon = resolveComponent("el-icon");
      const _component_el_form = resolveComponent("el-form");
      return openBlock(), createBlock(_component_el_form, mergeProps({ id: "f_query_condition" }, _ctx.$attrs, {
        "label-width": __props.labelWidth,
        form: unref(queryState).form,
        labelPosition: __props.labelPosition,
        size: "default",
        class: "f-query-condition",
        style: {
          "grid-template-areas": gridAreas.value,
          "grid-template-columns": `repeat(${unref(colLength)}, minmax(0px, ${100 / unref(colLength)}%))`
        },
        onSubmit: _cache[2] || (_cache[2] = withModifiers(() => {
        }, ["prevent"]))
      }), {
        default: withCtx(() => [
          (openBlock(true), createElementBlock(
            Fragment,
            null,
            renderList(cOpts.value, (opt, i) => {
              return openBlock(), createBlock(_component_el_form_item, mergeProps({
                key: i,
                label: opt.label,
                "label-width": opt.labelWidth
              }, { ref_for: true }, _ctx.$attrs, {
                style: { gridArea: i },
                class: [
                  opt.className,
                  {
                    render_label: opt.labelRender,
                    render_label_position_top: __props.labelPosition == "top" && opt.labelRender,
                    render_label_position_left: __props.labelPosition == "left" && opt.labelRender
                  }
                ]
              }), createSlots({
                default: withCtx(() => [
                  opt.slotName ? renderSlot(_ctx.$slots, opt.slotName, {
                    key: 0,
                    param: unref(queryState).form,
                    scope: unref(queryState).form
                  }) : createCommentVNode("v-if", true),
                  opt.isSelfCom ? (openBlock(), createBlock(resolveDynamicComponent(opt.comp), mergeProps(
                    {
                      key: 1,
                      ref_for: true,
                      ref: opt.comp === "t-select-table" ? (el) => handleRef(el, opt, i) : (el) => getRefs(el, opt, i),
                      modelValue: unref(queryState).form[opt.dataIndex],
                      "onUpdate:modelValue": ($event) => unref(queryState).form[opt.dataIndex] = $event,
                      placeholder: opt.placeholder || getPlaceholder(opt)
                    },
                    { ref_for: true },
                    typeof opt.bind == "function" ? opt.bind(unref(queryState).form) : { clearable: true, filterable: true, ..._ctx.$attrs, ...opt.bind },
                    {
                      style: { width: opt.width || "100%" },
                      onChange: ($event) => handleEvent({ type: opt.event, val: unref(queryState).form[opt.dataIndex] })
                    },
                    toHandlers(cEvent.value(opt))
                  ), null, 16, ["modelValue", "onUpdate:modelValue", "placeholder", "style", "onChange"])) : createCommentVNode("v-if", true),
                  !opt.isSelfCom && !opt.slotName ? (openBlock(), createBlock(resolveDynamicComponent(opt.comp), mergeProps(
                    {
                      key: 2,
                      ref_for: true
                    },
                    typeof opt.bind == "function" ? opt.bind(unref(queryState).form) : { clearable: true, filterable: true, ..._ctx.$attrs, ...opt.bind },
                    {
                      placeholder: opt.placeholder || getPlaceholder(opt),
                      onChange: ($event) => handleEvent({ type: opt.event, val: unref(queryState).form[opt.dataIndex] }),
                      ref_for: true,
                      ref: (el) => getRefs(el, opt, i)
                    },
                    toHandlers(cEvent.value(opt)),
                    {
                      modelValue: unref(queryState).form[opt.dataIndex],
                      "onUpdate:modelValue": ($event) => unref(queryState).form[opt.dataIndex] = $event
                    }
                  ), {
                    default: withCtx(() => [
                      (openBlock(true), createElementBlock(
                        Fragment,
                        null,
                        renderList(unref(selectListType)(opt), (value, key) => {
                          return openBlock(), createBlock(resolveDynamicComponent(unref(compChildName)(opt)), {
                            key,
                            disabled: value.disabled,
                            label: unref(compChildLabel)(opt, value),
                            value: unref(compChildValue)(opt, value, key)
                          }, {
                            default: withCtx(() => [
                              createTextVNode(
                                toDisplayString(unref(compChildShowLabel)(opt, value)),
                                1
                                /* TEXT */
                              )
                            ]),
                            _: 2
                            /* DYNAMIC */
                          }, 1032, ["disabled", "label", "value"]);
                        }),
                        128
                        /* KEYED_FRAGMENT */
                      ))
                    ]),
                    _: 2
                    /* DYNAMIC */
                  }, 1040, ["placeholder", "onChange", "modelValue", "onUpdate:modelValue"])) : createCommentVNode("v-if", true)
                ]),
                _: 2
                /* DYNAMIC */
              }, [
                opt.labelRender ? {
                  name: "label",
                  fn: withCtx(() => [
                    createVNode(_sfc_main$1, {
                      form: unref(queryState).form,
                      render: opt.labelRender
                    }, null, 8, ["form", "render"])
                  ]),
                  key: "0"
                } : void 0
              ]), 1040, ["label", "label-width", "style", "class"]);
            }),
            128
            /* KEYED_FRAGMENT */
          )),
          Object.keys(cOpts.value).length > 0 ? (openBlock(), createBlock(_component_el_form_item, {
            key: 0,
            "label-width": "0",
            style: { "grid-area": "submit_btn" },
            class: normalizeClass([
              "btn",
              { flex_end: cellLength.value % unref(colLength) === 0 },
              { btn_flex_end: Object.keys(cOpts.value).length === 4 || cellLength.value > 3 },
              { btn_label_position_top: __props.labelPosition == "top" }
            ])
          }, {
            default: withCtx(() => [
              __props.isFooter ? (openBlock(), createElementBlock(
                Fragment,
                { key: 0 },
                [
                  renderSlot(_ctx.$slots, "footerBtn"),
                  !unref(slots).footerBtn ? (openBlock(), createElementBlock(
                    Fragment,
                    { key: 0 },
                    [
                      createVNode(_component_el_button, mergeProps({
                        class: "btn_check",
                        onClick: checkHandle
                      }, { type: "primary", ...queryAttrs.value }, { loading: __props.loading }), {
                        default: withCtx(() => [
                          createTextVNode(
                            toDisplayString(queryAttrs.value.btnTxt),
                            1
                            /* TEXT */
                          )
                        ]),
                        _: 1
                        /* STABLE */
                      }, 16, ["loading"]),
                      __props.reset ? (openBlock(), createBlock(
                        _component_el_button,
                        mergeProps({
                          key: 0,
                          class: "btn_reset"
                        }, resetAttrs.value, { onClick: resetHandle }),
                        {
                          default: withCtx(() => [
                            createTextVNode(
                              toDisplayString(resetAttrs.value.btnTxt),
                              1
                              /* TEXT */
                            )
                          ]),
                          _: 1
                          /* STABLE */
                        },
                        16
                        /* FULL_PROPS */
                      )) : createCommentVNode("v-if", true),
                      renderSlot(_ctx.$slots, "querybar"),
                      originCellLength.value > __props.maxVisibleRows * unref(colLength) && unref(showOpen) ? (openBlock(), createBlock(_component_el_button, {
                        key: 1,
                        onClick: _cache[0] || (_cache[0] = ($event) => isRef(open) ? open.value = !unref(open) : open = !unref(open)),
                        link: ""
                      }, {
                        default: withCtx(() => [
                          createTextVNode(
                            toDisplayString(unref(open) ? packUpTxtText.value : unfoldTxtText.value) + " ",
                            1
                            /* TEXT */
                          ),
                          unref(open) ? (openBlock(), createBlock(_component_el_icon, { key: 0 }, {
                            default: withCtx(() => [
                              createVNode(unref(ArrowUp))
                            ]),
                            _: 1
                            /* STABLE */
                          })) : (openBlock(), createBlock(_component_el_icon, { key: 1 }, {
                            default: withCtx(() => [
                              createVNode(unref(ArrowDown))
                            ]),
                            _: 1
                            /* STABLE */
                          }))
                        ]),
                        _: 1
                        /* STABLE */
                      })) : createCommentVNode("v-if", true),
                      createVNode(_sfc_main$2, {
                        isDropDownSelectMore: __props.isDropDownSelectMore,
                        moreCheckList: __props.moreCheckList,
                        popoverAttrsBind: popoverAttrsBind.value,
                        onGetCheckList: _cache[1] || (_cache[1] = (event) => emits("getCheckList", event))
                      }, null, 8, ["isDropDownSelectMore", "moreCheckList", "popoverAttrsBind"])
                    ],
                    64
                    /* STABLE_FRAGMENT */
                  )) : createCommentVNode("v-if", true)
                ],
                64
                /* STABLE_FRAGMENT */
              )) : createCommentVNode("v-if", true)
            ]),
            _: 3
            /* FORWARDED */
          }, 8, ["class"])) : createCommentVNode("v-if", true)
        ]),
        _: 3
        /* FORWARDED */
      }, 16, ["label-width", "form", "labelPosition", "style"]);
    };
  }
});

export { _sfc_main as default };
