"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const index$2 = require("../../node_modules/element-plus/es/components/icon/index.js");
const index = require("../../node_modules/element-plus/es/components/config-provider/index.js");
const index$5 = require("../../node_modules/element-plus/es/components/button/index.js");
const index$6 = require("../../node_modules/element-plus/es/components/tag/index.js");
const index$7 = require("../../node_modules/element-plus/es/components/checkbox/index.js");
const index$1 = require("../../node_modules/element-plus/es/components/container/index.js");
const index$4 = require("../../node_modules/element-plus/es/components/dropdown/index.js");
const index$8 = require("../../node_modules/element-plus/es/components/result/index.js");
require("../../../_virtual/dayjs.min.js");
;/* empty css                                                    */
;/* empty css                                                         */
;/* empty css                                                        */
;/* empty css                                                            */
;/* empty css                                                         */
;/* empty css                                                         */
;/* empty css                                                       */
require("../../node_modules/element-plus/theme-chalk/el-config-provider.css.js");
;/* empty css                                                            */
;/* empty css                                                         */
;/* empty css                                                         */
;/* empty css                                                               */
;/* empty css                                                           */
require("../../node_modules/element-plus/theme-chalk/el-dropdown-menu.css.js");
require("../../node_modules/element-plus/theme-chalk/el-dropdown-item.css.js");
;/* empty css                                                           */
;/* empty css                                                      */
const vue = require("vue");
const zhCn = require("../../node_modules/element-plus/es/locale/lang/zh-cn.js");
const elementPlus = require("element-plus");
const index$9 = require("../api/index.js");
const LayoutDesigner = require("./LayoutDesigner.vue.js");
const common = require("../utils/common.js");
const index$3 = require("../../node_modules/@element-plus/icons-vue/dist/index.js");
const WelcomeView = require("./WelcomeView.vue.js");
const _package = require("../../package.json.js");
const vuex_esmBundler = require("../../../node_modules/vuex/dist/vuex.esm-bundler.js");
const _pluginVue_exportHelper = require("../../../_virtual/_plugin-vue_export-helper.js");
const _hoisted_1 = { class: "header-left" };
const _hoisted_2 = { class: "version" };
const _hoisted_3 = {
  key: 2,
  class: "title"
};
const _hoisted_4 = { class: "header-right" };
const _hoisted_5 = { class: "component-label" };
const _hoisted_6 = {
  key: 1,
  class: "init-error-container"
};
const TOTAL_GRID_ROWS = 36;
const _sfc_main = {
  __name: "index",
  props: {
    isBack: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    defaultHomePageRoute: {
      type: String,
      default: ""
    },
    relId: {
      type: String,
      default: ""
    },
    relType: {
      type: String,
      default: ""
    }
  },
  setup(__props) {
    const store = vuex_esmBundler.useStore();
    const props = __props;
    const version = _package.default.version;
    const currentInstance = vue.getCurrentInstance();
    const ctx = currentInstance.proxy;
    const relId = getUrlParam("relId") || props.relId;
    const relType = getUrlParam("relType") || props.relType;
    const layoutData = vue.ref([]);
    const isEditing = vue.ref(props.isEdit);
    const isInitd = vue.ref(0);
    vue.watch(isEditing, (val) => {
      vue.nextTick(() => {
        resizeLayout();
      });
    });
    const componentLibrary = vue.ref([]);
    const showWelcomeView = vue.ref(false);
    const welcomeComponent = vue.ref(WelcomeView.default);
    let pkId = null;
    async function init() {
      if (!relId || !relType) {
        isInitd.value = -1;
      } else {
        if (!store.getters.token) {
          const data = await index$9.default.login4dev(ctx.$http);
          store.commit("set_token", data.token);
          store.commit("set_refreshToken", data.refreshToken);
        }
        await fetchComponentLibrary();
        const templateData = await index$9.default.getTemplateByRelIdType(
          ctx.$http,
          relId,
          relType
        );
        if (templateData) {
          pkId = templateData.pkId;
          parseComponentLibrary2layoutData(templateData);
        }
        if (layoutData.value.length == 0 && "owner" == relType) {
          if (props.defaultHomePageRoute) {
            const hasRoute = ctx.$router.getRoutes().find((item) => item.path == props.defaultHomePageRoute);
            if (hasRoute) {
              const comp = await common.loadComponentByPath(
                props.defaultHomePageRoute,
                ctx.$router
              );
              welcomeComponent.value = comp;
            }
          }
          showWelcomeView.value = true;
        }
        isInitd.value = 1;
      }
    }
    const isOwner = vue.ref(false);
    const devHeight = vue.ref(0);
    function parseComponentLibrary2layoutData(templateData) {
      const layoutContext = JSON.parse(templateData.context) || [];
      if (layoutContext) {
        devHeight.value = layoutContext.containerHeight;
        const configData = layoutContext.config;
        configData.forEach((item) => {
          const comp = componentLibrary.value.find((comp2) => comp2.id == item.id);
          item.route = comp == null ? void 0 : comp.route;
        });
        layoutData.value = configData;
      }
      if (templateData.relType == "owner") {
        isOwner.value = true;
      } else {
        isOwner.value = false;
      }
    }
    const rowHeight = vue.ref(30);
    function resizeLayout() {
      const currHeight = document.querySelector(
        ".home-page-work-container"
      ).offsetHeight;
      rowHeight.value = (currHeight - 12) / TOTAL_GRID_ROWS;
      rowHeight.value = Math.round(rowHeight.value * 100) / 100;
      console.log("🚀 ~ resizeLayout ~ rowHeight.value:", rowHeight.value);
    }
    vue.watch(layoutData, (data) => {
      if (data && data.length > 0) {
        vue.nextTick(() => {
          resizeLayout();
        });
      }
    });
    window.addEventListener("resize", resizeLayout);
    const greeting = vue.computed(() => {
      const hour = (/* @__PURE__ */ new Date()).getHours();
      if (hour < 12) return "上午好";
      if (hour < 18) return "下午好";
      return "晚上好";
    });
    async function fetchComponentLibrary() {
      let list;
      try {
        list = await index$9.default.getWorkbenchComponents(ctx.$http, "homePage");
      } catch (err) {
        list = [];
      }
      componentLibrary.value = list.map((comp) => {
        const defaultConfig = JSON.parse(comp.defaultConfig);
        return {
          id: comp.moduleSubType,
          label: comp.moduleSubName,
          route: comp.route,
          w: defaultConfig.w,
          h: defaultConfig.h,
          minW: defaultConfig.minW,
          minH: defaultConfig.minH,
          isResizable: defaultConfig.isResizable,
          selected: false
        };
      });
    }
    const selectedCount = vue.computed(() => {
      return componentLibrary.value.filter((comp) => comp.selected).length;
    });
    function syncComponentLibrarySelected() {
      const routeSet = new Set(layoutData.value.map((item) => item.route));
      componentLibrary.value.forEach((comp) => {
        comp.selected = routeSet.has(comp.route);
      });
    }
    vue.watch(
      layoutData,
      () => {
        syncComponentLibrarySelected();
      },
      { deep: true, immediate: true }
    );
    let backupLayoutData = null;
    function handleEdit() {
      backupLayoutData = JSON.parse(JSON.stringify(layoutData.value));
      isEditing.value = true;
    }
    function handleSave() {
      document.querySelector(
        ".home-page-work-container"
      ).offsetHeight;
      const homePageConfig = layoutData.value.map((item) => {
        const copyItem = common.cloneDeep(item);
        delete copyItem.route;
        return copyItem;
      });
      index$9.default.saveTemplate(ctx.$http, {
        pkId,
        relId,
        relType,
        context: JSON.stringify({ config: homePageConfig })
      }).then((data) => {
        if (!props.isEdit) {
          isEditing.value = false;
        }
        pkId = data.pkId;
      });
    }
    function handleCancel() {
      if (backupLayoutData) {
        layoutData.value = backupLayoutData;
      }
      isEditing.value = false;
    }
    function handleClear() {
      elementPlus.ElMessageBox.confirm("是否清空工作台所有组件?", "清空确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        layoutData.value = [];
        elementPlus.ElMessage.success("已清空工作台");
      }).catch(() => {
      });
    }
    function handleComponentSelect(comp) {
    }
    function handleComponentCheck(comp) {
      if (comp.selected) {
        layoutData.value.forEach((item) => {
          item.y += 1;
        });
        const newItem = {
          x: 0,
          y: 0,
          w: comp.w || 3,
          h: comp.h || 3,
          minW: comp.minW || 1,
          minH: comp.minH || 1,
          i: Date.now().toString(),
          route: comp.route,
          id: comp.id,
          label: comp.label,
          isResizable: comp.isResizable
        };
        layoutData.value.push(newItem);
      } else {
        const index2 = layoutData.value.findIndex(
          (item) => item.route === comp.route
        );
        if (index2 > -1) {
          layoutData.value.splice(index2, 1);
        }
      }
    }
    function handleRestoreDefault() {
      elementPlus.ElMessageBox.confirm(
        "是否恢复成角色默认工作台？这将覆盖当前所有更改。",
        "恢复默认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        index$9.default.restoreToDefault(ctx.$http).then((templateData) => {
          if (!templateData) {
            elementPlus.ElMessage.warning("当前角色未配置首页不能恢复");
            return;
          }
          pkId = templateData.pkId;
          parseComponentLibrary2layoutData(templateData);
          if (!props.isEdit) {
            isEditing.value = false;
          }
        });
      }).catch(() => {
      });
    }
    function getUrlParam(key) {
      const targetUrl = window.location.href;
      const searchStr = targetUrl.split("?")[1] || "";
      if (!searchStr) return null;
      const params = new URLSearchParams(searchStr);
      const values = params.getAll(key);
      if (values.length === 0) return null;
      return values.length === 1 ? values[0] : values;
    }
    function handleBack() {
      const hasRoute = ctx.$router;
      if (hasRoute) {
        ctx.$router.go(-1);
      }
    }
    vue.onMounted(() => {
      init();
    });
    return (_ctx, _cache) => {
      const _component_el_icon = index$2.ElIcon;
      const _component_el_tag = index$6.ElTag;
      const _component_el_button = index$5.ElButton;
      const _component_el_checkbox = index$7.ElCheckbox;
      const _component_el_dropdown_item = index$4.ElDropdownItem;
      const _component_el_dropdown_menu = index$4.ElDropdownMenu;
      const _component_el_dropdown = index$4.ElDropdown;
      const _component_el_header = index$1.ElHeader;
      const _component_el_config_provider = index.ElConfigProvider;
      const _component_el_main = index$1.ElMain;
      const _component_el_container = index$1.ElContainer;
      const _component_el_result = index$8.ElResult;
      return showWelcomeView.value ? (vue.openBlock(), vue.createBlock(vue.resolveDynamicComponent(welcomeComponent.value), { key: 0 })) : (vue.openBlock(), vue.createBlock(_component_el_config_provider, {
        key: 1,
        locale: vue.unref(zhCn.default)
      }, {
        default: vue.withCtx(() => [
          isInitd.value == 1 ? (vue.openBlock(), vue.createBlock(_component_el_container, {
            key: 0,
            class: "fec-home-page-container"
          }, {
            default: vue.withCtx(() => [
              isEditing.value ? (vue.openBlock(), vue.createBlock(_component_el_header, {
                key: 0,
                class: "fec-home-page-header"
              }, {
                default: vue.withCtx(() => [
                  vue.createElementVNode("div", _hoisted_1, [
                    __props.isBack ? (vue.openBlock(), vue.createElementBlock("span", {
                      key: 0,
                      class: "back-btn",
                      onClick: handleBack
                    }, [
                      vue.createVNode(_component_el_icon, null, {
                        default: vue.withCtx(() => [
                          vue.createVNode(vue.unref(index$3.ArrowLeftBold))
                        ]),
                        _: 1
                      }),
                      _cache[1] || (_cache[1] = vue.createElementVNode("span", null, "返回", -1))
                    ])) : vue.createCommentVNode("", true),
                    __props.isEdit ? (vue.openBlock(), vue.createElementBlock(vue.Fragment, { key: 1 }, [
                      _cache[2] || (_cache[2] = vue.createElementVNode("div", { class: "title" }, "首页设计器", -1)),
                      vue.createElementVNode("div", _hoisted_2, "v" + vue.toDisplayString(vue.unref(version)), 1)
                    ], 64)) : (vue.openBlock(), vue.createElementBlock("div", _hoisted_3, vue.toDisplayString(greeting.value), 1))
                  ]),
                  vue.createElementVNode("div", _hoisted_4, [
                    isEditing.value ? (vue.openBlock(), vue.createElementBlock(vue.Fragment, { key: 0 }, [
                      vue.createVNode(_component_el_dropdown, {
                        trigger: "click",
                        placement: "bottom",
                        "hide-on-click": false,
                        onCommand: handleComponentSelect
                      }, {
                        dropdown: vue.withCtx(() => [
                          vue.createVNode(_component_el_dropdown_menu, { style: { "max-height": "600px" } }, {
                            default: vue.withCtx(() => [
                              (vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(componentLibrary.value, (comp) => {
                                return vue.openBlock(), vue.createBlock(_component_el_dropdown_item, {
                                  key: comp.id,
                                  command: comp
                                }, {
                                  default: vue.withCtx(() => [
                                    vue.createVNode(_component_el_checkbox, {
                                      modelValue: comp.selected,
                                      "onUpdate:modelValue": ($event) => comp.selected = $event,
                                      onChange: () => {
                                        handleComponentCheck(comp);
                                      }
                                    }, {
                                      default: vue.withCtx(() => [
                                        vue.createElementVNode("span", _hoisted_5, vue.toDisplayString(comp.label), 1)
                                      ]),
                                      _: 2
                                    }, 1032, ["modelValue", "onUpdate:modelValue", "onChange"])
                                  ]),
                                  _: 2
                                }, 1032, ["command"]);
                              }), 128)),
                              componentLibrary.value.length === 0 ? (vue.openBlock(), vue.createBlock(_component_el_dropdown_item, {
                                key: 0,
                                disabled: ""
                              }, {
                                default: vue.withCtx(() => [..._cache[4] || (_cache[4] = [
                                  vue.createElementVNode("span", {
                                    class: "component-label",
                                    style: { "text-align": "center" }
                                  }, "暂无可用组件", -1)
                                ])]),
                                _: 1
                              })) : vue.createCommentVNode("", true)
                            ]),
                            _: 1
                          })
                        ]),
                        default: vue.withCtx(() => [
                          vue.createVNode(_component_el_button, {
                            icon: vue.unref(index$3.Grid),
                            style: { "margin-right": "12px" }
                          }, {
                            default: vue.withCtx(() => [
                              _cache[3] || (_cache[3] = vue.createTextVNode(" 组件库 ", -1)),
                              vue.createVNode(_component_el_tag, {
                                size: "small",
                                type: "primary",
                                class: "col-count"
                              }, {
                                default: vue.withCtx(() => [
                                  vue.createTextVNode(vue.toDisplayString(selectedCount.value) + "/" + vue.toDisplayString(componentLibrary.value.length), 1)
                                ]),
                                _: 1
                              }),
                              vue.createVNode(_component_el_icon, { class: "el-icon--right" }, {
                                default: vue.withCtx(() => [
                                  vue.createVNode(vue.unref(index$3.ArrowDown))
                                ]),
                                _: 1
                              })
                            ]),
                            _: 1
                          }, 8, ["icon"])
                        ]),
                        _: 1
                      }),
                      vue.createVNode(_component_el_button, {
                        icon: vue.unref(index$3.Delete),
                        onClick: handleClear
                      }, {
                        default: vue.withCtx(() => [..._cache[5] || (_cache[5] = [
                          vue.createTextVNode(" 清空工作台 ", -1)
                        ])]),
                        _: 1
                      }, 8, ["icon"]),
                      isOwner.value && !props.isEdit ? (vue.openBlock(), vue.createBlock(_component_el_button, {
                        key: 0,
                        icon: vue.unref(index$3.Refresh),
                        onClick: handleRestoreDefault
                      }, {
                        default: vue.withCtx(() => [..._cache[6] || (_cache[6] = [
                          vue.createTextVNode(" 恢复默认 ", -1)
                        ])]),
                        _: 1
                      }, 8, ["icon"])) : vue.createCommentVNode("", true),
                      !props.isEdit ? (vue.openBlock(), vue.createBlock(_component_el_button, {
                        key: 1,
                        icon: vue.unref(index$3.Close),
                        onClick: handleCancel
                      }, {
                        default: vue.withCtx(() => [..._cache[7] || (_cache[7] = [
                          vue.createTextVNode(" 取消 ", -1)
                        ])]),
                        _: 1
                      }, 8, ["icon"])) : vue.createCommentVNode("", true),
                      vue.createVNode(_component_el_button, {
                        icon: vue.unref(index$3.Select),
                        type: "primary",
                        onClick: handleSave
                      }, {
                        default: vue.withCtx(() => [..._cache[8] || (_cache[8] = [
                          vue.createTextVNode(" 保存 ", -1)
                        ])]),
                        _: 1
                      }, 8, ["icon"])
                    ], 64)) : vue.createCommentVNode("", true)
                  ])
                ]),
                _: 1
              })) : vue.createCommentVNode("", true),
              vue.createVNode(_component_el_main, { class: "fec-home-page-main" }, {
                default: vue.withCtx(() => [
                  !isEditing.value ? (vue.openBlock(), vue.createElementBlock("div", {
                    key: 0,
                    class: "floating-edit-btn",
                    onClick: handleEdit
                  }, [
                    vue.createVNode(_component_el_icon, { size: 18 }, {
                      default: vue.withCtx(() => [
                        vue.createVNode(vue.unref(index$3.Edit))
                      ]),
                      _: 1
                    })
                  ])) : vue.createCommentVNode("", true),
                  vue.createVNode(_component_el_config_provider, { locale: vue.unref(zhCn.default) }, {
                    default: vue.withCtx(() => [
                      vue.createVNode(LayoutDesigner.default, {
                        modelValue: layoutData.value,
                        "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => layoutData.value = $event),
                        "read-only": !isEditing.value,
                        rowHeight: rowHeight.value
                      }, null, 8, ["modelValue", "read-only", "rowHeight"])
                    ]),
                    _: 1
                  }, 8, ["locale"])
                ]),
                _: 1
              })
            ]),
            _: 1
          })) : isInitd.value == -1 ? (vue.openBlock(), vue.createElementBlock("div", _hoisted_6, [
            vue.createVNode(_component_el_result, {
              icon: "warning",
              title: "缺少关联ID 或 关联类型",
              "sub-title": "请提供有效的关联ID(relId) 或 关联类型(relType)参数"
            })
          ])) : vue.createCommentVNode("", true)
        ]),
        _: 1
      }, 8, ["locale"]));
    };
  }
};
const layout = /* @__PURE__ */ _pluginVue_exportHelper.default(_sfc_main, [["__scopeId", "data-v-340b4846"]]);
exports.default = layout;
