import "../../../../node_modules/element-plus/es/index.mjs";
/* empty css                                                          */
/* empty css                                                                  */
/* empty css                                                             */
/* empty css                                                                */
import { ref, watch, computed, resolveComponent, createElementBlock, openBlock, createVNode, createElementVNode, withCtx, unref, normalizeStyle, createCommentVNode, withModifiers, normalizeClass, createBlock, toDisplayString, createTextVNode, nextTick } from "vue";
import emitter from "../utils/eventBus.mjs";
import "../../../../node_modules/grid-layout-plus/es/index.mjs";
import { VueDraggable as lo } from "../../../../node_modules/vue-draggable-plus/dist/vue-draggable-plus.mjs";
import FormSetting from "./formSetting.vue.mjs";
import PageHeaderSetting from "./PageHeaderSetting.vue.mjs";
import PageFooterSetting from "./PageFooterSetting.vue.mjs";
import ComponentPreviewWrapper from "./components/ComponentPreviewWrapper.vue.mjs";
import SubTitle from "./components/SubTitle.vue.mjs";
import H2Wrapper from "./components/H2Wrapper.vue.mjs";
import SubForm from "./components/SubForm.vue.mjs";
import ApprovalHistory from "./components/approvalHistory.vue.mjs";
import SubTable from "./components/SubTable.vue.mjs";
import Document from "./components/Document.vue.mjs";
import Contract from "./components/Contract.vue.mjs";
import { StarFilled as star_filled_default, Star as star_default, Lock as lock_default, Unlock as unlock_default, Delete as delete_default } from "../../../../node_modules/@element-plus/icons-vue/dist/index.mjs";
import { getEditConfigData, setEditConfigData, setSelectedItem, setHoverItem, getCurrentClass, isSelectedItem } from "../utils/common.mjs";
import { throttle as eo } from "../../../../node_modules/@vexip-ui/utils/dist/index.mjs";
import { defaultProperty } from "./aside/index.mjs";
/* empty css                                                              */
/* empty css                                                                */
/* empty css            */
import _export_sfc from "../../../../_virtual/_plugin-vue_export-helper.mjs";
import { ElScrollbar } from "../../../../node_modules/element-plus/es/components/scrollbar/index.mjs";
import { ElForm } from "../../../../node_modules/element-plus/es/components/form/index.mjs";
import De from "../../../../node_modules/grid-layout-plus/es/components/grid-layout.vue.mjs";
import { ElIcon } from "../../../../node_modules/element-plus/es/components/icon/index.mjs";
import { ElDivider } from "../../../../node_modules/element-plus/es/components/divider/index.mjs";
import { ElMessage } from "../../../../node_modules/element-plus/es/components/message/index.mjs";
const _hoisted_1 = { class: "form-work-area" };
const _hoisted_2 = { class: "form-grid-container" };
const _hoisted_3 = ["onMouseenter", "onClick"];
const _hoisted_4 = {
  key: 0,
  class: "component-toolbar"
};
const _hoisted_5 = ["onClick"];
const _hoisted_6 = ["onClick"];
const _hoisted_7 = ["onClick"];
const _hoisted_8 = ["onClick"];
const _hoisted_9 = { class: "status-tags" };
const _hoisted_10 = {
  key: 0,
  class: "field-name-tag"
};
const _hoisted_11 = {
  key: 1,
  class: "status-tag disabled-tag"
};
const dropId = "drop";
const _sfc_main = {
  __name: "index",
  setup(__props, { expose: __expose }) {
    const editConfigData = ref(getEditConfigData());
    editConfigData.value.fieldsData.forEach((item) => {
      item.component = { ...defaultProperty, ...item.component };
    });
    watch(
      editConfigData,
      (val) => {
        console.log("🚀 ~ val:", val);
        setEditConfigData(val);
      },
      { deep: true }
    );
    const layoutDragData = ref([]);
    const layoutData = ref(editConfigData.value.fieldsData || []);
    const gridLayout = ref(null);
    const dragItem = { x: 0, y: 0, w: 1, h: 1 };
    const gridWrapperHeight = ref(null);
    watch(
      () => layoutData,
      (val) => {
        const maxY = val.value.reduce(
          (max, item) => Math.max(max, item.y + item.h),
          0
        );
        const colHeight = editConfigData.value.labelPosition == "top" ? 90 : 60;
        gridWrapperHeight.value = maxY * colHeight + 100;
      },
      { immediate: true, deep: true }
    );
    watch(
      () => editConfigData.value.columns,
      (newColumns, oldColumns) => {
        if (!layoutData.value || newColumns === oldColumns || newColumns > oldColumns)
          return;
        const itemsToRelayout = [];
        const validItems = [];
        layoutData.value.forEach((item) => {
          if (item.i === dropId) {
            validItems.push(item);
          } else if (item.x + item.w > newColumns) {
            itemsToRelayout.push({ ...item });
          } else {
            validItems.push(item);
          }
        });
        if (itemsToRelayout.length > 0) {
          itemsToRelayout.sort((a, b) => a.y - b.y || a.x - b.x);
          const maxY = Math.max(...validItems.map((item) => item.y), -1);
          itemsToRelayout.forEach((item, index) => {
            item.y = maxY + 1 + Math.floor(index / newColumns);
            item.x = 0;
          });
          layoutData.value = [...validItems, ...itemsToRelayout];
          editConfigData.value.fieldsData = layoutData.value;
        }
      }
    );
    watch(
      () => editConfigData.value.labelPosition,
      (labelPosition) => {
        const targetHeight = labelPosition === "top" ? 0.75 : 1;
        layoutData.value.forEach((item) => {
          var _a, _b, _c;
          if (["subTitle", "h2", "divider"].includes((_a = item.component) == null ? void 0 : _a.fieldType)) {
            item.h = 1 * targetHeight;
          } else if ([
            "subForm",
            "subTable",
            "approvalHistory",
            "document",
            "contract"
          ].includes((_b = item.component) == null ? void 0 : _b.fieldType)) {
            if (((_c = item.component) == null ? void 0 : _c.titleMode) == "none") {
              item.h = 2 * targetHeight;
            } else {
              item.h = 3 * targetHeight;
            }
          }
        });
        gridLayout.value.resizeEvent();
      }
    );
    const addToGrid = ref(false);
    function handleAddToGrid(event) {
      console.log("🚀 ~ handleAddToGrid ~ event:", event);
      const dropItemIndex = layoutData.value.findIndex((item2) => item2.i === dropId);
      if (dropItemIndex !== -1) {
        const component = layoutData.value[dropItemIndex].component;
        layoutData.value[dropItemIndex].i = component.id;
        layoutData.value[dropItemIndex].id = component.id;
        gridLayout.value.dragEvent(
          "dragend",
          component.id,
          dragItem.x,
          dragItem.y,
          dragItem.w,
          dragItem.h
        );
      }
      const item = gridLayout.value.getItem(dropId);
      if (!item) return;
      try {
        item.wrapper.style.display = "";
      } catch (e) {
      }
      layoutDragData.value = [];
      addToGrid.value = true;
    }
    function handleDelete(item) {
      var _a, _b, _c;
      const index = layoutData.value.findIndex((cell) => cell.i == item.i);
      if (index !== -1) {
        const deletedItem = layoutData.value[index];
        if (!editConfigData.value.deletedFields) {
          editConfigData.value.deletedFields = [];
        }
        const deletedField = {
          label: ((_a = deletedItem.component) == null ? void 0 : _a.label) || "",
          fieldName: ((_b = deletedItem.component) == null ? void 0 : _b.fieldName) || "",
          fieldType: ((_c = deletedItem.component) == null ? void 0 : _c.fieldType) || "",
          deleteTime: (/* @__PURE__ */ new Date()).toLocaleString("zh-CN"),
          data: deletedItem
        };
        editConfigData.value.deletedFields.push(deletedField);
        layoutData.value.splice(index, 1);
        ElMessage.success("字段已移至回收站");
      }
    }
    function handleHide(item) {
      const index = layoutData.value.findIndex((cell) => cell.i === item.i);
      if (index !== -1) {
        if (!editConfigData.value.hiddenFields) {
          editConfigData.value.hiddenFields = [];
        }
        editConfigData.value.hiddenFields.push(item.component);
        layoutData.value.splice(index, 1);
      }
    }
    let lastPosition = { x: null, y: null };
    let cachedRect = null;
    const onFormDragMove = eo((event) => {
      if (addToGrid.value) {
        return;
      }
      const component = event.clonedData;
      if (!component) return;
      if (!cachedRect || cachedRect.element !== event.to) {
        cachedRect = {
          element: event.to,
          rect: event.to.getBoundingClientRect()
        };
      }
      const rect = cachedRect.rect;
      const mouseX = event.originalEvent.clientX;
      const mouseY = event.originalEvent.clientY;
      const x = mouseX - rect.left;
      const y = mouseY - rect.top;
      const positionChanged = lastPosition.x === null || lastPosition.y === null || Math.abs(x - lastPosition.x) > 5 || // 5px 的容差
      Math.abs(y - lastPosition.y) > 5;
      if (!positionChanged) {
        return;
      }
      lastPosition = { x, y };
      let finalWH = { w: 1, h: 1 };
      if (component.fieldType == "textarea") {
        finalWH = { w: 1, h: 2 };
      } else if (component.fieldType == "subTitle" || component.fieldType == "h2" || component.fieldType == "divider") {
        finalWH = {
          w: editConfigData.value.columns,
          h: editConfigData.value.labelPosition == "top" ? 0.75 : 1,
          isResizable: false
        };
      } else if (component.fieldType == "subForm" || component.fieldType == "subTable") {
        finalWH = {
          w: editConfigData.value.columns,
          h: editConfigData.value.labelPosition == "top" ? 1.5 : 2
        };
      } else if (component.fieldType == "approvalHistory" || component.fieldType == "document" || component.fieldType == "contract") {
        finalWH = {
          w: editConfigData.value.columns,
          h: editConfigData.value.labelPosition == "top" ? 2.25 : 3
        };
      }
      const colNum = editConfigData.value.columns;
      const rowHeight = editConfigData.value.labelPosition == "top" ? 90 : 60;
      const margin = 0;
      const cellWidth = (rect.width + margin) / colNum;
      const cellHeight = rowHeight + margin;
      const gridX = Math.floor(x / cellWidth);
      const gridY = Math.floor(y / cellHeight);
      const finalX = Math.max(0, Math.min(gridX, colNum - 1));
      const finalY = Math.max(0, gridY);
      let dropItem = layoutData.value.find((item) => item.i == dropId);
      if (!dropItem) {
        layoutData.value.push({
          x: finalX,
          y: finalY,
          w: finalWH.w,
          h: finalWH.h,
          i: dropId,
          isResizable: finalWH.isResizable === false ? false : true,
          component
        });
      } else {
        dropItem.x = finalX;
        dropItem.y = finalY;
      }
      nextTick(() => {
        var _a;
        const index = layoutData.value.findIndex((item) => item.i == dropId);
        if (index !== -1) {
          const item = (_a = gridLayout.value) == null ? void 0 : _a.getItem(dropId);
          if (!item) {
            return;
          }
          try {
            item.wrapper.style.display = "none";
          } catch (e) {
          }
          Object.assign(item.state, {
            top: y,
            left: x
          });
          item.calcXY(y, x);
          gridLayout.value.dragEvent(
            "dragstart",
            dropId,
            finalX,
            finalY,
            finalWH.h,
            finalWH.w
          );
          dragItem.x = layoutData.value[index].x;
          dragItem.y = layoutData.value[index].y;
          layoutDragData.value = [];
        }
      });
    });
    emitter.on("onFormDragStart", () => {
      addToGrid.value = false;
    });
    emitter.on("onFormDragEnd", (event) => {
      cachedRect = null;
      lastPosition = { x: null, y: null };
      const component = event.clonedData;
      const mouseX = event.originalEvent.clientX;
      const mouseY = event.originalEvent.clientY;
      const rect = document.querySelector(".form-grid-container").getBoundingClientRect();
      const isInRect = mouseX >= rect.left && mouseX <= rect.right && mouseY >= rect.top && mouseY <= rect.bottom;
      if (!isInRect) {
        gridLayout.value.dragEvent(
          "dragend",
          dropId,
          dragItem.x,
          dragItem.y,
          dragItem.h,
          dragItem.w
        );
        layoutData.value = layoutData.value.filter(
          (item) => item.i != dropId && item.i != component.id
        );
      }
      console.log("🚀 ~ onFormDragEnd:", event);
    });
    emitter.on("resizeEvent", () => {
      gridLayout.value.resizeEvent();
    });
    ref(/* @__PURE__ */ new Map());
    const isDragging = computed(() => {
      var _a;
      return ((_a = gridLayout.value) == null ? void 0 : _a.state.isDragging) || false;
    });
    function isLinkedVisibility(id) {
      var _a;
      const linkedVisibility = ((_a = editConfigData.value.linkedConfig) == null ? void 0 : _a.visibility) || [];
      for (const item of linkedVisibility) {
        if (item.dataLinkFieldList.includes(id)) {
          return true;
        }
      }
      return false;
    }
    __expose({
      onFormDragMove
    });
    return (_ctx, _cache) => {
      const _component_el_icon = ElIcon;
      const _component_Hide = resolveComponent("Hide");
      const _component_el_divider = ElDivider;
      const _component_el_form = ElForm;
      const _component_el_scrollbar = ElScrollbar;
      return openBlock(), createElementBlock("div", _hoisted_1, [
        createVNode(PageHeaderSetting),
        createVNode(FormSetting),
        createElementVNode("div", _hoisted_2, [
          createVNode(_component_el_scrollbar, null, {
            default: withCtx(() => [
              createVNode(_component_el_form, {
                class: "form-grid",
                "label-width": editConfigData.value.labelWidth,
                "label-position": editConfigData.value.labelPosition
              }, {
                default: withCtx(() => [
                  createVNode(unref(lo), {
                    draggable: "false",
                    modelValue: layoutDragData.value,
                    "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => layoutDragData.value = $event),
                    group: "dev",
                    class: "grid-draggable-wrapper",
                    onAdd: handleAddToGrid,
                    style: normalizeStyle(
                      gridWrapperHeight.value !== null ? "height: " + gridWrapperHeight.value + "px;" : ""
                    )
                  }, {
                    default: withCtx(() => [
                      createVNode(unref(De), {
                        ref_key: "gridLayout",
                        ref: gridLayout,
                        layout: layoutData.value,
                        "onUpdate:layout": _cache[1] || (_cache[1] = ($event) => layoutData.value = $event),
                        "row-height": editConfigData.value.labelPosition == "top" ? 90 : 60,
                        margin: [0, 0],
                        "col-num": editConfigData.value.columns,
                        "prevent-collision": false,
                        "vertical-compact": true,
                        style: { "height": "100%" }
                      }, {
                        item: withCtx(({ item }) => [
                          item.component ? (openBlock(), createElementBlock("div", {
                            key: 0,
                            class: normalizeClass(["form-component", [
                              unref(getCurrentClass)(item.component),
                              item.component.fieldType
                            ]]),
                            onMouseenter: ($event) => unref(setHoverItem)(item.component),
                            onMouseleave: _cache[0] || (_cache[0] = ($event) => unref(setHoverItem)()),
                            onClick: withModifiers(($event) => unref(setSelectedItem)(item.component), ["stop"])
                          }, [
                            !isDragging.value && unref(isSelectedItem)(item.component) ? (openBlock(), createElementBlock("div", _hoisted_4, [
                              createElementVNode("span", {
                                class: normalizeClass(["toolbar-btn required-btn", { "is-required": item.component.required }]),
                                title: "设置必填",
                                onClick: withModifiers(($event) => item.component.required = !item.component.required, ["stop"])
                              }, [
                                createVNode(_component_el_icon, null, {
                                  default: withCtx(() => [
                                    item.component.required ? (openBlock(), createBlock(unref(star_filled_default), { key: 0 })) : (openBlock(), createBlock(unref(star_default), { key: 1 }))
                                  ]),
                                  _: 2
                                }, 1024)
                              ], 10, _hoisted_5),
                              createElementVNode("span", {
                                class: normalizeClass(["toolbar-btn disabled-btn", { "is-disabled": item.component.disabled }]),
                                title: "设置只读",
                                onClick: withModifiers(($event) => item.component.disabled = !item.component.disabled, ["stop"])
                              }, [
                                createVNode(_component_el_icon, null, {
                                  default: withCtx(() => [
                                    item.component.disabled ? (openBlock(), createBlock(unref(lock_default), { key: 0 })) : (openBlock(), createBlock(unref(unlock_default), { key: 1 }))
                                  ]),
                                  _: 2
                                }, 1024)
                              ], 10, _hoisted_6),
                              createElementVNode("span", {
                                class: "toolbar-btn settings-btn",
                                title: "放进隐藏域",
                                onClick: withModifiers(($event) => handleHide(item), ["stop"])
                              }, [
                                createVNode(_component_el_icon, null, {
                                  default: withCtx(() => [
                                    createVNode(_component_Hide)
                                  ]),
                                  _: 1
                                })
                              ], 8, _hoisted_7),
                              createElementVNode("span", {
                                class: "toolbar-btn delete-btn",
                                title: "删除组件",
                                onClick: withModifiers(($event) => handleDelete(item), ["stop"])
                              }, [
                                createVNode(_component_el_icon, null, {
                                  default: withCtx(() => [
                                    createVNode(unref(delete_default))
                                  ]),
                                  _: 1
                                })
                              ], 8, _hoisted_8)
                            ])) : createCommentVNode("", true),
                            createElementVNode("div", _hoisted_9, [
                              editConfigData.value.showFieldName && item.component.fieldName ? (openBlock(), createElementBlock("div", _hoisted_10, toDisplayString(item.component.fieldType == "blank" ? "空白占位" : item.component.fieldName), 1)) : createCommentVNode("", true),
                              item.component.disabled ? (openBlock(), createElementBlock("div", _hoisted_11, [
                                createVNode(_component_el_icon, null, {
                                  default: withCtx(() => [
                                    createVNode(unref(lock_default))
                                  ]),
                                  _: 1
                                })
                              ])) : createCommentVNode("", true)
                            ]),
                            createElementVNode("div", {
                              class: normalizeClass(["component-content", {
                                "is-disabled": item.component.disabled,
                                "is-readonly": item.component.readOnly && !item.component.disabled,
                                "is-linked-visibility": isLinkedVisibility(
                                  item.component.id
                                )
                              }])
                            }, [
                              item.component.fieldType == "subTitle" ? (openBlock(), createBlock(SubTitle, {
                                key: 0,
                                "component-data": item.component
                              }, null, 8, ["component-data"])) : item.component.fieldType == "h2" ? (openBlock(), createBlock(H2Wrapper, {
                                key: 1,
                                "component-data": item.component
                              }, null, 8, ["component-data"])) : item.component.fieldType == "subForm" ? (openBlock(), createBlock(SubForm, {
                                key: 2,
                                "component-data": item.component
                              }, null, 8, ["component-data"])) : item.component.fieldType == "subTable" ? (openBlock(), createBlock(SubTable, {
                                key: 3,
                                "component-data": item.component
                              }, null, 8, ["component-data"])) : item.component.fieldType == "approvalHistory" ? (openBlock(), createBlock(ApprovalHistory, {
                                key: 4,
                                "component-data": item.component
                              }, null, 8, ["component-data"])) : item.component.fieldType == "document" ? (openBlock(), createBlock(Document, {
                                key: 5,
                                "component-data": item.component
                              }, null, 8, ["component-data"])) : item.component.fieldType == "contract" ? (openBlock(), createBlock(Contract, {
                                key: 6,
                                "component-data": item.component
                              }, null, 8, ["component-data"])) : item.component.fieldType == "divider" ? (openBlock(), createBlock(_component_el_divider, {
                                key: 7,
                                "border-style": "dashed"
                              }, {
                                default: withCtx(() => _cache[3] || (_cache[3] = [
                                  createTextVNode(" 此处为分割线，阻止下方组件自动向上补齐，解析时不显示 ")
                                ])),
                                _: 1
                              })) : (openBlock(), createBlock(ComponentPreviewWrapper, {
                                key: 8,
                                "component-data": item.component
                              }, null, 8, ["component-data"]))
                            ], 2)
                          ], 42, _hoisted_3)) : createCommentVNode("", true)
                        ]),
                        _: 1
                      }, 8, ["layout", "row-height", "col-num"])
                    ]),
                    _: 1
                  }, 8, ["modelValue", "style"])
                ]),
                _: 1
              }, 8, ["label-width", "label-position"])
            ]),
            _: 1
          })
        ]),
        createVNode(PageFooterSetting)
      ]);
    };
  }
};
const formWorkArea = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-d23df582"]]);
export {
  formWorkArea as default
};
