package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.ImageModel;
import com.rj.service.IImageModelService;
import com.rj.utils.ImageConversionUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.rj.service.MinIOService;

/**
 * 图像模型控制
 *
 * https://help.aliyun.com/zh/model-studio/text-to-image#20e9dbb913b9s
 * 
 * 使用Swagger注解进行API文档生成，支持在线API测试。
 * 所有接口都包含完整的参数验证、异常处理和日志记录。
 * 
 * @author 系统生成
 * @date 2025/1/30
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/api/image-model")
@Tag(name = "图像模型管理", description = "图像模型相关接口")
public class ImageModelController {

    /**
     * 图像模型服务接口
     * 用于处理图像模型相关的业务逻辑
     */
    @Autowired
    private IImageModelService imageModelService;
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private com.rj.scheduler.ImageModelStatusScheduler imageModelStatusScheduler;
    
    @Autowired
    private MinIOService minIOService;
    
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 图像模型请求DTO
     * 
     * 用于接收创建图像模型记录的请求参数。
     * 包含所有必要的字段验证，确保数据的完整性和有效性。
     */
    @Data
    public static class ImageModelRequest {
        /**
         * 图像名称，必填字段
         */
        @NotBlank(message = "图像名称不能为空")
        private String imageName;

        private String uuid;
        /**
         * 模型名称，必填字段
         */
        @NotBlank(message = "模型名称不能为空")
        private String modelName;
        
        /**
         * 所属人姓名，必填字段
         */
        @NotBlank(message = "所属人姓名不能为空")
        private String ownerName;
        
        /**
         * 所属人电话，必填字段
         */
        @NotBlank(message = "所属人电话不能为空")
        private String ownerPhone;
        
        /**
         * 图片类型，必填字段
         */
        @NotBlank(message = "图片类型不能为空")
        private String imageType;
        
        /**
         * 素材URL，可选字段
         */
        private String materialUrl;
        
        /**
         * 素材临时URL，可选字段
         */
        private String materialTempUrl;
        
        /**
         * 成品图片URL，可选字段
         */
        private String resultImageUrl;
        
        /**
         * 成品图片临时URL，可选字段
         */
        private String resultImageTempUrl;
        
        /**
         * 提示词，可选字段
         */
        private String prompt;
        
        /**
         * 功能函数名称，可选字段
         */
        private String functionName;
        
        /**
         * 放大倍数，可选字段
         */
        private java.math.BigDecimal scaleFactor;
        
        /**
         * 请求ID，可选字段
         */
        private String requestId;
        
        /**
         * 任务ID，可选字段
         */
        private String taskId;
    }

    /**
     * 分页查询请求DTO
     * 
     * 用于接收分页查询图像模型记录的请求参数。
     * 支持多种条件筛选，包括所属人信息、模型名称、图片类型等。
     */
    @Data
    public static class PageRequest {
        /**
         * 当前页码，默认为1
         */
        private Integer current = 1;
        
        /**
         * 每页大小，默认为10
         */
        private Integer size = 10;
        
        /**
         * 所属人姓名，支持模糊查询
         */
        private String ownerName;
        
        /**
         * 所属人电话，支持模糊查询
         */
        private String ownerPhone;
        
        /**
         * 模型名称，支持模糊查询
         */
        private String modelName;
        
        /**
         * 图片类型，精确匹配
         */
        private String imageType;
        
        /**
         * 开始时间，用于时间范围查询
         */
        private String startTime;
        
        /**
         * 结束时间，用于时间范围查询
         */
        private String endTime;
    }

    /**
     * 创建图像模型记录
     * 
     * 接收图像模型请求参数，创建新的图像模型记录并保存到数据库。
     * 该方法会进行参数验证、数据转换、业务处理等完整流程。
     * 
     * @param request 图像模型请求参数，包含所有必要的字段信息
     * @return ResponseEntity 包含操作结果的响应实体
     *         - success: 操作是否成功
     *         - message: 操作结果消息
     *         - data: 创建的图像模型记录（成功时）
     */
    @PostMapping("/create")
    @Operation(summary = "创建图像模型记录", description = "创建新的图像模型记录")
    public ResponseEntity<Map<String, Object>> createImageModel(@Valid @RequestBody ImageModelRequest request) {
        try {
            log.info("创建图像模型记录开始，参数：{}", request);
            
            // 构建图像模型对象，使用属性拷贝简化代码
            ImageModel imageModel = new ImageModel();
            BeanUtils.copyProperties(request, imageModel);
            imageModel.setCreateTime(LocalDateTime.now());
            imageModel.setUpdateTime(LocalDateTime.now());

            boolean result = imageModelService.saveImageModel(imageModel);
            
            Map<String, Object> response = new HashMap<>();
            if (result) {
                response.put("success", true);
                response.put("message", "图像模型记录创建成功");
                response.put("data", imageModel);
                log.info("图像模型记录创建成功，ID: {}", imageModel.getUuid());
            } else {
                response.put("success", false);
                response.put("message", "图像模型记录创建失败");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("创建图像模型记录异常", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "创建图像模型记录异常: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 根据UUID删除图像模型记录
     *
     * 通过唯一标识符删除对应的图像模型记录。
     * UUID是主键，删除操作是幂等的。
     *
     * @param uuid 唯一标识符，对应数据库主键
     * @return ResponseEntity 包含删除结果的响应实体
     *         - success: 删除是否成功
     *         - message: 删除结果消息
     */
    @DeleteMapping("/delete/{uuid}")
    @Operation(summary = "根据UUID删除图像模型记录", description = "根据唯一标识符删除图像模型记录")
    public ResponseEntity<Map<String, Object>> deleteImageModelByUuid(
            @Parameter(description = "唯一标识符") @PathVariable String uuid) {
        try {
            log.info("根据UUID删除图像模型记录，uuid: {}", uuid);

            boolean result = imageModelService.removeByUuid(uuid);

            Map<String, Object> response = new HashMap<>();
            if (result) {
                response.put("success", true);
                response.put("message", "图像模型记录删除成功");
            } else {
                response.put("success", false);
                response.put("message", "未找到对应的图像模型记录或删除失败");
            }

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("根据UUID删除图像模型记录异常", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "删除异常: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 去除图像中的中英文字符或常见水印
     * 
     * 调用AI模型去除图像中的水印，支持中英文字符和常见水印的检测与去除。
     * 使用场景包括：素材二次处理、广告图净化、图片去水印等。
     * 
     * @param request 图像模型请求参数，包含素材URL和处理参数
     * @return ResponseEntity 包含处理结果的响应实体
     *         - success: 处理是否成功
     *         - message: 处理结果消息
     *         - data: 处理后的图像模型记录（包含结果URL）
     */
    @PostMapping("/removeWatermar")
    @Operation(summary = "去除图像中的中英文字符或常见水印", description = "去除图像中的中英文字符或常见水印。使用场景包括：素材二次处理、广告图净化等")
    public ResponseEntity<Map<String, Object>> removeWatermar(@Valid @RequestBody ImageModelRequest request) {
        try {
            log.info("去除图像中的中英文字符或常见水印开始，参数：{}", request);

            // 构建图像模型对象，使用属性拷贝简化代码
            ImageModel imageModel = new ImageModel();
            BeanUtils.copyProperties(request, imageModel);
            imageModel.setCreateTime(LocalDateTime.now());
            imageModel.setUpdateTime(LocalDateTime.now());
            
            // 调用服务层进行水印去除处理
            ImageModel result = imageModelService.removeWatermar(imageModel);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "水印去除处理成功");
            response.put("data", result);
            log.info("水印去除处理成功，ID: {}, 结果URL: {}", 
                    result.getUuid(), result.getResultImageUrl());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("去除图像水印异常", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "去除图像水印失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 上传图片素材
     * 
     * 支持图片文件上传，包括文件验证、MinIO存储、URL生成和数据库记录保存。
     * 支持多种图片格式：jpg, jpeg, png, gif, bmp, webp
     * 文件大小限制：10MB
     * 
     * @param file 上传的图片文件
     * @param ownerName 所属人姓名
     * @param ownerPhone 所属人电话
     * @return ResponseEntity 包含上传结果的响应实体
     *         - success: 上传是否成功
     *         - message: 上传结果消息
     *         - data: 图像模型记录（包含永久URL和临时URL）
     */
    @PostMapping("/upload")
    @Operation(summary = "上传图片素材", description = "上传图片素材到MinIO存储，生成永久URL和临时URL，并保存记录到数据库")
    public ResponseEntity<Map<String, Object>> uploadImageMaterial(
            @Parameter(description = "图片文件") @RequestParam("file") MultipartFile file,
            @Parameter(description = "所属人姓名") @RequestParam("ownerName") String ownerName,
            @Parameter(description = "所属人电话") @RequestParam("ownerPhone") String ownerPhone,
            @Parameter(description = "素材名称") @RequestParam("imageName") String imageName) {
        try {
            String imageType = "material"; //  默认上传的全部是素材。
            log.info("开始上传图片素材，文件名：{}，所属人：{}，电话：{}，类型：{}", 
                    file.getOriginalFilename(), ownerName, ownerPhone, imageType);

            // 参数验证
            if (ownerName == null || ownerName.trim().isEmpty()) {
                throw new IllegalArgumentException("所属人姓名不能为空");
            }
            if (ownerPhone == null || ownerPhone.trim().isEmpty()) {
                throw new IllegalArgumentException("所属人电话不能为空");
            }
            if (imageType == null || imageType.trim().isEmpty()) {
                throw new IllegalArgumentException("图片类型不能为空");
            }

            // 调用服务层进行图片上传
            ImageModel result = imageModelService.uploadImageMaterial(file, ownerName, ownerPhone, imageType,imageName);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "图片素材上传成功");
            response.put("data", result);
            log.info("图片素材上传成功，ID: {}，永久URL: {}，临时URL: {}", 
                    result.getUuid(), result.getMaterialUrl(), result.getMaterialTempUrl());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("上传图片素材异常", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "上传图片素材失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 根据UUID查询图像模型记录
     * 
     * 通过唯一标识符查询对应的图像模型记录。
     * UUID是主键，查询结果唯一且准确。
     * 
     * @param uuid 唯一标识符，对应数据库主键
     * @return ResponseEntity 包含查询结果的响应实体
     *         - success: 查询是否成功
     *         - message: 查询结果消息
     *         - data: 图像模型记录（找到时）
     */
    @GetMapping("/get/{uuid}")
    @Operation(summary = "根据UUID查询图像模型记录", description = "根据唯一标识符查询图像模型记录")
    public ResponseEntity<Map<String, Object>> getImageModelByUuid(
            @Parameter(description = "唯一标识符") @PathVariable String uuid) {
        try {
            log.info("根据UUID查询图像模型记录，UUID: {}", uuid);
            
            ImageModel imageModel = imageModelService.getByUuid(uuid);
            
            Map<String, Object> response = new HashMap<>();
            if (imageModel != null) {
                response.put("success", true);
                response.put("message", "查询成功");
                response.put("data", imageModel);
            } else {
                response.put("success", false);
                response.put("message", "未找到对应的图像模型记录");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("根据UUID查询图像模型记录异常", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "查询异常: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 分页查询图像模型记录
     * 
     * 支持多种条件的分页查询功能，包括：
     * - 按所属人姓名、电话模糊查询
     * - 按模型名称模糊查询
     * - 按图片类型精确查询
     * - 按时间范围查询
     * 
     * @param request 分页查询请求参数，包含查询条件和分页信息
     * @return ResponseEntity 包含分页查询结果的响应实体
     *         - success: 查询是否成功
     *         - message: 查询结果消息
     *         - data: 分页结果（包含记录列表和分页信息）
     */
 
    @Operation(summary = "分页查询图像模型记录", description = "分页查询图像模型记录")
    public ResponseEntity<Map<String, Object>> pageImageModel(@RequestBody PageRequest request) {
        try {
            log.info("分页查询图像模型记录开始，参数：{}", request);
            
            Page<ImageModel> page = new Page<>(request.getCurrent(), request.getSize());
            LambdaQueryWrapper<ImageModel> queryWrapper = new LambdaQueryWrapper<>();
            
            if (request.getOwnerName() != null && !request.getOwnerName().trim().isEmpty()) {
                queryWrapper.like(ImageModel::getOwnerName, request.getOwnerName());
            }
            if (request.getOwnerPhone() != null && !request.getOwnerPhone().trim().isEmpty()) {
                queryWrapper.like(ImageModel::getOwnerPhone, request.getOwnerPhone());
            }
            if (request.getModelName() != null && !request.getModelName().trim().isEmpty()) {
                queryWrapper.like(ImageModel::getModelName, request.getModelName());
            }
            if (request.getImageType() != null && !request.getImageType().trim().isEmpty()) {
                queryWrapper.eq(ImageModel::getImageType, request.getImageType());
            }
            
            queryWrapper.orderByDesc(ImageModel::getCreateTime);
            
            Page<ImageModel> result = imageModelService.page(page, queryWrapper);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "查询成功");
            response.put("data", result);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("分页查询图像模型记录异常", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "查询异常: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 分页查询图像模型列表
     * 
     * 参考face-detect/logs接口实现，返回标准格式的分页查询结果，包含：
     * - total: 总记录数
     * - current: 当前页码
     * - pages: 总页数
     * - data: 数据列表
     * - size: 每页大小
     * - success: 操作是否成功
     * - message: 响应消息
     * 
     * @param current 当前页码，默认为1
     * @param size 每页大小，默认为10
     * @param ownerName 所属人姓名，支持模糊查询
     * @param ownerPhone 所属人电话，支持模糊查询
     * @param modelName 模型名称，支持模糊查询
     * @param imageType 图片类型，精确匹配
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return ResponseEntity 包含标准格式分页查询结果的响应实体
     */
    @PostMapping("/page")
    @Operation(summary = "分页查询图像模型列表", description = "分页查询图像模型列表，返回标准格式")
    public ResponseEntity<Map<String, Object>> listImageModel(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "所属人姓名")
            @RequestParam(required = false) String ownerName,
            @Parameter(description = "图像名称")
            @RequestParam(required = false) String imageName,
            @Parameter(description = "所属人电话")
            @RequestParam(required = false) String ownerPhone,
            @Parameter(description = "模型名称")
            @RequestParam(required = false) String modelName,
            @Parameter(description = "图片类型")
            @RequestParam(required = false) String imageType,
            @Parameter(description = "开始时间")
            @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间")
            @RequestParam(required = false) String endTime) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            log.info("分页查询图像模型列表开始，参数：current={}, size={}, ownerName={}, ownerPhone={}, modelName={}, imageType={}, startTime={}, endTime={}", 
                    current, size, ownerName, ownerPhone, modelName, imageType, startTime, endTime);
            
            Page<ImageModel> page = new Page<>(current, size);
            LambdaQueryWrapper<ImageModel> queryWrapper = new LambdaQueryWrapper<>();
            
            // 构建查询条件
            if (ownerName != null && !ownerName.trim().isEmpty()) {
                queryWrapper.like(ImageModel::getOwnerName, ownerName);
            }
            if (ownerPhone != null && !ownerPhone.trim().isEmpty()) {
                queryWrapper.like(ImageModel::getOwnerPhone, ownerPhone);
            }
            if (modelName != null && !modelName.trim().isEmpty()) {
                queryWrapper.like(ImageModel::getModelName, modelName);
            }
            if (imageName != null && !imageName.trim().isEmpty()) {
                queryWrapper.like(ImageModel::getImageName, imageName);
            }
            if (imageType != null && !imageType.trim().isEmpty()) {
                queryWrapper.eq(ImageModel::getImageType, imageType);
            }
            if (startTime != null && !startTime.trim().isEmpty()) {
                queryWrapper.ge(ImageModel::getCreateTime, startTime);
            }
            if (endTime != null && !endTime.trim().isEmpty()) {
                queryWrapper.le(ImageModel::getUpdateTime, endTime);
            }

            // 按创建时间降序排列
            queryWrapper.orderByDesc(ImageModel::getUpdateTime);
            
            // 执行分页查询
            Page<ImageModel> pageResult = imageModelService.page(page, queryWrapper);
            
            // 构建标准格式响应
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("current", pageResult.getCurrent());
            result.put("size", pageResult.getSize());
            result.put("pages", pageResult.getPages());
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("分页查询图像模型列表异常", e);
            result.put("success", false);
            result.put("message", "查询异常: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 根据请求ID查询图像模型记录
     * 
     * 通过请求ID查询对应的图像模型记录。
     * 一个请求ID可能对应多条记录，此方法返回最新的一条。
     * 主要用于追踪特定请求的处理结果。
     * 
     * @param requestId 请求ID，用于追踪处理请求
     * @return ResponseEntity 包含查询结果的响应实体
     *         - success: 查询是否成功
     *         - message: 查询结果消息
     *         - data: 图像模型记录（找到时）
     */
    @GetMapping("/get-by-request/{requestId}")
    @Operation(summary = "根据请求ID查询图像模型记录", description = "根据请求ID查询图像模型记录")
    public ResponseEntity<Map<String, Object>> getImageModelByRequestId(
            @Parameter(description = "请求ID") @PathVariable String requestId) {
        try {
            log.info("根据请求ID查询图像模型记录，requestId: {}", requestId);
            
            ImageModel imageModel = imageModelService.getByRequestId(requestId);
            
            Map<String, Object> response = new HashMap<>();
            if (imageModel != null) {
                response.put("success", true);
                response.put("message", "查询成功");
                response.put("data", imageModel);
            } else {
                response.put("success", false);
                response.put("message", "未找到对应的图像模型记录");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("根据请求ID查询图像模型记录异常", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "查询异常: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 根据任务ID查询图像模型记录
     * 
     * 通过任务ID查询对应的图像模型记录。
     * 一个任务ID可能对应多条记录，此方法返回最新的一条。
     * 主要用于查询异步处理任务的结果。
     * 
     * @param taskId 任务ID，用于追踪异步处理任务
     * @return ResponseEntity 包含查询结果的响应实体
     *         - success: 查询是否成功
     *         - message: 查询结果消息
     *         - data: 图像模型记录（找到时）
     */
    @GetMapping("/get-by-task/{taskId}")
    @Operation(summary = "根据任务ID查询图像模型记录", description = "根据任务ID查询图像模型记录")
    public ResponseEntity<Map<String, Object>> getImageModelByTaskId(
            @Parameter(description = "任务ID") @PathVariable String taskId) {
        try {
            log.info("根据任务ID查询图像模型记录，taskId: {}", taskId);
            
            ImageModel imageModel = imageModelService.getByTaskId(taskId);
            
            Map<String, Object> response = new HashMap<>();
            if (imageModel != null) {
                response.put("success", true);
                response.put("message", "查询成功");
                response.put("data", imageModel);
            } else {
                response.put("success", false);
                response.put("message", "未找到对应的图像模型记录");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("根据任务ID查询图像模型记录异常", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "查询异常: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    @PostMapping("/text-to-image")
    @Operation(summary = "文本生成图像", description = "基于文本提示词生成图像")
    public ResponseEntity<Map<String, Object>> textToImage(
            @Parameter(description = "文本生成图像") @Valid @RequestBody TextModelController.ImageProcessingRequest request) {
        log.info("开始文本生成图像，request: {}", request);
        
        try {
            // 调用服务层进行文本生成图像处理
            Map<String, Object> processingResponse = imageModelService.generateImageByText(request);
            
            log.info("文本生成图像处理完成，生成图片数量: {}", processingResponse.get("imageCount"));
            
            return ResponseEntity.ok(processingResponse);

        } catch (Exception e) {
            log.error("文本生成图像处理失败: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "文本生成图像处理失败: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }


    /**
     * 图像处理接口，根据给的素材生成图片
     */
    @PostMapping("/image-background")
    @Operation(summary = "图像处理", description = "基于参考图像和提示词进行图像处理")
    public ResponseEntity<Map<String, Object>> imageProcessing(
            @Parameter(description = "图像处理请求参数") @Valid @RequestBody TextModelController.ImageProcessingRequest request) {
        log.info("开始图像处理,request : {} ",request);
        Map<String, Object> result = new HashMap<>();

        try {
            log.info("开始图像处理，基础图片: {}, 参考图片: {}, 参考提示词: {}",
                    request.getBaseImageUrl(), request.getRefImageUrl(), request.getRefPrompt());

            // 模拟图像处理（实际项目中应该调用图像处理服务）
            Map<String, Object> processingResponse = performImageProcessing(request);

            result.put("success", true);
            result.put("message", "图像处理完成");
            result.put("baseImageUrl", request.getBaseImageUrl());
            result.put("refImageUrl", request.getRefImageUrl());
            result.put("refPrompt", request.getRefPrompt());
            result.put("processedImages", processingResponse.get("processedImages"));
            result.put("processingTimeMs", processingResponse.get("processingTimeMs"));
            result.put("modelVersion", request.getParameters() != null ? request.getParameters().getModelVersion() : "v3");
            result.put("refPromptWeight", request.getParameters() != null ? request.getParameters().getRefPromptWeight() : 0.5);
            result.put("requestId", generateRequestId());
            result.put("timestamp", LocalDateTime.now());

            log.info("图像处理完成，生成图片数量: {}", processingResponse.get("imageCount"));

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("图像处理失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "图像处理失败: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    @Autowired
    ImageConversionUtil imageConversionUtil ;
    /**
     * 执行图像处理的方法 - 调用阿里云API
     */
    private Map<String, Object> performImageProcessing(TextModelController.ImageProcessingRequest request) {
        Map<String, Object> response = new HashMap<>();
        long startTime = System.currentTimeMillis();
        
        try {
            log.info("开始调用阿里云图像生成API，基础图片: {}, 参考图片: {}", 
                request.getBaseImageUrl(), request.getRefImageUrl());
            
            // 处理引导图像RGBA转换（如果存在引导图像）
            if (request.getBaseImageUrl() != null && !request.getBaseImageUrl().trim().isEmpty()) {
                log.info("检测到引导图像，开始进行RGBA转换处理");
                byte[] bytes = imageConversionUtil.convertImageToAliyunFormatAdvanced(request.getBaseImageUrl());
                String processedRefImageUrl = uploadFile(bytes);
                if (processedRefImageUrl != null) {
                    log.info("产品主图baseImage图像RGBA转换完成，新URL: {}", processedRefImageUrl);
                    request.setBaseImageUrl(processedRefImageUrl);
                }
            }
            // 处理前景边缘图像转换
            if (request.getReferenceEdge() != null && request.getReferenceEdge().getForegroundEdge() != null) {
                String[] originalForegroundEdges = request.getReferenceEdge().getForegroundEdge();
                String[] backgroundEdges = request.getReferenceEdge().getBackgroundEdge();

                List<String> processedForegroundEdges = new ArrayList<>();
                List<String> processedbackgroundEdges = new ArrayList<>();

                // 1, 背景图边处理
                for (String backgroundEdge : backgroundEdges) {
                    byte[] bytes = imageConversionUtil.convertImageToAliyunFormatAdvanced(backgroundEdge);
                    String processedRefImageUrl = uploadFile(bytes);
                    if (processedRefImageUrl != null) {
                        log.info("产品主图baseImage图像RGBA转换完成，新URL: {}", processedRefImageUrl);
                        processedbackgroundEdges .add(processedRefImageUrl);
                    }
                }


                // 2, 前景图边处理
                for (String foregroundEdgeUrl : originalForegroundEdges) {
                    if (foregroundEdgeUrl != null && !foregroundEdgeUrl.trim().isEmpty()) {
                        log.info("开始进行ForegroundEdge的RGBA转换处理: {}", foregroundEdgeUrl);
                        try {
                byte[] bytes = imageConversionUtil.convertImageToAliyunFormatAdvanced(foregroundEdgeUrl);
                            if (bytes != null) {
                String processedRefImageUrl = uploadFile(bytes);
                                if (processedRefImageUrl != null && !processedRefImageUrl.trim().isEmpty()) {
                    log.info("ForegroundEdge图像RGBA转换完成，新URL: {}", processedRefImageUrl);
                                    processedForegroundEdges.add(processedRefImageUrl);
                                } else {
                                    log.warn("ForegroundEdge图像上传失败，跳过此URL: {}", foregroundEdgeUrl);
                                }
                            } else {
                                log.warn("ForegroundEdge图像转换失败，跳过此URL: {}", foregroundEdgeUrl);
                            }
                        } catch (Exception e) {
                            log.error("处理ForegroundEdge图像时发生异常: {}", foregroundEdgeUrl, e);
                        }
                    } else {
                        log.warn("发现空的ForegroundEdge URL，跳过处理");
                    }
                }
                
                // 只有当成功处理了至少一个URL时才更新
                if (!processedForegroundEdges.isEmpty()) {
                    String[] newForegroundEdges = processedForegroundEdges.toArray(new String[0]);
                    request.getReferenceEdge().setForegroundEdge(newForegroundEdges);
                    log.info("成功处理{}个ForegroundEdge图像", newForegroundEdges.length);
                } else {
                    log.warn("没有成功处理任何ForegroundEdge图像，将使用原始URL");
                }

                if (!processedbackgroundEdges.isEmpty()) {
                    String[] processedbackgroundEdgess = processedbackgroundEdges.toArray(new String[0]);
                    request.getReferenceEdge().setBackgroundEdge(processedbackgroundEdgess);
                    log.info("成功处理{}个processedbackgroundEdgess e图像", processedbackgroundEdgess.length);
                }

            }


            // 构建阿里云请求参数
            Map<String, Object> aliyunRequest = buildAliyunRequest(request);
            
            // 发送请求到阿里云
            String aliyunResponse = sendRequestToAliyun(aliyunRequest);
            
            // 解析阿里云响应
            Map<String, Object> parsedResponse = parseAliyunResponse(aliyunResponse);
            
            // 保存数据到数据库
            ImageModel imageModel = createImageModelRecord(request, parsedResponse);
            boolean saveResult = imageModelService.saveImageModel(imageModel);
            
            long processingTime = System.currentTimeMillis() - startTime;
            
            response.put("success", true);
            response.put("taskId", parsedResponse.get("taskId"));
            response.put("status", parsedResponse.get("status"));
            response.put("taskStatus", parsedResponse.get("status")); // 添加task_status字段
            response.put("processingTimeMs", processingTime);
            response.put("saveResult", saveResult);
            response.put("recordId", imageModel.getUuid());
            
            // 如果有参考边缘信息，记录处理详情
            if (request.getReferenceEdge() != null) {
                response.put("foregroundEdgeCount", request.getReferenceEdge().getForegroundEdge() != null ?
                        request.getReferenceEdge().getForegroundEdge().length : 0);
                response.put("backgroundEdgeCount", request.getReferenceEdge().getBackgroundEdge() != null ?
                        request.getReferenceEdge().getBackgroundEdge().length : 0);
            }
            
            log.info("阿里云图像生成任务提交成功，任务ID: {}, 处理时间: {}ms", parsedResponse.get("taskId"), processingTime);
            
        } catch (Exception e) {
            log.error("阿里云图像生成失败: {}", e.getMessage(), e);
            response.put("success", false);
            response.put("error", e.getMessage());
            response.put("processingTimeMs", System.currentTimeMillis() - startTime);
        }
        
        return response;
    }
    
    /**
     *
     * 
     * 上传到MinIO并生成新的临时访问链接
     * 
     * @param
     * @return 处理后的RGBA图像临时访问链接，如果处理失败返回null
     */
    private String uploadFile( byte[] originalImageBytes) {
        try {
            log.info("开始处理引导图像RGBA转换，原始URL: ");
            
            // 1. 下载原始图像

            // 2. 转换为RGBA格式
            // 3. 生成唯一文件名
            String uniqueFileName = generateUniqueFileName("png");
            
            // 4. 上传RGBA图像到MinIO
            String materialUrl = minIOService.uploadFile(originalImageBytes, uniqueFileName, "image/png");
            log.info("RGBA图像上传到MinIO成功: {}", materialUrl);
            
            // 5. 生成7天临时访问链接
            String materialTempUrl = minIOService.generateTempUrl(uniqueFileName);
            log.info("生成7天临时访问链接: {}", materialTempUrl);
            
            return materialTempUrl;
            
        } catch (Exception e) {
            log.error("处理引导图像RGBA转换失败: {}", e);
            return null;
        }
    }
    

    

    /**
     * 生成唯一文件名
     * 
     * @param extension 文件扩展名
     * @return 唯一文件名
     */
    private String generateUniqueFileName(String extension) {
        long timestamp = System.currentTimeMillis();
        String uuid = java.util.UUID.randomUUID().toString().replace("-", "");
        return timestamp + "_" + uuid + "." + extension;
    }
    
    /**
     * 构建阿里云请求参数
     */
    private Map<String, Object> buildAliyunRequest(TextModelController.ImageProcessingRequest request) {
        Map<String, Object> aliyunRequest = new HashMap<>();
        
        // 设置模型
        aliyunRequest.put("model", "wanx-background-generation-v2");
        
        // 构建input参数
        Map<String, Object> input = new HashMap<>();
        input.put("base_image_url", request.getBaseImageUrl());
        input.put("ref_image_url", request.getRefImageUrl());
        input.put("ref_prompt", request.getRefPrompt());
        
        // 构建reference_edge参数
        if (request.getReferenceEdge() != null) {
            Map<String, Object> referenceEdge = new HashMap<>();
            
            // 处理前景边缘URL，过滤掉null值和无效URL
            if (request.getReferenceEdge().getForegroundEdge() != null) {
                List<String> validForegroundEdges = new ArrayList<>();
                for (String url : request.getReferenceEdge().getForegroundEdge()) {
                    if (isValidUrl(url)) {
                        validForegroundEdges.add(url);
                    } else {
                        log.warn("跳过无效的前景边缘URL: {}", url);
                    }
                }
                if (!validForegroundEdges.isEmpty()) {
                    referenceEdge.put("foreground_edge", validForegroundEdges.toArray(new String[0]));
                    log.info("添加{}个有效的前景边缘URL", validForegroundEdges.size());
                } else {
                    log.warn("没有有效的前景边缘URL");
                }
            }
            
            // 处理背景边缘URL，过滤掉null值和无效URL
            if (request.getReferenceEdge().getBackgroundEdge() != null) {
                List<String> validBackgroundEdges = new ArrayList<>();
                for (String url : request.getReferenceEdge().getBackgroundEdge()) {
                    if (isValidUrl(url)) {
                        validBackgroundEdges.add(url);
                    } else {
                        log.warn("跳过无效的背景边缘URL: {}", url);
                    }
                }
                if (!validBackgroundEdges.isEmpty()) {
                    referenceEdge.put("background_edge", validBackgroundEdges.toArray(new String[0]));
                    log.info("添加{}个有效的背景边缘URL", validBackgroundEdges.size());
                } else {
                    log.warn("没有有效的背景边缘URL");
                }
            }
            
            // 处理前景边缘提示词，过滤掉null值
            if (request.getReferenceEdge().getForegroundEdgePrompt() != null) {
                List<String> validForegroundPrompts = new ArrayList<>();
                for (String prompt : request.getReferenceEdge().getForegroundEdgePrompt()) {
                    if (prompt != null && !prompt.trim().isEmpty()) {
                        validForegroundPrompts.add(prompt);
                    }
                }
                if (!validForegroundPrompts.isEmpty()) {
                    referenceEdge.put("foreground_edge_prompt", validForegroundPrompts.toArray(new String[0]));
                }
            }
            
            // 处理背景边缘提示词，过滤掉null值
            if (request.getReferenceEdge().getBackgroundEdgePrompt() != null) {
                List<String> validBackgroundPrompts = new ArrayList<>();
                for (String prompt : request.getReferenceEdge().getBackgroundEdgePrompt()) {
                    if (prompt != null && !prompt.trim().isEmpty()) {
                        validBackgroundPrompts.add(prompt);
                    }
                }
                if (!validBackgroundPrompts.isEmpty()) {
                    referenceEdge.put("background_edge_prompt", validBackgroundPrompts.toArray(new String[0]));
                }
            }
            
            // 只有当referenceEdge不为空时才添加到input中
            if (!referenceEdge.isEmpty()) {
            input.put("reference_edge", referenceEdge);
                log.info("添加reference_edge参数，包含{}个字段", referenceEdge.size());
            } else {
                log.warn("reference_edge参数为空，跳过添加");
            }
        }
        
        aliyunRequest.put("input", input);
        
        // 构建parameters参数
        Map<String, Object> parameters = new HashMap<>();
        if (request.getParameters() != null) {
            parameters.put("n", request.getParameters().getN());
            parameters.put("ref_prompt_weight", request.getParameters().getRefPromptWeight());
            parameters.put("model_version", request.getParameters().getModelVersion());
        } else {
            parameters.put("n", 1);
            parameters.put("ref_prompt_weight", 0.5);
            parameters.put("model_version", "v3");
        }
        aliyunRequest.put("parameters", parameters);
        
        return aliyunRequest;
    }
    
    /**
     * 发送请求到阿里云
     */
    private String sendRequestToAliyun(Map<String, Object> request) throws Exception {
        String apiKey = System.getenv("DASHSCOPE_API_KEY");
        if (apiKey == null || apiKey.isEmpty()) {
            throw new RuntimeException("DASHSCOPE_API_KEY 环境变量未设置");
        }
        
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/background-generation/generation/";
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("X-DashScope-Async", "enable");
        headers.set("Authorization", "Bearer " + apiKey);
        
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);
        
        log.info("发送请求到阿里云: {}", objectMapper.writeValueAsString(request));
        
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        
        if (response.getStatusCode().is2xxSuccessful()) {
            log.info("阿里云请求成功，响应: {}", response.getBody());
            return response.getBody();
        } else {
            throw new RuntimeException("阿里云请求失败，状态码: " + response.getStatusCode());
        }
    }
    
    /**
     * 解析阿里云响应
     */
    private Map<String, Object> parseAliyunResponse(String responseBody) throws Exception {
        JsonNode rootNode = objectMapper.readTree(responseBody);
        Map<String, Object> result = new HashMap<>();
        
        if (rootNode.has("output")) {
            JsonNode outputNode = rootNode.get("output");
            if (outputNode.has("task_id")) {
                result.put("taskId", outputNode.get("task_id").asText());
            }
            if (outputNode.has("task_status")) {
                result.put("status", outputNode.get("task_status").asText());
            }
        }
        
        if (rootNode.has("request_id")) {
            result.put("requestId", rootNode.get("request_id").asText());
        }
        
        return result;
    }
    
    /**
     * 创建ImageModel记录对象
     */
    private ImageModel createImageModelRecord(TextModelController.ImageProcessingRequest request, Map<String, Object> parsedResponse) {
        ImageModel imageModel = new ImageModel();
        
        // 设置基本信息
        imageModel.setImageName(request.getImageName());
        imageModel.setModelName("wanx-background-generation-v2");
        imageModel.setOwnerName(request.getOwnerName());
        imageModel.setOwnerPhone(request.getOwnerPhone());
        imageModel.setImageType("result"); // 生成的结果图片
        
        // 设置时间
        imageModel.setCreateTime(LocalDateTime.now());
        imageModel.setUpdateTime(LocalDateTime.now());
        
        // 设置素材URL（包含所有相关URL的JSON）
        String materialUrlJson = createMaterialUrlJson(request);
        imageModel.setMaterialTempUrl(materialUrlJson);
        
        // 设置提示词
        imageModel.setPrompt(request.getRefPrompt());
        
        // 设置功能函数
        imageModel.setFunctionName("background_generation");
        
        // 设置请求ID、任务ID和任务状态
        imageModel.setRequestId(generateRequestId());
        imageModel.setTaskId((String) parsedResponse.get("taskId"));
        imageModel.setTaskStatus((String) parsedResponse.get("status"));
        
        log.info("创建ImageModel记录: 所属人={}, 任务ID={}, 任务状态={}, 请求ID={}", 
            request.getOwnerName(), parsedResponse.get("taskId"), parsedResponse.get("status"), imageModel.getRequestId());
        
        return imageModel;
    }
    
    /**
     * 创建包含所有URL信息的JSON字符串
     */
    private String createMaterialUrlJson(TextModelController.ImageProcessingRequest request) {
        try {
            Map<String, Object> urlInfo = new HashMap<>();
            
            // 主图URL
            urlInfo.put("baseImageUrl", request.getBaseImageUrl());
            
            // 参考图URL
            urlInfo.put("refImageUrl", request.getRefImageUrl());
            
            // 参考边缘信息
            if (request.getReferenceEdge() != null) {
                Map<String, Object> edgeInfo = new HashMap<>();
                
                // 前景边缘URL
                if (request.getReferenceEdge().getForegroundEdge() != null) {
                    edgeInfo.put("foregroundEdge", request.getReferenceEdge().getForegroundEdge());
                }
                
                // 背景边缘URL
                if (request.getReferenceEdge().getBackgroundEdge() != null) {
                    edgeInfo.put("backgroundEdge", request.getReferenceEdge().getBackgroundEdge());
                }
                
                // 前景边缘提示词
                if (request.getReferenceEdge().getForegroundEdgePrompt() != null) {
                    edgeInfo.put("foregroundEdgePrompt", request.getReferenceEdge().getForegroundEdgePrompt());
                }
                
                // 背景边缘提示词
                if (request.getReferenceEdge().getBackgroundEdgePrompt() != null) {
                    edgeInfo.put("backgroundEdgePrompt", request.getReferenceEdge().getBackgroundEdgePrompt());
                }
                
                urlInfo.put("referenceEdge", edgeInfo);
            }
            
            // 转换为JSON字符串
            String jsonString = objectMapper.writeValueAsString(urlInfo);
            log.info("创建素材URL JSON: {}", jsonString);
            return jsonString;
            
        } catch (Exception e) {
            log.error("创建素材URL JSON失败: {}", e.getMessage(), e);
            // 如果JSON创建失败，至少保存基础图片URL
            return request.getBaseImageUrl();
        }
    }

    /**
     * 手动触发图像模型任务状态检查
     * 
     * 提供手动触发任务状态检查的接口，用于：
     * - 立即检查所有PENDING或RUNNING状态的任务
     * - 调试和测试任务状态检查功能
     * - 紧急情况下手动处理任务
     * 
     * @return ResponseEntity 包含执行结果的响应实体
     *         - success: 执行是否成功
     *         - message: 执行结果消息
     *         - processedCount: 处理的任务数量
     *         - timestamp: 执行时间戳
     */
    @PostMapping("/check-status")
    @Operation(summary = "手动触发任务状态检查", description = "立即执行图像模型任务状态检查，处理所有PENDING或RUNNING状态的任务")
    public ResponseEntity<Map<String, Object>> checkImageModelStatus() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("手动触发图像模型任务状态检查开始");
            
            // 调用调度器的检查方法
            imageModelStatusScheduler.checkImageModelStatus();
            
            result.put("success", true);
            result.put("message", "图像模型任务状态检查执行成功");
            result.put("timestamp", LocalDateTime.now());
            result.put("requestId", generateRequestId());
            
            log.info("手动触发图像模型任务状态检查完成");
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("手动触发图像模型任务状态检查失败: {}", e.getMessage(), e);
            
            result.put("success", false);
            result.put("message", "图像模型任务状态检查执行失败: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
            result.put("timestamp", LocalDateTime.now());
            result.put("requestId", generateRequestId());
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 验证URL是否有效
     * 
     * @param url 要验证的URL
     * @return 是否为有效URL
     */
    private boolean isValidUrl(String url) {
        if (url == null || url.trim().isEmpty()) {
            return false;
        }
        
        try {
            // 基本URL格式验证
            if (!url.startsWith("http://") && !url.startsWith("https://")) {
                return false;
            }
            
            // 尝试解析URL
            new java.net.URL(url);
            return true;
        } catch (Exception e) {
            log.warn("URL格式无效: {}", url);
            return false;
        }
    }

    /**
     * 生成请求ID
     */
    private String generateRequestId() {
        return "REQ_" + System.currentTimeMillis() + "_" + (int)(Math.random() * 1000);
    }
    
    /**
     * 调用阿里云 根据图片和指令，生成新图
     *
     * @return ResponseEntity 包含生成结果的响应实体
     */
    @PostMapping("/image-to-image")
    @Operation(summary = "图生图", description = "根据图片和指令，生成新图片")
    public ResponseEntity<Map<String, Object>> generateimageToImage(
            @Parameter(description = "文件", required = true)
            @RequestParam("multipartFile") MultipartFile multipartFile,
            @Parameter(description = "参考提示词", required = true)
            @RequestParam("refPrompt") String refPrompt,
            @Parameter(description = "提示词", required = true)
            @RequestParam("prompt") String prompt,
            @Parameter(description = "所属人姓名", required = true)
            @RequestParam("ownerName") String ownerName,
            @Parameter(description = "所属人电话", required = true)
            @RequestParam("ownerPhone") String ownerPhone,
            @Parameter(description = "图片名称", required = true)
            @RequestParam("imageName") String imageName,
            @Parameter(description = "模型名称", required = false)
            @RequestParam(value = "model") String model,
            @Parameter(description = "参数", required = false)
            @RequestParam(value = "parameters", required = false) String parameters) {
        
        try {
            log.info("开始图生图处理，ownerName: {}, imageName: {}, prompt: {}",
                    ownerName, imageName, prompt);
            
            // 调用业务层方法处理图生图逻辑
            Map<String, Object> result = imageModelService.generateImageToImage(
                multipartFile, prompt, ownerName, ownerPhone, imageName, model, parameters);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("图生图API失败: {}", e.getMessage(), e);
            
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "图生图生成失败: " + e.getMessage());
            errorResult.put("error", e.getClass().getSimpleName());
            errorResult.put("timestamp", LocalDateTime.now());
            errorResult.put("requestId", generateRequestId());
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        }
    }

}
