<template>
  <div ref="watermarkContainer" class="watermark-container">
    <canvas ref="watermarkCanvas" class="watermark-canvas"></canvas>
  </div>
</template>

<script>
  export default {
    name: 'Watermark',
    props: {
      text: {
        type: String,
        default: '',
      },
      fontSize: {
        type: Number,
        default: 16,
      },
      color: {
        type: String,
        default: 'rgba(219, 219, 219)',
      },
      angle: {
        type: Number,
        default: -25,
      },
    },
    data() {
      return {
        isInit: false,
      }
    },
    watch: {
      text: {
        handler() {
          this.drawWatermark()
        },
        immediate: true,
      },
    },
    mounted() {
      this.initWatermark()
      window.addEventListener('resize', this.handleResize)
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.handleResize)
    },
    methods: {
      initWatermark() {
        this.isInit = true
        this.drawWatermark()
      },
      drawWatermark() {
        if (!this.isInit || !this.text) return

        const canvas = this.$refs.watermarkCanvas
        const ctx = canvas.getContext('2d')
        const container = this.$refs.watermarkContainer

        // 设置canvas大小与容器一致
        canvas.width = container.offsetWidth || window.innerWidth
        canvas.height = container.offsetHeight || window.innerHeight

        // 清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height)

        // 设置水印样式
        ctx.font = `${this.fontSize}px Arial`
        ctx.fillStyle = this.color
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'
        ctx.globalAlpha = 0.8 // 增加全局透明度
        // 计算水印间距和布局 - 调整为5*5分布
        const textWidth = ctx.measureText(this.text).width
        // 计算5*5分布需要的间距，进一步减小垂直间距
        const gapX = canvas.width / 5
        const gapY = canvas.height / 5

        // 调整起始位置，确保边缘水印完整显示
        const startX = textWidth * 2
        const startY = textWidth * 1.2

        // 绘制重复的水印，实现5*5分布
        for (let x = startX; x < canvas.width; x += gapX) {
          for (let y = startY; y < canvas.height; y += gapY) {
            ctx.save()
            ctx.translate(x, y)
            ctx.rotate((Math.PI / 180) * this.angle)
            ctx.fillText(this.text, 0, 0)
            ctx.restore()
          }
        }
      },
      handleResize() {
        this.$nextTick(() => {
          this.drawWatermark()
        })
      },
    },
  }
</script>

<style scoped>
  .watermark-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 9998;
  }

  .watermark-canvas {
    width: 100%;
    height: 100%;
  }
</style>
