<!--  -->
<template>
     <div class="img-box-con">
       <!-- <img :src="dataUrl" class="img-box"/> -->
        <div v-if="spinning" class="loading-spinner"></div>
        <a-empty v-if="showDescription" :description="description" style="position: absolute;"/>
       <canvas id="myCanvas" class="my-Canvas" :width="canvasSize.width" :height="canvasSize.height"></canvas>
     </div>
</template>

<script>
import { showText } from 'pdf-lib';
import {addWatermark} from './../../utils/addWatermark'
import * as IS from './../../utils/is'
import imgUse from './utils/ImageUse'

export default {
  // import引入的组件需要注入到对象中才能使用
  name: 'imgBox',
  components: {},
  props: {
    url: { type: String },
    isEnlarge:{type:Boolean},
    setEvent: { type: Function },
    isShowWatermark:{type:Boolean, default:true}, // 是否显示水印 默认：true
  },
  data() {
    // 这里存放数据
    return {
      showDescription:false,
      description:'',
      spinning:true,
      dataUrl: "",
      canvasSize:{
        width:800,
        height:600
      }
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    isEnlarge:{
      handler(val) {
        console.log('imgBox 1=====>',val);
        this.spinning = val
        this.getSize(4)
        // if(val == false){
        //   const regex = /^blob:[^ ]+$/;
        //   if (regex.test(this.dataUrl)) {
        //     URL.revokeObjectURL(this.dataUrl);
        //     this.dataUrl = ''
        //   }
        // }
      },
      deep: true,
      immediate: true,
    },
    url: {
      handler(val_) {
        const val = val_
        const {$watermarkConfig} = this
        // URL.revokeObjectURL(this.dataUrl);
        // console.log('imgBox 0=====>',val);
        if (IS.isString(val)) {
          this.spinning = true
         this.isShowWatermark === true && (addWatermark(val,this,$watermarkConfig).then((res) => {
            this.dataUrl = res.url;
            this.$nextTick(()=>{
              this.getSize(2)
            })
          })) || (this.dataUrl = val)
        }
        if(IS.isObject(val)){
          this.spinning = true
          this.isShowWatermark === true && (addWatermark(val.url,this,$watermarkConfig).then((res) => {
                this.dataUrl = res.url;
                this.$nextTick(()=>{
                  this.getSize(3)
                })
            })) || (this.dataUrl = val.url)
        }
        if(this.isShowWatermark === false){
          this.spinning = true
          this.$nextTick(()=>{
            this.getSize(5)
          })
        }
      },
      deep: true,
      immediate: true,
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
   
    window.addEventListener('resize', ()=>{
      this.$nextTick(()=>{
        this.getSize(111)
      })
    });
    const resizeObserver = new ResizeObserver(()=>{
      this.$nextTick(()=>{
        this.getSize(11)
      })
    });
    // 开始监听
    resizeObserver.observe(document.getElementById('p-data-con-id'));

    // 使用 MutationObserver 监听父容器的 DOM 变化
    const mutationObserver = new MutationObserver(()=>{
      this.$nextTick(()=>{
        this.getSize(1111)
      })
    });

    // 开始监听
    mutationObserver.observe(document.getElementById('p-data-con-id'), {
        attributes: true, // 监听属性变化（如样式变化）
        childList: true, // 监听子元素变化
        subtree: true // 监听子树变化
    });


    this.getSize(1)
  },
  // 方法集合 imgUse
  methods: {
    getSize(type){
      // let parentElement = document.getElementById('p-data-con-id'); // 获取父容器
      
      // // if(IS.isNullOrUnDef(parentElement) || IS.isEmpty(parentElement)){
      // //   setTimeout(()=>{
      // //     console.log('this.getSize=====>', type,1);
      // //     this.setCanvasSize()
      // //   },1000)
      // // } else {
      // //   console.log('this.getSize=====>', type,2);
      // //   this.setCanvasSize()
      // // }
      this.setCanvasSize()
    },
    setCanvasSize(){
      // console.log('this.setCanvasSize=====>', this.dataUrl);
      const tempArr = document.getElementsByClassName('p-data-con')
      for (let parentElement of tempArr) {
        const width_ = parentElement.offsetWidth; // 或使用其他方法获取宽度
        const height_ = parentElement.offsetHeight; // 或使用其他方法获取高度
        const rect = parentElement.getBoundingClientRect(); // 获取尺寸信息
        let width = rect.width; // 父容器的宽度
        let height = rect.height; // 父容器的高度
        if(width<=100 || height<=100){
          width = width_
          height = height_
        }
        if(width>100 && height>100){
          this.canvasSize.width = width;
          this.canvasSize.height = height;
          const canvas = parentElement.querySelector("#myCanvas");
          this.setImg(canvas,parentElement)
          break;
        }
      }
    },
    setImg(canvas, parentElement){
      imgUse(canvas, this.dataUrl,(err)=>{
        console.log('this.spinning====>',this.spinning)
        this.spinning = false
        if(err&& err){
          this.description = err
          this.showDescription = true
        }else{
          this.description = ''
          this.showDescription = false
        }
        
      })
    },
  },
  }
</script>
<style lang='less' scoped>
.img-box-con{
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto;
  position: relative;
}

.loading-spinner {
  position: absolute;
  width: 50px;
  height: 50px;
  border: 5px solid #ccc;
  border-top-color: #007bff; /* 上边框颜色 */
  border-radius: 50%; /* 圆形 */
  animation: spin 1s linear infinite; /* 旋转动画 */
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>