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

<script setup lang="ts">
import { useUserStore } from '@/store/modules/user';
import { onUnmounted, onMounted, ref } from 'vue';

const userStore = useUserStore();
const watermarkRef = ref<HTMLDivElement>();

const createWatermark = () => {
  const canvas = document.createElement('canvas');
  canvas.width = 300;
  canvas.height = 205;
  const ctx = canvas.getContext('2d');

  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hour = String(now.getHours()).padStart(2, '0');
  const minute = String(now.getMinutes()).padStart(2, '0');
  const second = String(now.getSeconds()).padStart(2, '0');
  const date = `${year}-${month}-${day} ${hour}:${minute}:${second}`;

  const username = userStore.name || '未知用户';
  const text = `${username} | ${date}`;

  ctx.rotate((-20 * Math.PI) / 180);
  ctx.font = '14px MicroSoft YaHei';
  ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText(text, canvas.width / 2, canvas.height / 2);
  return canvas.toDataURL();
}

const updateWatermark = () => {
    if(watermarkRef.value){
        const watermarkUrl = createWatermark();
        watermarkRef.value.style.backgroundImage = `url(${watermarkUrl})`;
    }
}

let timer: number;

onMounted(() => {
    updateWatermark();
    timer = window.setInterval(updateWatermark,1000);
});

onUnmounted(() => {
    clearInterval(timer);
});
</script>

<style scoped>
.watermark-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background-repeat: repeat;
  background-attachment: fixed;
  pointer-events: none; /*鼠标穿透*/
}
</style>
