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;

/**
 * 徕卡风格水印模板构建器
 * 对应 LeicaWatermarkOperator
 *
 * 布局说明（百分比基于1920x1080量化，精度0.5%）：
 * - 画布大小 = 原图大小（不扩展）
 * - 原图收缩放在画布上半部分，底部留出空间
 * - 底部白色区域左侧：帧途 Logo + "帧途" 文字
 * - 底部白色区域右侧：二维码（含头像）+ 景区名 + 日期时间
 */
@Component
public class LeicaWatermarkTemplateBuilder extends AbstractWatermarkTemplateBuilder {

    public static final String STYLE = "leica";

    // 百分比常量配置（基于1920x1080量化，精度0.5%）
    /** 底部额外区域占高度百分比 */
    private static final double EXTRA_BOTTOM_PERCENT = 0.13;         // 13%
    /** Logo大小占高度百分比 */
    private static final double LOGO_SIZE_PERCENT = 0.045;           // 4.5%
    /** Logo额外边距占高度百分比 */
    private static final double LOGO_EXTRA_BORDER_PERCENT = 0.02;    // 2%
    /** Logo字体大小占高度百分比 */
    private static final double LOGO_FONT_SIZE_PERCENT = 0.035;      // 3.5%
    /** 二维码大小占高度百分比 */
    private static final double QRCODE_SIZE_PERCENT = 0.11;          // 11%
    /** 二维码X偏移占宽度百分比 */
    private static final double QRCODE_OFFSET_X_PERCENT = 0.005;     // 0.5%
    /** 二维码Y偏移占高度百分比 */
    private static final double QRCODE_OFFSET_Y_PERCENT = 0.02;      // 2%
    /** 左右边距占宽度百分比 */
    private static final double OFFSET_X_PERCENT = 0.04;             // 4%
    /** 上下边距占高度百分比 */
    private static final double OFFSET_Y_PERCENT = 0.03;             // 3%
    /** 景区名字体大小占高度百分比 */
    private static final double SCENIC_FONT_SIZE_PERCENT = 0.03;     // 3%
    /** 日期时间字体大小占高度百分比 */
    private static final double DATETIME_FONT_SIZE_PERCENT = 0.025;  // 2.5%

    private static final String LOGO_TEXT_COLOR = "#333333";
    private static final String SCENIC_COLOR = "#333333";
    private static final String DATETIME_COLOR = "#999999";

    /**
     * Logo 图片 URL（需要预先上传到 OSS）
     */
    private static final String LOGO_URL = "https://oss.zhentuai.com/zt/zt-logo.png";

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

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

        // 根据百分比计算实际像素值
        int extraBottom = (int) (imageHeight * EXTRA_BOTTOM_PERCENT);
        int logoSize = (int) (imageHeight * LOGO_SIZE_PERCENT);
        int logoExtraBorder = (int) (imageHeight * LOGO_EXTRA_BORDER_PERCENT);
        int logoFontSize = (int) (imageHeight * LOGO_FONT_SIZE_PERCENT);
        int qrcodeSize = (int) (imageHeight * QRCODE_SIZE_PERCENT);
        int qrcodeOffsetX = (int) (imageWidth * QRCODE_OFFSET_X_PERCENT);
        int qrcodeOffsetY = (int) (imageHeight * QRCODE_OFFSET_Y_PERCENT);
        int offsetX = (int) (imageWidth * OFFSET_X_PERCENT);
        int offsetY = (int) (imageHeight * OFFSET_Y_PERCENT);
        int scenicFontSize = (int) (imageHeight * SCENIC_FONT_SIZE_PERCENT);
        int datetimeFontSize = (int) (imageHeight * DATETIME_FONT_SIZE_PERCENT);

        // 画布大小 = 原图大小（不扩展）
        int canvasWidth = imageWidth;
        int canvasHeight = imageHeight;

        // 原图收缩后的区域高度
        int shrunkImageHeight = imageHeight - extraBottom;
        // 底部区域起始 Y 坐标
        int bottomAreaY = shrunkImageHeight;

