<template>
  <Layout style="height: 100vh" :key="actionStore.appKey">
    <LayoutHeader style="background: #fff">
      <div class="header-left">
        <h1>{{ projectStore.projectInfo.name || "大屏标题" }}</h1>
      </div>
      <div class="header-middle">
        <MenuBar />
      </div>
      <div class="header-right">
        <Button size="small" style="margin-right: 8px" @click="handlePreivewJson"
          ><ExportOutlined />生成json</Button
        >
        <Upload :before-upload="handleUpload" :show-upload-list="false" accept=".json">
          <Button size="small" style="margin-right: 8px"
            ><ImportOutlined />导入json</Button
          >
        </Upload>
        <Button size="small" style="margin-right: 8px" @click="handleJson"
          ><ExportOutlined />导出json</Button
        >
        <Button size="small" style="margin-right: 8px" @click="handlePreview"
          ><DesktopOutlined />预览</Button
        >
        <Button
          size="small"
          type="primary"
          @click="handleSave"
          :loading="loading"
          ><SaveOutlined />保存</Button
        >
      </div>
    </LayoutHeader>

    <LayoutContent>
      <div
        class="layer-wrapper"
        :style="{ width: stageStore.showLayer ? '200px' : '0px' }"
      >
        <!-- 图层管理 -->
        <LayerManagement v-show="stageStore.showLayer" />
      </div>
      <div class="component-wrapper" >
        <!-- 组件库 -->
        <ComponentLibary />
      </div>
      <div class="workspace-wrapper">
        <!-- 舞台 -->
        <Workspace />
      </div>
      <div class="config-wrapper">
        <!-- 属性配置 -->
        <Configurator />
      </div>
    </LayoutContent>
  </Layout>

  <CodeEditorModal ref="codeEditorModalRef" title="生成JSON"/>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import {
  Layout,
  LayoutHeader,
  LayoutContent,
  Button,
  message,
  Upload,
} from "ant-design-vue";
import { DesktopOutlined, SaveOutlined, ImportOutlined, ExportOutlined } from "@ant-design/icons-vue";
import { useProjectStore } from "@/store/modules/project";
import { useStageStore } from "@/store/modules/stage";
import { useAcionStore } from "@/store/modules/action";
import { useRoute } from "vue-router";
import { useRequest } from "vue-hooks-plus";
import { useAppStore } from "@/store/modules/app";
import { getPageDesignApi } from "@shalu/service";
import { CodeEditorModal } from "@shalu/dashboard-ui/components/codeEditor";

import LayerManagement from "./component/LayerManagement.vue";
import ComponentLibary from "./component/ComponentLibary.vue";
import Workspace from "./component/Workspace.vue";
import Configurator from "./component/Configurator.vue";
import MenuBar from "./component/MenuBar.vue";

const route = useRoute();

const stageStore = useStageStore();
const projectStore = useProjectStore();
const appStore = useAppStore();
const loading = ref(false);
const actionStore = useAcionStore();
const codeEditorModalRef = ref();

const { run, loading: loadingPage } = useRequest(getPageDesignApi, {
  manual: true,
  onSuccess: (res) => {
    const { appPageId, pcJson } = res;
    if(pcJson) {
      projectStore.setProjectInfo(JSON.parse(pcJson));
      return;
    }
    if(appPageId) {
      projectStore.updateProjectInfo({ pageId: appPageId });
    }
    actionStore.initRecord();
  },
  onError: (e) => {
    console.error(e);
    message.error("获取页面信息失败");
  },
});

/* 获取项目信息 */
projectStore.getCurrentProjectInfo();
// 传入pageId和token，获取页面信息
if(route.query?.pageId && route.query?.token) {
  const { token, pageId } = route.query;
  localStorage.setItem("token", token as string);
  run({id: pageId as string});
} else {
  actionStore.initRecord();
}

watch(
  () => loadingPage.value,
  () => {
    appStore.setPageLoading(loadingPage.value);
  },
)

watch(
  () => projectStore.projectInfo.name,
  (val) => {

    document.title = val || "大屏设计";
  },
  {
    immediate: true
  }
)

const handlePreview = () => {
  localStorage.setItem(
    "currentProject",
    JSON.stringify(projectStore.projectInfo)
  );
  window.open("#/view?id=1");
};

const handleSave = async () => {
  if(!route.query?.pageId) {
    message.error("未找到页面Id");
    return;
  }
  try {
    loading.value = true;
    localStorage.setItem(
      "currentProject",
      JSON.stringify(projectStore.projectInfo)
    );

    await projectStore.handleSaveProject(route.query?.pageId as string);
  } catch (e) {
    loading.value = false;
    message.error("保存失败");
  } finally {
    loading.value = false;
  }
};

const handleJson = () => {
  const json = JSON.stringify(projectStore.projectInfo);
  const blob = new Blob([json], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = projectStore.projectInfo.name + ".json";
  a.click();
  URL.revokeObjectURL(url);
};

const handleUpload = (file: File) => {
  appStore.setPageLoading(true);
  const reader = new FileReader();
  reader.onload = (e) => {
    const result = e.target?.result;
    if (typeof result === "string") {
      try {
        const json = JSON.parse(result);
        projectStore.setProjectInfo(json);
        message.success("导入成功");
      } catch (e) {
        message.error("文件格式错误");
      } finally {
        appStore.setPageLoading(false);
      }
    }
  };
  reader.readAsText(file);
  reader.onerror = () => {
    appStore.setPageLoading(false);
    message.error("文件读取失败");
  };
  return false;
};

/**
 * 生成json预览
 */
const handlePreivewJson = () => {
  codeEditorModalRef.value.open(JSON.stringify(projectStore.projectInfo, null, 2));
}

</script>

<style lang="less" scoped>
.ant-layout-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  border-bottom: solid 1px #eee;
  z-index: 2;
  .ant-btn {
    font-size: 12px;
  }
  .header-left h1 {
    width: 300px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .header-right {
    width: 500px;
    text-align: right;
  }
}

.ant-layout-content {
  display: flex;
}

.layer-wrapper {
  position: relative;
  // width: 200px;
  background: #fff;
  z-index: 2;
}
.component-wrapper {
  position: relative;
  background: @bg-color;
  z-index: 1;
  border-right: solid 1px #f0f0f0;
}
.workspace-wrapper {
  position: relative;
  flex: 1;
  z-index: 0;
}
.config-wrapper {
  position: relative;
  background: #fff;
  border-left: solid 1px #eee;
}
</style>
