<template>
  <JsvPreload
    v-if="showPreload"
    :preloadList="preloadList"
    :onPreloadDone="preloadDone"
  ></JsvPreload>

  <div v-if="showComponent">
    <div v-for="(item, index) in maskConfig">
      <jsv-mask-clip-div
        :key="index"
        v-if="displaySetting[index] == 1"
        :style="{
          top: (item.top * size.width) / imgInfo.width,
          left: (item.left * size.width) / imgInfo.width,
          width: (item.width * size.width) / imgInfo.width,
          height: (item.height * size.width) / imgInfo.width,
        }"
        :viewSrc="imgInfo.src"
        :maskSrc="item.src"
        :maskLeft="item.left / imgInfo.width"
        :maskTop="item.top / imgInfo.height"
        :maskWidth="item.width / imgInfo.width"
        :maskHeight="item.height / imgInfo.height"
      />
    </div>
  </div>
  <img
    :src="strokeSrc"
    :style="{
      width: size.width,
      height: size.height,
    }"
  />
</template>

<script setup>
import { shallowRef } from "vue";
import { JsvMaskClipDiv, JsvPreload, buildPreloadInfo } from "jsview";

const props = defineProps({
  //每一片的配置, 格式 { pieces: [{file: "", left: 0, top: 0, width: 0, height: 0}]}
  //注意, mask的图片资源和json在同目录下
  configUrl: {
    type: String,
  },
  size: {
    type: Object,
  },
  //每一片的显示设置, 0表示不显示, 1表示显示
  displaySetting: {
    type: Array,
  },
  //图片信息, 格式 { src: "", width: 0, height: 0 }
  imgInfo: {
    type: Object,
  },
  strokeSrc: {
    type: String,
  },
});
const showPreload = shallowRef(false);
const showComponent = shallowRef(false);

const preloadList = [];
const maskConfig = [];

function preloadDone() {
  showComponent.value = true;
}

function prepareSrc() {
  preloadList.push(buildPreloadInfo(props.imgInfo.src));
  if (props.strokeSrc) {
    preloadList.push(buildPreloadInfo(props.strokeSrc));
  }
  fetch(props.configUrl)
    .then((res) => res.json())
    .then((data) => {
      const lastSlashIndex = props.configUrl.lastIndexOf("/");
      const baseUrl = props.configUrl.substring(0, lastSlashIndex + 1);
      for (let i = 0; i < data.pieces.length; i++) {
        const url = baseUrl + data.pieces[i].file;
        preloadList.push(buildPreloadInfo(url));
        maskConfig.push({
          src: url,
          left: data.pieces[i].left,
          top: data.pieces[i].top,
          width: data.pieces[i].width,
          height: data.pieces[i].height,
        });
      }
      showPreload.value = true;
    })
    .catch((err) => {
      console.log("fetch mask config failed", err);
    });
}
prepareSrc();
</script>