        // 创建模板（白色背景）
        PuzzleTemplateEntity template = createTemplateWithColor(
                "watermark_leica_" + System.currentTimeMillis(),
                canvasWidth,
                canvasHeight,
                "#FFFFFF"
        );

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

        // 1. 原图元素（收缩放在画布上半部分）
        PuzzleElementEntity originalImageElement = createImageElement(
                "originalImage", "原图",
                0, 0,
                imageWidth, shrunkImageHeight, 1,
                FIT_MODE_COVER, null, null
        );
        elements.add(originalImageElement);
        dynamicData.put("originalImage", request.getOriginalImageUrl());

        // 2. Logo 元素（底部左侧）
        int logoY = bottomAreaY + offsetY + logoExtraBorder;
        PuzzleElementEntity logoElement = createImageElement(
                "logo", "Logo",
                offsetX, logoY - (int)(logoSize * 0.24),
                logoSize, logoSize, 10,
                FIT_MODE_CONTAIN, null, null
        );
        elements.add(logoElement);
        dynamicData.put("logo", LOGO_URL);

        // 3. "帧途" 文字（Logo 右边）
        int logoTextX = offsetX + logoSize + (int)(imageWidth * 0.005);
        int logoTextY = bottomAreaY + offsetY + logoExtraBorder;
        PuzzleElementEntity logoTextElement = createTextElement(
                "logoText", "帧途文字",
                logoTextX, logoTextY,
                (int)(imageWidth * 0.05), logoSize, 10,
                "PingFang SC", logoFontSize, LOGO_TEXT_COLOR,
                "NORMAL", TEXT_ALIGN_LEFT
        );
        elements.add(logoTextElement);
        dynamicData.put("logoText", "帧途");

        // 4. 计算右侧区域位置
        // 估算文字宽度（使用景区名和日期的较大者）
        int estimatedTextWidth = Math.max(
                (request.getScenicLine() != null ? request.getScenicLine().length() : 0) * scenicFontSize / 2,
                (request.getDatetimeLine() != null ? request.getDatetimeLine().length() : 0) * datetimeFontSize / 2
        );

        int qrcodeX = canvasWidth - offsetX - qrcodeSize - qrcodeOffsetX - estimatedTextWidth;
        int qrcodeY = bottomAreaY + offsetY - qrcodeOffsetY;

        // 5. 二维码元素
        PuzzleElementEntity qrcodeElement = createImageElement(
                "qrcode", "二维码",
                qrcodeX, qrcodeY,
                qrcodeSize, qrcodeSize, 10,
                FIT_MODE_CONTAIN, null, null
        );
        elements.add(qrcodeElement);
        dynamicData.put("qrcode", request.getQrcodeUrl());

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

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

        // 7. 计算文字位置（与二维码垂直居中）
        int qrcodeCenter = qrcodeY + qrcodeSize / 2;
        int totalTextHeight = scenicFontSize + datetimeFontSize + (int)(imageHeight * 0.01);
        int textY = qrcodeCenter - totalTextHeight / 2;
        int textX = canvasWidth - offsetX - estimatedTextWidth;

        // 8. 景区名文字
        PuzzleElementEntity scenicTextElement = createTextElement(
                "scenicLine", "景区名",
                textX, textY,
                estimatedTextWidth, scenicFontSize + (int)(imageHeight * 0.01), 30,
                "PingFang SC", scenicFontSize, SCENIC_COLOR,
                "NORMAL", TEXT_ALIGN_LEFT
        );
        elements.add(scenicTextElement);
        dynamicData.put("scenicLine", request.getScenicLine() != null ? request.getScenicLine() : "");

        // 9. 日期时间文字
        int datetimeY = textY + scenicFontSize + (int)(imageHeight * 0.005);
        PuzzleElementEntity datetimeTextElement = createTextElement(
                "datetimeLine", "日期时间",
                textX, datetimeY,
                estimatedTextWidth, datetimeFontSize + (int)(imageHeight * 0.01), 30,
                "PingFang SC", datetimeFontSize, DATETIME_COLOR,
                "NORMAL", TEXT_ALIGN_LEFT
        );
        elements.add(datetimeTextElement);
        dynamicData.put("datetimeLine", request.getDatetimeLine() != null ? request.getDatetimeLine() : "");

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