<?php

namespace App\Http\Middleware;

use Closure;
use Dcat\Admin\Admin;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * 向页面输出 JavaScript 代码来动态添加水印
 */
class WatermarkMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (Admin::user()) {
            $username = Admin::user()->username;
            $nickname = Admin::user()->name;
            $script = "<script>
                var username = '{$username}';
                var nickname = '{$nickname}';

                // 创建水印元素的样式
                var watermarkStyle = 'position: fixed; transform: rotate(-30deg); opacity: 0.1; z-index: 1000; font-size: 1em; pointer-events: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background: transparent;';
                // 获取页面宽度和高度
                var pageWidth = document.documentElement.scrollWidth;
                var pageHeight = document.documentElement.scrollHeight;
                var spacing = 300; // 间距为 150px，可以根据需求调整
                // 创建水印元素并添加到页面中
                for (var x = -pageHeight; x < pageWidth; x += spacing) {
                    for (var y = -pageWidth; y < pageHeight; y += spacing) {
                        var watermark = document.createElement('div');
                        watermark.style.cssText = watermarkStyle + 'top: ' + y + 'px; left: ' + x + 'px;';
                        // 添加用户名和昵称
                        var usernameDiv = document.createElement('div');
                        usernameDiv.innerText = nickname;
                        var nicknameDiv = document.createElement('div');
                        nicknameDiv.innerText = username;
                        watermark.appendChild(usernameDiv);
                        watermark.appendChild(nicknameDiv);
                        document.body.appendChild(watermark);
                    }
                }
            </script>";

            // 将 JavaScript 代码添加到响应内容中
            $response = $next($request);
            $content = $response->getContent();
            $content = str_replace('</body>', $script.'</body>', $content);
            $response->setContent($content);

            return $response;
        }

        return $next($request);
    }
}
