import { ElIcon } from "../../node_modules/element-plus/es/components/icon/index.mjs";
import { ElConfigProvider } from "../../node_modules/element-plus/es/components/config-provider/index.mjs";
import { ElButton } from "../../node_modules/element-plus/es/components/button/index.mjs";
import { ElTag } from "../../node_modules/element-plus/es/components/tag/index.mjs";
import { ElCheckbox } from "../../node_modules/element-plus/es/components/checkbox/index.mjs";
import { ElContainer, ElHeader, ElMain } from "../../node_modules/element-plus/es/components/container/index.mjs";
import { ElDropdown, ElDropdownMenu, ElDropdownItem } from "../../node_modules/element-plus/es/components/dropdown/index.mjs";
import { ElResult } from "../../node_modules/element-plus/es/components/result/index.mjs";
import "../../../_virtual/dayjs.min.mjs";
/* empty css                                                    */
/* empty css                                                         */
/* empty css                                                        */
/* empty css                                                            */
/* empty css                                                         */
/* empty css                                                         */
/* empty css                                                       */
import "../../node_modules/element-plus/theme-chalk/el-config-provider.css.mjs";
/* empty css                                                            */
/* empty css                                                         */
/* empty css                                                         */
/* empty css                                                               */
/* empty css                                                           */
import "../../node_modules/element-plus/theme-chalk/el-dropdown-menu.css.mjs";
import "../../node_modules/element-plus/theme-chalk/el-dropdown-item.css.mjs";
/* empty css                                                           */
/* empty css                                                      */
import { getCurrentInstance, ref, watch, nextTick, computed, onMounted, createBlock, openBlock, resolveDynamicComponent, unref, withCtx, createElementBlock, createCommentVNode, createVNode, createElementVNode, Fragment, toDisplayString, createTextVNode, renderList } from "vue";
import zh_cn_default from "../../node_modules/element-plus/es/locale/lang/zh-cn.mjs";
import { ElMessageBox, ElMessage } from "element-plus";
import api from "../api/index.mjs";
import LayoutDesigner from "./LayoutDesigner.vue.mjs";
import { loadComponentByPath, cloneDeep } from "../utils/common.mjs";
import { ArrowLeftBold as arrow_left_bold_default, Grid as grid_default, ArrowDown as arrow_down_default, Delete as delete_default, Refresh as refresh_default, Close as close_default, Select as select_default, Edit as edit_default } from "../../node_modules/@element-plus/icons-vue/dist/index.mjs";
import WelcomeView from "./WelcomeView.vue.mjs";
import packageJson from "../../package.json.mjs";
import { useStore } from "../../../node_modules/vuex/dist/vuex.esm-bundler.mjs";
import _export_sfc from "../../../_virtual/_plugin-vue_export-helper.mjs";
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 = useStore();
    const props = __props;
    const version = packageJson.version;
    const currentInstance = getCurrentInstance();
    const ctx = currentInstance.proxy;
    const relId = getUrlParam("relId") || props.relId;
    const relType = getUrlParam("relType") || props.relType;
    const layoutData = ref([]);
    const isEditing = ref(props.isEdit);
    const isInitd = ref(0);
    watch(isEditing, (val) => {
      nextTick(() => {
        resizeLayout();
      });
    });
    const componentLibrary = ref([]);
    const showWelcomeView = ref(false);
    const welcomeComponent = ref(WelcomeView);
    let pkId = null;
    async function init() {
      if (!relId || !relType) {
        isInitd.value = -1;
      } else {
        if (!store.getters.token) {
          const data = await api.login4dev(ctx.$http);
          store.commit("set_token", data.token);
          store.commit("set_refreshToken", data.refreshToken);
        }
        await fetchComponentLibrary();
        const templateData = await api.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 loadComponentByPath(
                props.defaultHomePageRoute,
                ctx.$router
              );
              welcomeComponent.value = comp;
            }
          }
          showWelcomeView.value = true;
        }
        isInitd.value = 1;
      }
    }
    const isOwner = ref(false);
    const devHeight = 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 = 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);
    }
    watch(layoutData, (data) => {
      if (data && data.length > 0) {
        nextTick(() => {
          resizeLayout();
        });
      }
    });
    window.addEventListener("resize", resizeLayout);
    const greeting = computed(() => {
      const hour = (/* @__PURE__ */ new Date()).getHours();
      if (hour < 12) return "上午好";
      if (hour < 18) return "下午好";
      return "晚上好";
    });
    async function fetchComponentLibrary() {
      let list;
      try {
        list = await api.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 = 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);
      });
    }
    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 = cloneDeep(item);
        delete copyItem.route;
        return copyItem;
      });
      api.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() {
      ElMessageBox.confirm("是否清空工作台所有组件?", "清空确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        layoutData.value = [];
        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 index = layoutData.value.findIndex(
          (item) => item.route === comp.route
        );
        if (index > -1) {
          layoutData.value.splice(index, 1);
        }
      }
    }
    function handleRestoreDefault() {
      ElMessageBox.confirm(
        "是否恢复成角色默认工作台？这将覆盖当前所有更改。",
        "恢复默认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        api.restoreToDefault(ctx.$http).then((templateData) => {
          if (!templateData) {
            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);
      }
    }
    onMounted(() => {
      init();
    });
    return (_ctx, _cache) => {
      const _component_el_icon = ElIcon;
      const _component_el_tag = ElTag;
      const _component_el_button = ElButton;
      const _component_el_checkbox = ElCheckbox;
      const _component_el_dropdown_item = ElDropdownItem;
      const _component_el_dropdown_menu = ElDropdownMenu;
      const _component_el_dropdown = ElDropdown;
      const _component_el_header = ElHeader;
      const _component_el_config_provider = ElConfigProvider;
      const _component_el_main = ElMain;
      const _component_el_container = ElContainer;
      const _component_el_result = ElResult;
      return showWelcomeView.value ? (openBlock(), createBlock(resolveDynamicComponent(welcomeComponent.value), { key: 0 })) : (openBlock(), createBlock(_component_el_config_provider, {
        key: 1,
        locale: unref(zh_cn_default)
      }, {
        default: withCtx(() => [
          isInitd.value == 1 ? (openBlock(), createBlock(_component_el_container, {
            key: 0,
            class: "fec-home-page-container"
          }, {
            default: withCtx(() => [
              isEditing.value ? (openBlock(), createBlock(_component_el_header, {
                key: 0,
                class: "fec-home-page-header"
              }, {
                default: withCtx(() => [
                  createElementVNode("div", _hoisted_1, [
                    __props.isBack ? (openBlock(), createElementBlock("span", {
                      key: 0,
                      class: "back-btn",
                      onClick: handleBack
                    }, [
                      createVNode(_component_el_icon, null, {
                        default: withCtx(() => [
                          createVNode(unref(arrow_left_bold_default))
                        ]),
                        _: 1
                      }),
                      _cache[1] || (_cache[1] = createElementVNode("span", null, "返回", -1))
                    ])) : createCommentVNode("", true),
                    __props.isEdit ? (openBlock(), createElementBlock(Fragment, { key: 1 }, [
                      _cache[2] || (_cache[2] = createElementVNode("div", { class: "title" }, "首页设计器", -1)),
                      createElementVNode("div", _hoisted_2, "v" + toDisplayString(unref(version)), 1)
                    ], 64)) : (openBlock(), createElementBlock("div", _hoisted_3, toDisplayString(greeting.value), 1))
                  ]),
                  createElementVNode("div", _hoisted_4, [
                    isEditing.value ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                      createVNode(_component_el_dropdown, {
                        trigger: "click",
                        placement: "bottom",
                        "hide-on-click": false,
                        onCommand: handleComponentSelect
                      }, {
                        dropdown: withCtx(() => [
                          createVNode(_component_el_dropdown_menu, { style: { "max-height": "600px" } }, {
                            default: withCtx(() => [
                              (openBlock(true), createElementBlock(Fragment, null, renderList(componentLibrary.value, (comp) => {
                                return openBlock(), createBlock(_component_el_dropdown_item, {
                                  key: comp.id,
                                  command: comp
                                }, {
                                  default: withCtx(() => [
                                    createVNode(_component_el_checkbox, {
                                      modelValue: comp.selected,
                                      "onUpdate:modelValue": ($event) => comp.selected = $event,
                                      onChange: () => {
                                        handleComponentCheck(comp);
                                      }
                                    }, {
                                      default: withCtx(() => [
                                        createElementVNode("span", _hoisted_5, toDisplayString(comp.label), 1)
                                      ]),
                                      _: 2
                                    }, 1032, ["modelValue", "onUpdate:modelValue", "onChange"])
                                  ]),
                                  _: 2
                                }, 1032, ["command"]);
                              }), 128)),
                              componentLibrary.value.length === 0 ? (openBlock(), createBlock(_component_el_dropdown_item, {
                                key: 0,
                                disabled: ""
                              }, {
                                default: withCtx(() => [..._cache[4] || (_cache[4] = [
                                  createElementVNode("span", {
                                    class: "component-label",
                                    style: { "text-align": "center" }
                                  }, "暂无可用组件", -1)
                                ])]),
                                _: 1
                              })) : createCommentVNode("", true)
                            ]),
                            _: 1
                          })
                        ]),
                        default: withCtx(() => [
                          createVNode(_component_el_button, {
                            icon: unref(grid_default),
                            style: { "margin-right": "12px" }
                          }, {
                            default: withCtx(() => [
                              _cache[3] || (_cache[3] = createTextVNode(" 组件库 ", -1)),
                              createVNode(_component_el_tag, {
                                size: "small",
                                type: "primary",
                                class: "col-count"
                              }, {
                                default: withCtx(() => [
                                  createTextVNode(toDisplayString(selectedCount.value) + "/" + toDisplayString(componentLibrary.value.length), 1)
                                ]),
                                _: 1
                              }),
                              createVNode(_component_el_icon, { class: "el-icon--right" }, {
                                default: withCtx(() => [
                                  createVNode(unref(arrow_down_default))
                                ]),
                                _: 1
                              })
                            ]),
                            _: 1
                          }, 8, ["icon"])
                        ]),
                        _: 1
                      }),
                      createVNode(_component_el_button, {
                        icon: unref(delete_default),
                        onClick: handleClear
                      }, {
                        default: withCtx(() => [..._cache[5] || (_cache[5] = [
                          createTextVNode(" 清空工作台 ", -1)
                        ])]),
                        _: 1
                      }, 8, ["icon"]),
                      isOwner.value && !props.isEdit ? (openBlock(), createBlock(_component_el_button, {
                        key: 0,
                        icon: unref(refresh_default),
                        onClick: handleRestoreDefault
                      }, {
                        default: withCtx(() => [..._cache[6] || (_cache[6] = [
                          createTextVNode(" 恢复默认 ", -1)
                        ])]),
                        _: 1
                      }, 8, ["icon"])) : createCommentVNode("", true),
                      !props.isEdit ? (openBlock(), createBlock(_component_el_button, {
                        key: 1,
                        icon: unref(close_default),
                        onClick: handleCancel
                      }, {
                        default: withCtx(() => [..._cache[7] || (_cache[7] = [
                          createTextVNode(" 取消 ", -1)
                        ])]),
                        _: 1
                      }, 8, ["icon"])) : createCommentVNode("", true),
                      createVNode(_component_el_button, {
                        icon: unref(select_default),
                        type: "primary",
                        onClick: handleSave
                      }, {
                        default: withCtx(() => [..._cache[8] || (_cache[8] = [
                          createTextVNode(" 保存 ", -1)
                        ])]),
                        _: 1
                      }, 8, ["icon"])
                    ], 64)) : createCommentVNode("", true)
                  ])
                ]),
                _: 1
              })) : createCommentVNode("", true),
              createVNode(_component_el_main, { class: "fec-home-page-main" }, {
                default: withCtx(() => [
                  !isEditing.value ? (openBlock(), createElementBlock("div", {
                    key: 0,
                    class: "floating-edit-btn",
                    onClick: handleEdit
                  }, [
                    createVNode(_component_el_icon, { size: 18 }, {
                      default: withCtx(() => [
                        createVNode(unref(edit_default))
                      ]),
                      _: 1
                    })
                  ])) : createCommentVNode("", true),
                  createVNode(_component_el_config_provider, { locale: unref(zh_cn_default) }, {
                    default: withCtx(() => [
                      createVNode(LayoutDesigner, {
                        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 ? (openBlock(), createElementBlock("div", _hoisted_6, [
            createVNode(_component_el_result, {
              icon: "warning",
              title: "缺少关联ID 或 关联类型",
              "sub-title": "请提供有效的关联ID(relId) 或 关联类型(relType)参数"
            })
          ])) : createCommentVNode("", true)
        ]),
        _: 1
      }, 8, ["locale"]));
    };
  }
};
const layout = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-340b4846"]]);
export {
  layout as default
};
