<template>
  <Header
    :action-groups="actions"
    :title="title"
    :draw="draw"
    :noBack="!overviewId"
    @back="router.replace({ name: 'overview', query: router.currentRoute.value.query })"
  >
    <template #saves>
      <el-button type="primary" @click="saveHandler" :disabled="draw.drawing">
        保存
      </el-button>
    </template>
  </Header>
</template>

<script lang="ts" setup>
import { ElButton, ElMessage } from "element-plus";
import { useDraw } from "../../../components/container/use-draw.ts";
import Header from "../../../components/header/index.vue";
import { getHeaderActions } from "../../../components/header/actions.ts";
import { Transform } from "konva/lib/Util";
import { selectExposeFormat } from "@/example/dialog/expose/index.ts";
import { grayscaleImage } from "@/utils/dom.ts";
import saveAs from "@/utils/file-serve.ts";
import { jsPDF } from "jspdf";
import { getImage as getResourceImage } from "@/utils/resource.ts";
import { nextTick, onUnmounted } from "vue";
import { tabulationData } from "../../store.ts";
import { Mode } from "@/constant/mode.ts";
import { overviewId, tabulationId } from "@/example/env.ts";
import { listener } from "@/utils/event.ts";
import { router } from "../../router.ts";
import { paperConfigs } from "@/example/components/slide/actions.ts";

const props = defineProps<{ title: string }>();

const draw = useDraw();
const getCoverImage = (format: string) => {
  return draw.enterTemp(async () => {
    const pop = draw.mode.push(Mode.readonly);
    const oldMat = draw.viewer.viewMat;
    draw.viewer.setViewMat([1, 0, 0, 1, 0, 0]);
    await nextTick();

    const viewSize = draw.viewer.viewSize!;
    const size = {
      width: draw.stage!.width(),
      height: draw.stage!.height(),
    };
    const rect = {
      x: (size.width - viewSize.width) / 2,
      y: (size.height - viewSize.height) / 2,
      ...viewSize,
    };

    let fileBlob = await (draw.stage!.toBlob({
      pixelRatio: 4,
      mimeType: format,
      quality: 1,
      ...rect,
    }) as Promise<Blob>);
    draw.viewer.setViewMat(oldMat);
    pop();
    return [rect, fileBlob] as const;
  });
};
const baseActions = getHeaderActions(draw);
const actions = [
  [baseActions.undo, baseActions.redo],
  [
    // baseActions.clear,
    {
      ...baseActions.initViewport,
      handler: () => {
        draw.viewer.setViewMat(new Transform());
      },
    },
  ],
  [
    {
      handler: async () => {
        const ef = await selectExposeFormat();
        const format = "image/jpeg";
        let [rect, fileBlob] = await getCoverImage(format);
        const filename = props.title;
        let ext = "jpg";

        if (ef.color === "grayscale") {
          const url = URL.createObjectURL(fileBlob);
          const img = await getResourceImage(url);
          fileBlob = await grayscaleImage(img, undefined, format);
          URL.revokeObjectURL(url);
        }

        if (ef.format === "PDF") {
          const paperKey = tabulationData.value?.paperKey || "a4";
          const paperSize = paperConfigs[paperKey].size;
          const url = URL.createObjectURL(fileBlob);
          const img = await getResourceImage(url);
          const pdf = new jsPDF({
            orientation: paperSize[0] > paperSize[1] ? "landscape" : "portrait",
            unit: "mm",
            format: paperKey,
          });
          pdf.addImage(img, format, 0, 0, paperSize[0], paperSize[1]);
          fileBlob = pdf.output("blob");
          ext = "pdf";
          URL.revokeObjectURL(url);
        }
        await saveAs(fileBlob, `${filename}.${ext}`);
        ElMessage.success("导出成功");
      },
      text: "导出",
      icon: "download",
    },
  ],
];

onUnmounted(
  listener(document.documentElement, "keydown", (ev) => {
    if (!isUpload && ev.ctrlKey && ev.key.toUpperCase() === "S") {
      saveHandler();
    }
  })
);

let isUpload = false;
const saveHandler = async () => {
  isUpload = true;
  const [_, fileBlob] = await getCoverImage("image/jpeg");
  const url = await window.platform.uploadResourse(
    new File([fileBlob], `tabulation-list-cover.png`)
  );
  tabulationId.value = await window.platform.saveTabulationData(tabulationId.value, {
    ...tabulationId.value,
    listCover: url,
    store: draw!.getData(),
    viewport: draw!.viewer.transform.m,
    paperKey: tabulationData.value.paperKey,
    isAutoGen: tabulationData.value.isAutoGen && !draw.history.hasUndo.value,
  });
  isUpload = false;
};
</script>
