<template>
  <div class="global-watermark"></div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  name: "GlobalWatermark",
  props: {
    fontSize: {
      type: Number,
      default: 16,
    },
    opacity: {
      type: Number,
      default: 0.1,
    },
    rotate: {
      type: Number,
      default: -15,
    },
  },
  computed: {
    watermarkStyle() {
      return {
        position: "fixed",
        top: "0",
        left: "0",
        width: "100%",
        height: "100%",
        "pointer-events": "none",
        "z-index": "9999",
        "background-image": this.generateWatermark(),
      };
    },
    ...mapGetters(["userInfo"]),
  },
  watch: {
    userInfo(newVal, oldVal) {
      this.updateStyle();
    },
  },
  methods: {
    generateWatermark() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const date = now.getDate();
      const svg = `
                <svg xmlns="http://www.w3.org/2000/svg" width="200" height="150">
                    <text x="100" y="80"
                        font-size="${this.fontSize}"
                        text-anchor="midle"
                        fill="rgba(0, 0, 0, ${this.opacity})"
                        transform="rotate(${this.rotate} 100 100)">
                            <tspan x="100" dy="0">${this.userInfo.userName || ''}</tspan>
                            <tspan x="100" dy="1.2em">${this.userInfo.nickName || ''}</tspan>
                            <tspan x="100" dy="1.2em">${year}-${month}-${date}</tspan>
                    </text>
                </svg>
            `;
      const base64 = btoa(unescape(encodeURIComponent(svg)));
      return `url("data:image/svg+xml;base64,${base64}")`;
    },
    updateStyle() {
      const oldStyle = document.querySelector(".watermark-style");

      if (oldStyle) {
        document.head.removeChild(oldStyle);
      }
      
      const style = document.createElement("style");
      style.className = "watermark-style"
      style.textContent = `
            .global-watermark {
                ${Object.entries(this.watermarkStyle)
                  .map(([key, value]) => `${key}: ${value};`)
                  .join(" ")}
            }
        `;
      document.head.appendChild(style);
    },
  },
  mounted() {
    this.updateStyle()
  },
};
</script>
