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

  <div v-if="showComponent">
    <jsv-mask-clip-div
      :style="{
        top: (maskConfig.top * size.width) / imgInfo.width,
        left: (maskConfig.left * size.width) / imgInfo.width,
        width: (maskConfig.width * size.width) / imgInfo.width,
        height: (maskConfig.height * size.width) / imgInfo.width,
      }"
      :viewSrc="imgInfo.src"
      :maskSrc="maskConfig.src"
      :maskLeft="maskConfig.left / imgInfo.width"
      :maskTop="maskConfig.top / imgInfo.height"
      :maskWidth="maskConfig.width / imgInfo.width"
      :maskHeight="maskConfig.height / imgInfo.height"
    />
  </div>
</template>

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

//只显示一片的demo
const props = defineProps({
  configUrl: {
    //每一片的配置, 格式 { pieces: [{file: "", left: 0, top: 0, width: 0, height: 0}]}
    type: String,
  },
  pieceIndex: {
    type: Number,
  },
  size: {
    type: Object,
  },
  imgInfo: {
    type: Object,
  },
});
const showPreload = shallowRef(false);
const showComponent = shallowRef(false);

const preloadList = [];
let maskConfig = null;

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);
      if (data.pieces[props.pieceIndex]) {
        const url = baseUrl + data.pieces[props.pieceIndex].file;
        preloadList.push(buildPreloadInfo(url));
        maskConfig = {
          src: url,
          left: data.pieces[props.pieceIndex].left,
          top: data.pieces[props.pieceIndex].top,
          width: data.pieces[props.pieceIndex].width,
          height: data.pieces[props.pieceIndex].height,
        };
        showPreload.value = true;
      } else {
        console.error("pieceIndex out of range", data, props.pieceIndex);
      }
    })
    .catch((err) => {
      console.log("fetch mask config failed", err);
    });
}
prepareSrc();
</script>
