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

import com.ycwl.basic.annotation.IgnoreToken;
import com.ycwl.basic.image.watermark.edge.WatermarkEdgeTaskCreator;
import com.ycwl.basic.image.watermark.edge.WatermarkRequest;
import com.ycwl.basic.puzzle.edge.task.PuzzleEdgeRenderTaskService;
import com.ycwl.basic.utils.ApiResponse;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 水印边缘渲染测试控制器
 * 用于测试水印边缘渲染功能
 */
@Slf4j
@IgnoreToken
@RestController
@RequestMapping("/test/watermark/edge")
@RequiredArgsConstructor
public class WatermarkEdgeTestController {

    private final WatermarkEdgeTaskCreator watermarkEdgeTaskCreator;
    private final PuzzleEdgeRenderTaskService puzzleEdgeRenderTaskService;

    /**
     * 获取支持的水印风格列表
     */
    @GetMapping("/styles")
    public ApiResponse<List<String>> getSupportedStyles() {
        return ApiResponse.success(watermarkEdgeTaskCreator.getSupportedStyles());
    }

    /**
     * 创建水印渲染任务（异步）
     * 任务创建后由边缘端拉取执行
     */
    @PostMapping("/create")
    public ApiResponse<CreateTaskResponse> createTask(@RequestBody CreateTaskRequest req) {
        // 参数校验
        if (req.getStyle() == null || req.getStyle().isEmpty()) {
            return ApiResponse.fail("水印风格(style)不能为空");
        }
        if (!watermarkEdgeTaskCreator.isStyleSupported(req.getStyle())) {
            return ApiResponse.fail("不支持的水印风格: " + req.getStyle() +
                    "，支持的风格: " + watermarkEdgeTaskCreator.getSupportedStyles());
        }
        if (req.getOriginalImageUrl() == null || req.getOriginalImageUrl().isEmpty()) {
            return ApiResponse.fail("原图URL(originalImageUrl)不能为空");
        }
        if (req.getImageWidth() <= 0 || req.getImageHeight() <= 0) {
            return ApiResponse.fail("图片宽高必须大于0");
        }

        // 构建请求
        WatermarkRequest watermarkRequest = WatermarkRequest.builder()
                .originalImageUrl(req.getOriginalImageUrl())
                .imageWidth(req.getImageWidth())
                .imageHeight(req.getImageHeight())
                .qrcodeUrl(req.getQrcodeUrl())
                .faceUrl(req.getFaceUrl())
                .scenicLine(req.getScenicLine())
                .datetimeLine(req.getDatetimeLine())
                .offsetTop(req.getOffsetTop())
                .offsetBottom(req.getOffsetBottom())
                .offsetLeft(req.getOffsetLeft())
                .offsetRight(req.getOffsetRight())
                .scale(req.getScale())
                .outputFormat(req.getOutputFormat() != null ? req.getOutputFormat() : "JPEG")
                .outputQuality(req.getOutputQuality() != null ? req.getOutputQuality() : 75)
                .build();

        // 创建任务
        Long taskId = watermarkEdgeTaskCreator.createTask(
                req.getStyle(),
                watermarkRequest,
                req.getRecordId() != null ? req.getRecordId() : 0L,  // 测试用默认值
                req.getFaceId(),
                req.getWatermarkType() != null ? req.getWatermarkType() : "test"
        );

        CreateTaskResponse response = new CreateTaskResponse();
        response.setTaskId(taskId);
        response.setMessage("任务已创建，等待边缘端拉取执行");

        log.info("测试创建水印任务: style={}, taskId={}", req.getStyle(), taskId);
        return ApiResponse.success(response);
    }

