<template>
  <div class="df-layout">
    <Header
      class="df-header"
      :type="props.type"
      @back-page="router.back"
      @back="board.back()"
      @forward="board.forward()"
      @view-init="board.viewInit()"
      @save="saveHandler"
      @export="exportHandler"
      :back-disabled="state.backDisabled"
      :forward-disabled="state.forwardDisabled"
      v-if="props && board"
    />

    <div class="df-layout-child">
      <Eshape v-model:shape="state.selectShape" v-if="state.selectShape" />
      <div class="df-sider">
        <Slider
          :type="props.type"
          v-model:add-shape="state.addShape"
          @track-image="trackImage"
          @selectImage="setBackImage"
          v-if="props"
        />
      </div>
      <div class="df-content">
        <div class="df-board">
          <canvas ref="dom" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import Header from "./header.vue";
import Slider from "./slider.vue";
import Eshape from "./eshape.vue";
import { computed, nextTick, ref } from "vue";
import { RouteName, router } from "@/router";
import { useBoard, title } from "./board/useBoard";
import { selectFuseImage, selectMapImage } from "@/view/case/quisk";
import { CaseTagging } from "@/store/caseTagging";
import saveAs from "@/util/file-serve";
import { BoardTypeDesc } from "@/constant/caseFile";
import {
  BoardType,
  SaveCaseFileImageInfo,
  TitleShapeData,
  saveCaseFileImageInfo,
} from "@/store/caseFile";

const dom = ref<HTMLCanvasElement>();
const props = computed(() => {
  const route = router.currentRoute.value;
  if (route.name !== RouteName.drawCaseFile || !dom.value) {
    return null;
  } else {
    const params = route.params;
    const fileId = Number(params.id);
    return {
      caseId: Number(params.caseId),
      inAdd: fileId === -1,
      fileId,
      type: params.type.toString() as BoardType,
      dom: dom.value!,
    };
  }
});

const setBackImage = (blob: Blob) => {
  board.value!.setImage(URL.createObjectURL(blob));
};

const trackImage = async () => {
  const data =
    props.value!.type === BoardType.scene
      ? await selectFuseImage(props.value!)
      : await selectMapImage({});

  if (data?.blob) {
    setBackImage(data.blob);
    if ("taggings" in data) {
      const tags = data.taggings as CaseTagging[];
      const table = await board.value!.calcTableShape([
        ["序号", "标注"],
        ...tags.map((tag, index) => [`序号${index + 1}`, tag.tagTitle]),
      ]);
      board.value!.setDefaultTable(null, table.content);
    }
  }
};

const { board, state } = useBoard(props);

// 获取通用数据
const getStore = async () => {
  const store = await board.value!.getStore();
  const titleShape = store.shapes.find(
    (shape: any) => shape.type === title
  ) as TitleShapeData;
  return { store, titleShape };
};

// 保存数据
const saveHandler = async () => {
  const { store, titleShape } = await getStore();
  const args = props.value!;

  const blob = await board.value!.export();
  const body: SaveCaseFileImageInfo = {
    caseId: args.caseId,
    imgType: args.type,
    file: new File([blob], `${args.type}_${args.fileId}.png`),
    filesTitle: titleShape?.text || `${args.caseId}_${BoardTypeDesc[args.type]}`,
    content: store,
  };

  args.inAdd || (body.filesId = props.value!.fileId);

  const data = await saveCaseFileImageInfo(body);
  if (args.inAdd) {
    router.replace({
      name: RouteName.drawCaseFile,
      params: { caseId: args.caseId, type: args.type, id: data.filesId },
    });
  }

  await nextTick();
  setTimeout(() => {
    location.reload();
  }, 100);
};

// 导出图片
const exportHandler = async () => {
  const { titleShape } = await getStore();
  const blob = await board.value!.export();
  saveAs(blob, `${titleShape.text}.png`);
};
</script>

<style lang="scss" scoped>
.df-layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f0f2f5;
}

.df-header {
  flex: none;
}

.df-layout-child {
  width: 100%;
  height: calc(100% - 5.4rem);
  display: flex;
  position: relative;
}

.df-sider {
  flex: 0 0 340px;
  overflow-y: auto;
  box-sizing: border-box;
  background: #fff;
}

.df-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.df-board {
  border: 1px solid #000;
  outline: 10px solid #fff;
  width: 940px;
  height: 670px;
  box-sizing: border-box;
  canvas {
    background: #fff;
    width: 100%;
    height: 100%;
  }
}
</style>
