<template>
  <Header :action-groups="actions" title="图纸" :draw="draw">
    <template #saves>
      <el-button type="primary" @click="saveHandler">保存</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 { saveTabulationData } from "../../req.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 } from "vue";
import { tabulationData } from "../../store.ts";

const draw = useDraw();

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 draw.enterTemp(async () => {
          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);
          return [rect, fileBlob] as const;
        });

        const filename = "canvas";
        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 url = URL.createObjectURL(fileBlob);
          const img = await getResourceImage(url);
          const pdf = new jsPDF(rect.width > rect.height ? "l" : "p", "px", [
            rect.width,
            rect.height,
          ]);
          pdf.addImage(img, format, 0, 0, rect.width, rect.height);
          fileBlob = pdf.output("blob");
          ext = "pdf";
          URL.revokeObjectURL(url);
        }
        await saveAs(fileBlob, `${filename}.${ext}`);
        ElMessage.success("导出成功");
      },
      text: "导出",
      icon: "download",
    },
  ],
];

const saveHandler = () => {
  saveTabulationData({
    store: draw!.getData(),
    viewport: draw!.viewer.transform.m,
    paperKey: tabulationData.value.paperKey,
  });
};
</script>
