<template>
  <Slide :menus="menus" :draw="draw" />
</template>

<script lang="ts" setup>
import Slide from "../../../components/slide/slide.vue";
import {
  paper as paperRaw,
  text,
  serial,
  table,
  test,
  PaperKey,
  draw as drawMenuRaw,
} from "../../../components/slide/actions.ts";
import { useDraw } from "../../../components/container/use-draw.ts";
import { computed, h, nextTick, reactive, watch } from "vue";
import { tabulationData } from "../../store";
import { genTabulationData } from "./gen-tab.ts";
import { defaultLayer } from "@/constant/index.ts";
import { copy } from "@/utils/shared.ts";
import { v4 as uuid } from "uuid";
import SlideIcons from "@/example/components/slide/slide-icons.vue";
import { iconGroups } from "@/example/constant.ts";

const draw = useDraw();
const paper = reactive({
  ...paperRaw,
  children: paperRaw.children.map((item) => ({
    ...item,
    active: computed(() => tabulationData.value.paperKey === item.key),
    handler: () => (tabulationData.value.paperKey = item.key as PaperKey),
  })),
});

const drawMenu = copy(drawMenuRaw);
drawMenu.children!.shift();

const menus = reactive([
  paper,
  drawMenu,
  {
    icon: "legend",
    name: "图例",
    value: uuid(),
    mount: (props: any) =>
      h(SlideIcons, { ...props, groups: [iconGroups[iconGroups.length - 1]] }),
  },
  {
    ...text,
    payload: { ...text.payload, preset: { ...text.payload.preset, fontSize: 16 } },
  },
  serial,
  table,
]);

const setPaperAfterHandler = async (paperKey: PaperKey, oldPaperKey?: PaperKey) => {
  let isUpdate = false;
  // if (oldPaperKey) {
  //   try {
  //     await ElMessageBox.confirm(
  //       "纸张已变化， 是否需要重新生成模板数据（会清空已有数据）？",
  //       {
  //         type: "info",
  //         confirmButtonText: "生成",
  //         cancelButtonText: "取消",
  //       }
  //     );
  //     isUpdate = true;
  //   } catch {
  //     isUpdate = false;
  //   }
  // }
  paperRaw.children.find((item) => item.key === paperKey)!.handler(draw);
  await nextTick();
  if (!isUpdate) return;

  const data = await genTabulationData(
    paperKey,
    tabulationData.value.store.config.compass.rotation,
    tabulationData.value.cover
  );

  draw.history.clear();
  draw.store.setStore({
    layers: {
      [defaultLayer]: data,
    },
  });
};

watch(() => tabulationData.value?.paperKey, setPaperAfterHandler, { immediate: true });

if (import.meta.env.DEV) {
  menus.push(test);
}
</script>
