<template>
  <div class="watermark-container" ref="parentRef">
    <slot></slot>
  </div>
</template>

<script>
import useWatermarkBg from './useWatermarkBg.js';
let ob;
let div;
export default {
  name: 'fireflyWaterMark',
  props: {
    text: {  //水印文案
      type: String,
      require: true,
      default: '萤火平台'
    },
    lineFeedText: {  //换行水印文本
      type: String,
      default: null
    },
    fontSize: {  //水印字体大小
      type: Number,
      default: 14
    },
    rotate: {  //水印文案旋转角度
      type: Number,
      default: -20
    }, 
    hide:{  //是否隐藏水印
      type:Boolean,
      default:false,
    },
    gap: {   //文案原基础宽度增加宽度
      type: Number,
      default: 20
    }
  },
  watch:{
    text: {
      handler(newVal) {
        this.waterMark();
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.waterMark();
    ob = new MutationObserver(records => {
      for (const record of records) {
        //删除水印
        for (const dom of record.removedNodes) {
          if (dom === div) {
            //删除了dom节点
            console.log('删除水印节点');
            this.waterMark();
          }
        }
        //修改
        if (record.target === div) {
          console.log('修改水印节点');
          this.waterMark();
        }
      }
    });
    const parentRef = this.$refs.parentRef;
    ob.observe(parentRef, {
      childList: true,
      attributes: true,
      subtree: true 
    });
  },
  destroyed() {
    ob && ob.disconnect(); //取消监听
    div = null;
  },

  methods: {
    waterMark() {
      console.log(this.$refs, 'this.$refs');
      const parentRef = this.$refs.parentRef;
      if (!parentRef) {
        return;
      }
      if (div) {
        div.remove();
      }
      const bg = useWatermarkBg(this._props);
      const { base64, styleSize } = bg.value;
      div = document.createElement('div');
      div.style.backgroundImage = `url(${base64})`;
      div.style.backgroundSize = `${styleSize}px ${styleSize}px`;
      div.style.backgroundRepeat = 'repeat';
      div.style.zIndex = 99999;
      div.style.height = '100%';
      div.style.width = '100%';
      // div.style.position = 'fixed';
      div.style.position = 'absolute';
      div.style.top = '0px';
      div.style.left = '0px';
      div.style.inset = 0;
      div.style.pointerEvents = 'none';
      console.log('是否隐藏',this.hide)
      div.style.display = this.hide?'none':'block';
      parentRef.appendChild(div);
    }
  }
};
</script>

<style lang="scss" scoped>
@import '../../../css/fireflyWaterMark.scss';
</style>