/**
 * 创建水印
 * @param text 水印文本
 */
export function createWatermark(text: string | string[] = '内部资料') {
  // 检查是否在浏览器环境
  if (typeof document === 'undefined') {
    console.warn('Watermark: 非浏览器环境，无法创建水印');
    return;
  }

  console.log('Watermark: 开始创建水印', text);

  try {
    // 创建Canvas生成水印图片
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    
    if (!ctx) {
      throw new Error('无法获取Canvas上下文');
    }

    // 设置Canvas尺寸
    canvas.width = 300;
    canvas.height = 200;

    // 设置样式
    ctx.font = 'normal 16px Arial, sans-serif';
    ctx.fillStyle = 'rgba(0, 0, 0, 0.06)';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';

    // 旋转画布
    ctx.translate(150, 100);
    ctx.rotate(-25 * Math.PI / 180);
    ctx.translate(-150, -100);

    // 绘制文本
    const texts = Array.isArray(text) ? text : [text];
    const lineHeight = 24;
    const startY = (200 - (texts.length - 1) * lineHeight) / 2;

    texts.forEach((textItem, index) => {
      ctx.fillText(textItem, 150, startY + index * lineHeight);
    });

    // 转换为DataURL
    const dataURL = canvas.toDataURL('image/png');

    // 创建水印元素
    const watermark = document.createElement('div');
    watermark.style.position = 'fixed';
    watermark.style.top = '0';
    watermark.style.left = '0';
    watermark.style.width = '100%';
    watermark.style.height = '100%';
    watermark.style.backgroundImage = `url(${dataURL})`;
    watermark.style.backgroundRepeat = 'repeat';
    watermark.style.backgroundSize = '400px 300px';
    watermark.style.pointerEvents = 'none';
    watermark.style.zIndex = '9999';
    watermark.style.opacity = '0.8';

    // 添加到body
    document.body.appendChild(watermark);

    console.log('Watermark: 水印创建成功');

    // 返回销毁方法
    return () => {
      if (watermark.parentNode) {
        watermark.parentNode.removeChild(watermark);
        console.log('Watermark: 水印已销毁');
      }
    };

  } catch (error) {
    console.error('Watermark: 创建水印失败', error);
  }
}