package com.ycwl.basic.image.watermark.edge;

import com.ycwl.basic.puzzle.entity.PuzzleElementEntity;
import com.ycwl.basic.puzzle.entity.PuzzleTemplateEntity;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 打印专用水印模板构建器
 * 对应 PrinterDefaultWatermarkOperator
 *
 * 布局说明：
 * - 白色背景 + 原图元素（COVER模式）
 * - 左下角：圆形二维码（带白色圆形背景）
 * - 二维码中央：圆形头像（可选）
 * - 右下角：景区名 + 日期时间 两行文字（白色，右对齐）
 * - 支持缩放和四边偏移
 */
@Component
public class PrinterDefaultWatermarkTemplateBuilder extends AbstractWatermarkTemplateBuilder {

    public static final String STYLE = "pDefault";

    // 常量配置（与 PrinterDefaultWatermarkOperator 保持一致）
    private static final int OFFSET_Y = 15;
    private static final int QRCODE_SIZE = 150;
    private static final double QRCODE_LEFT_MARGIN_RATIO = 0.05;
    private static final int QRCODE_OFFSET_Y = -35;
    private static final int SCENIC_FONT_SIZE = 42;
    private static final int DATETIME_FONT_SIZE = 42;
    private static final String FONT_COLOR = "#FFFFFF";
    private static final double TEXT_RIGHT_MARGIN_RATIO = 0.05;

    @Override
    public String getStyle() {
        return STYLE;
    }

    @Override
    public WatermarkTemplateResult build(WatermarkRequest request) {
        int imageWidth = request.getImageWidth();
        int imageHeight = request.getImageHeight();
        double scale = request.getScaleValue();

        // 应用缩放
        int scaledOffsetY = (int) (OFFSET_Y * scale);
        int scaledQrcodeSize = (int) (QRCODE_SIZE * scale);
        int scaledQrcodeOffsetY = (int) (QRCODE_OFFSET_Y * scale);
        int scaledScenicFontSize = (int) (SCENIC_FONT_SIZE * scale);
        int scaledDatetimeFontSize = (int) (DATETIME_FONT_SIZE * scale);

        // 获取偏移值
        int offsetLeft = (int) (request.getOffsetLeftValue() * scale);
        int offsetRight = (int) (request.getOffsetRightValue() * scale);
        int offsetBottom = (int) (request.getOffsetBottomValue() * scale);

        // 创建模板（白色背景，原图作为元素实现 COVER 模式）
        PuzzleTemplateEntity template = createTemplateWithColor(
                "watermark_printer_" + System.currentTimeMillis(),
                imageWidth,
                imageHeight,
                "#FFFFFF"
        );

        List<PuzzleElementEntity> elements = newElementList();
        Map<String, String> dynamicData = newDynamicData();

        // 0. 原图元素（z-index=1，最底层，COVER模式）
        PuzzleElementEntity originalImageElement = createImageElement(
                "originalImage", "原图",
                0, 0,
                imageWidth, imageHeight, 1,
                FIT_MODE_COVER, null, null
        );
        elements.add(originalImageElement);
        dynamicData.put("originalImage", request.getOriginalImageUrl());

        // 0.5 打印水印叠加层（z-index=5，全屏覆盖，在原图上方、文字/二维码下方）
        if (request.getPrintWatermarkUrl() != null && !request.getPrintWatermarkUrl().isEmpty()) {
            PuzzleElementEntity printWatermarkElement = createImageElement(
                    "printWatermark", "打印水印",
                    0, 0,
                    imageWidth, imageHeight, 5,
                    FIT_MODE_COVER, null, null
            );
            elements.add(printWatermarkElement);
            dynamicData.put("printWatermark", request.getPrintWatermarkUrl());
        }

        // 计算二维码位置
        int qrcodeWidth = scaledQrcodeSize;
        int qrcodeHeight = scaledQrcodeSize;
        int qrcodeX = (int) (imageWidth * QRCODE_LEFT_MARGIN_RATIO) + offsetLeft;
        int qrcodeY = imageHeight - scaledOffsetY - qrcodeHeight - offsetBottom;

        // 1. 二维码元素（圆形裁切）
        PuzzleElementEntity qrcodeElement = createCircleImageElement(
                "qrcode", "二维码",
                qrcodeX, qrcodeY + scaledQrcodeOffsetY,
                qrcodeHeight, 10
        );
        elements.add(qrcodeElement);
        dynamicData.put("qrcode", request.getQrcodeUrl());

        // 2. 头像元素（圆形，二维码中央，可选）
        if (request.getFaceUrl() != null && !request.getFaceUrl().isEmpty()) {
            int avatarDiameter = (int) (qrcodeHeight * 0.45);
            int avatarX = qrcodeX + (qrcodeWidth - avatarDiameter) / 2;
            int avatarY = qrcodeY + scaledQrcodeOffsetY + (qrcodeHeight - avatarDiameter) / 2;

            PuzzleElementEntity faceElement = createCircleImageElement(
                    "face", "头像",
                    avatarX, avatarY,
                    avatarDiameter, 20
            );
            elements.add(faceElement);
            dynamicData.put("face", request.getFaceUrl());
        }

        // 3. 计算文字位置（右对齐）
        int textRightX = imageWidth - (int) (imageWidth * TEXT_RIGHT_MARGIN_RATIO) - offsetRight;
        int textWidth = textRightX - qrcodeX - qrcodeWidth - 20;

        // 计算垂直居中
        int qrcodeTop = qrcodeY + scaledQrcodeOffsetY;
        int qrcodeBottom = qrcodeTop + qrcodeHeight;
        int qrcodeCenter = (qrcodeTop + qrcodeBottom) / 2;
        int totalTextHeight = scaledScenicFontSize + scaledDatetimeFontSize + 10;
        int textY = qrcodeCenter - totalTextHeight / 2;

        // 4. 景区名文字（右对齐）
        PuzzleElementEntity scenicTextElement = createTextElement(
                "scenicLine", "景区名",
                textRightX - textWidth, textY,
                textWidth, scaledScenicFontSize + 10, 30,
                "PingFang SC", scaledScenicFontSize, FONT_COLOR,
                "BOLD", TEXT_ALIGN_RIGHT
        );
        elements.add(scenicTextElement);
        dynamicData.put("scenicLine", request.getScenicLine() != null ? request.getScenicLine() : "");

        // 5. 日期时间文字（右对齐）
        int datetimeY = textY + scaledScenicFontSize + 5;

        PuzzleElementEntity datetimeTextElement = createTextElement(
                "datetimeLine", "日期时间",
                textRightX - textWidth, datetimeY,
                textWidth, scaledDatetimeFontSize + 10, 30,
                "PingFang SC", scaledDatetimeFontSize, FONT_COLOR,
                "BOLD", TEXT_ALIGN_RIGHT
        );
        elements.add(datetimeTextElement);
        dynamicData.put("datetimeLine", request.getDatetimeLine() != null ? request.getDatetimeLine() : "");

        return createResult(template, elements, dynamicData);
    }
}