    /**
     * 创建水印渲染任务并等待结果（同步）
     * 注意：此接口会阻塞直到任务完成或超时
     */
    @PostMapping("/createAndWait")
    public ApiResponse<CreateAndWaitResponse> createAndWait(@RequestBody CreateTaskRequest req) {
        // 参数校验
        if (req.getStyle() == null || req.getStyle().isEmpty()) {
            return ApiResponse.fail("水印风格(style)不能为空");
        }
        if (!watermarkEdgeTaskCreator.isStyleSupported(req.getStyle())) {
            return ApiResponse.fail("不支持的水印风格: " + req.getStyle() +
                    "，支持的风格: " + watermarkEdgeTaskCreator.getSupportedStyles());
        }
        if (req.getOriginalImageUrl() == null || req.getOriginalImageUrl().isEmpty()) {
            return ApiResponse.fail("原图URL(originalImageUrl)不能为空");
        }
        if (req.getImageWidth() <= 0 || req.getImageHeight() <= 0) {
            return ApiResponse.fail("图片宽高必须大于0");
        }

        // 构建请求
        WatermarkRequest watermarkRequest = WatermarkRequest.builder()
                .originalImageUrl(req.getOriginalImageUrl())
                .imageWidth(req.getImageWidth())
                .imageHeight(req.getImageHeight())
                .qrcodeUrl(req.getQrcodeUrl())
                .faceUrl(req.getFaceUrl())
                .scenicLine(req.getScenicLine())
                .datetimeLine(req.getDatetimeLine())
                .offsetTop(req.getOffsetTop())
                .offsetBottom(req.getOffsetBottom())
                .offsetLeft(req.getOffsetLeft())
                .offsetRight(req.getOffsetRight())
                .scale(req.getScale())
                .outputFormat(req.getOutputFormat() != null ? req.getOutputFormat() : "JPEG")
                .outputQuality(req.getOutputQuality() != null ? req.getOutputQuality() : 75)
                .build();

        // 超时时间，默认30秒
        long timeoutMs = req.getTimeoutMs() != null ? req.getTimeoutMs() : 30000L;

        // 先创建任务获取 taskId
        Long taskId = watermarkEdgeTaskCreator.createTask(
                req.getStyle(),
                watermarkRequest,
                req.getRecordId() != null ? req.getRecordId() : 0L,
                req.getFaceId(),
                req.getWatermarkType() != null ? req.getWatermarkType() : "test"
        );

        // 注册等待并等待结果
        puzzleEdgeRenderTaskService.registerWait(taskId);
        PuzzleEdgeRenderTaskService.TaskWaitResult result = puzzleEdgeRenderTaskService.waitForTask(taskId, timeoutMs);

        CreateAndWaitResponse response = new CreateAndWaitResponse();
        response.setTaskId(taskId);
        response.setSuccess(result.isSuccess());
        response.setImageUrl(result.getImageUrl());
        response.setErrorMessage(result.getErrorMessage());

        log.info("测试水印任务完成: style={}, taskId={}, success={}, imageUrl={}",
                req.getStyle(), taskId, result.isSuccess(), result.getImageUrl());

        return ApiResponse.success(response);
    }

    /**
     * 创建任务请求
     */
    @Data
    public static class CreateTaskRequest {
        /**
         * 水印风格：normal / leica / printer_default
         */
        private String style;

        /**
         * 原图URL
         */
        private String originalImageUrl;

        /**
         * 原图宽度
         */
        private int imageWidth;

        /**
         * 原图高度
         */
        private int imageHeight;

        /**
         * 二维码URL
         */
        private String qrcodeUrl;

        /**
         * 头像URL（可选）
         */
        private String faceUrl;

        /**
         * 景区名称
         */
        private String scenicLine;

        /**
         * 日期时间行
         */
        private String datetimeLine;

        /**
         * 四边偏移（像素）
         */
        private Integer offsetTop;
        private Integer offsetBottom;
        private Integer offsetLeft;
        private Integer offsetRight;

        /**
         * 缩放倍数
         */
        private Double scale;

        /**
         * 输出格式：PNG / JPEG
         */
        private String outputFormat;

        /**
         * 输出质量（0-100）
         */
        private Integer outputQuality;

        /**
         * 关联的拼图记录ID（测试用）
         */
        private Long recordId;

        /**
         * 人脸ID（可选）
         */
        private Long faceId;

        /**
         * 水印类型标识
         */
        private String watermarkType;

        /**
         * 等待超时时间（毫秒），仅用于 createAndWait
         */
        private Long timeoutMs;
    }

    /**
     * 创建任务响应
     */
    @Data
    public static class CreateTaskResponse {
        private Long taskId;
        private String message;
    }

    /**
     * 创建并等待响应
     */
    @Data
    public static class CreateAndWaitResponse {
        private Long taskId;
        private boolean success;
        private String imageUrl;
        private String errorMessage;
    }
}
