<template>
    <div class="canvas-container" ref="parentElement">
      <canvas
        ref="canvas"
        class="canvas-content"
        @click="handleCanvasClick"
        @drop="handleDrop"
        @dragover="handleDragOver"
      ></canvas>
    </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { CanvasPhotoEditor } from "@/view/case/photos/canvas-photo-editor.js";

const props = defineProps({
  // SVG图片的URL
  content: {
    type: String,
    required: true
  },
  photos: {
    type: Array,
    required: true
  },
  pageCount: {
    type: Number,
  }
}); 
// --- 响应式数据 ---
const canvas = ref(null);
const parentElement = ref(null);
const editor = ref(null);

// 监听属性变化并重新加载/处理SVG
watch(() => props.content, ()=>{
  if(editor.value && props.content){
        let content = typeof props.content === 'string'?JSON.parse(props.content):props.content
        console.log("newcontent", content);
        editor.value.pages = content.pages;
        editor.value.pageCount = props.pageCount;
        editor.value.indexingLineList = content.indexingLineList;
        editor.value.drawAllPages(props.photos);
        editor.value.resetPosition(); // 移除scrollToCenter，用resetPosition
  }
});
// --- 初始化 ---
onMounted(() => {
  if (canvas.value) {
    // 创建编辑器实例
    editor.value = new CanvasPhotoEditor(canvas.value, {
      pageWidth: 600,
      pageHeight: 840,
      canvasBgColor: "#efefef",
      pageBgColor: "#ffffff",
      photos: props.photos,
      scale: 0.5,
      show: true,
      updata: (value) => {
        // selectedPageItem.value = value.selectedPageItem;
        // selectedPageIndex.value = value.selectedPageIndex;
        // historylength.value = value.historylength;
        // currentIndex.value = value.currentIndex;
        console.log("updata", value);
      },
    });

    // 绑定容器（用于居中计算）
    editor.value.bindScrollWrapper(parentElement.value);
    console.log("updata", parentElement.value);
    if(props.content){
        let content = typeof props.content === 'string'?JSON.parse(props.content):props.content
        editor.value.pages = content.pages;
        editor.value.indexingLineList = content.indexingLineList;
        editor.value.drawAllPages(props.photos);  
    }
    // 初始化绘制
    editor.value.resetPosition(); // 移除scrollToCenter，用resetPosition

    // 同步初始数据
    // scale.value = editor.value.scale;
  }
});
const exportToPDF = async (paperType, name, fileType = 'pdf') => {

  if(fileType == 'pdf'){
    await editor.value.exportPagesToPDF(paperType, name);
  }else{
    await editor.value.exportPagesAsImages(paperType, name);
  }
}
defineExpose({
  exportToPDF
})
</script>

<style scoped>
.canvas-container {
  width: 100%;
  height: 100%;
}
/* 可以根据需要添加更多样式 */
</style>
