<template>
  <div class="mark-body-container" ref="container">
    <div :style="{ width: answerPaperScale }">
      <template v-for="(item, index) in imageWithStyles" :key="index">
        <img :src="item.url" />
      </template>
      <!-- style="border: 1px solid black; background: black" -->
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, ref, watchEffect } from "vue";
import { store } from "./store";
import filters from "@/filters";

interface ImageStyle {
  width: number; // or string?
}
export default defineComponent({
  name: "MarkBody",
  setup() {
    const container = ref(null);
    const imageWithStyles: Array<any> = reactive([]);
    watchEffect(async () => {
      if (store.currentTask?.sliceConfig) {
        async function loadImage(url: string): Promise<HTMLImageElement> {
          return new Promise((resolve, reject) => {
            const image = new Image();
            image.setAttribute("crossorigin", "anonymous");
            image.src = url;
            image.onload = () => resolve(image);
            image.onerror = reject;
          });
        }
        for (const url of store.currentTask.sliceUrls) {
          await loadImage(filters.toCompleteUrl(url));
        }
        let zIndex = 500;
        for (const sliceConfig of store.currentTask.sliceConfig) {
          const url = filters.toCompleteUrl(
            store.currentTask.sliceUrls[sliceConfig.i - 1]
          );
          const image = await loadImage(url);

          const div: HTMLDivElement = container.value;
          const maxSliceWidth = Math.max(
            ...store.currentTask.sliceConfig.map((v) => v.w)
          );

          const canvas = document.createElement("canvas");
          canvas.width = Math.max(sliceConfig.w, maxSliceWidth);
          canvas.height = sliceConfig.h;
          const ctx = canvas.getContext("2d");
          ctx?.drawImage(
            image,
            sliceConfig.x,
            sliceConfig.y,
            sliceConfig.w,
            sliceConfig.h,
            0,
            0,
            sliceConfig.w,
            sliceConfig.h
          );
          // console.log(image, canvas.height, sliceConfig, ctx);
          // console.log(canvas.toDataURL());
          imageWithStyles.push({
            url: canvas.toDataURL(),
          });
        }
      }
    });

    const answerPaperScale = computed(() => {
      const scale = store.setting.uiSetting["answer.paper.scale"] || 1;
      return scale * 100 + "%";
    });
    return { container, store, imageWithStyles, answerPaperScale };
  },
});
</script>

<style scoped>
.mark-body-container {
  height: calc(100vh - 21px);
  overflow: scroll;
}
.mark-body-container img {
  width: 100%;
}
</style>
