package com.moka.gdtauto.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moka.gdtauto.annotation.AuthUser;
import com.moka.gdtauto.common.Result;
import com.moka.gdtauto.entity.SysUser;
import com.moka.gdtauto.entity.TencentImages;
import com.moka.gdtauto.service.TencentImagesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 腾讯广告图片上传Controller
 *
 * @author moka
 * @since 2026-02-06
 */
@Slf4j
@RestController
@RequestMapping("/api/tencent-images")
@Api(tags = "腾讯广告图片管理")
public class TencentImagesController {

    @Autowired
    private TencentImagesService imagesService;

    /**
     * 上传图片到腾讯广告
     */
    @PostMapping("/upload")
    @ApiOperation("上传图片到腾讯广告")
    public Result<TencentImages> uploadImage(
            @ApiParam("图片文件") @RequestParam("file") MultipartFile file,
            @ApiParam("广告账户ID") @RequestParam("accountId") Long accountId,
            @ApiParam("是否添加水印") @RequestParam(value = "hasWatermark", required = false, defaultValue = "false") Boolean hasWatermark,
            @ApiParam("剧ID") @RequestParam(value = "dramaId", required = false) Long dramaId,
            @ApiParam("图片描述") @RequestParam(value = "description", required = false) String description,
            @AuthUser SysUser user
        ) {
        
        try {
            log.info("开始上传图片: 文件名={}, 账户ID={}, 是否添加水印={}, 剧ID={}", 
                file.getOriginalFilename(), accountId, hasWatermark, dramaId);

            // 校验文件
            if (file.isEmpty()) {
                return Result.fail("图片文件不能为空");
            }

            // 校验文件格式
            String filename = file.getOriginalFilename();
            if (filename == null || (!filename.toLowerCase().endsWith(".jpg") 
                && !filename.toLowerCase().endsWith(".jpeg") 
                && !filename.toLowerCase().endsWith(".png"))) {
                return Result.fail("仅支持JPG、JPEG、PNG格式的图片");
            }

            // 校验文件大小（最大10MB）
            if (file.getSize() > 10 * 1024 * 1024) {
                return Result.fail("图片大小不能超过10MB");
            }

            // 如果选择添加水印，必须选择剧
            if (hasWatermark && dramaId == null) {
                return Result.fail("添加水印时必须选择剧");
            }

            // 上传图片
            TencentImages result = imagesService.uploadImage(file, accountId, hasWatermark, dramaId, description);
            
            if ("SUCCESS".equals(result.getUploadStatus())) {
                log.info("图片上传成功，ID: {}", result.getId());
                return Result.success(result, "图片上传成功");
            } else {
                log.error("图片上传失败: {}", result.getErrorMessage());
                return Result.fail("图片上传失败: " + result.getErrorMessage());
            }
            
        } catch (Exception e) {
            log.error("上传图片异常", e);
            return Result.fail("上传图片异常: " + e.getMessage());
        }
    }

    /**
     * 分页查询图片列表
     */
    @GetMapping("/list")
    @ApiOperation("分页查询图片列表")
    public Result<Page<TencentImages>> list(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Long page,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") Long size,
            @ApiParam("账户ID") @RequestParam(required = false) Long accountId,
            @ApiParam("上传状态") @RequestParam(required = false) String uploadStatus) {
        
        try {
            Page<TencentImages> pageParam = new Page<>(page, size);
            LambdaQueryWrapper<TencentImages> wrapper = new LambdaQueryWrapper<>();
            
            if (accountId != null) {
                wrapper.eq(TencentImages::getAccountId, accountId);
            }
            if (uploadStatus != null && !uploadStatus.trim().isEmpty()) {
                wrapper.eq(TencentImages::getUploadStatus, uploadStatus);
            }
            
            wrapper.orderByDesc(TencentImages::getCreatedTime);
            
            Page<TencentImages> result = imagesService.page(pageParam, wrapper);
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("查询图片列表异常", e);
            return Result.fail("查询图片列表异常: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询图片详情
     */
    @GetMapping("/{id}")
    @ApiOperation("根据ID查询图片详情")
    public Result<TencentImages> getById(@ApiParam("图片ID") @PathVariable Long id) {
        try {
            TencentImages image = imagesService.getById(id);
            if (image == null) {
                return Result.fail("图片不存在");
            }
            return Result.success(image);
        } catch (Exception e) {
            log.error("查询图片详情异常", e);
            return Result.fail("查询图片详情异常: " + e.getMessage());
        }
    }

    /**
     * 删除图片记录
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除图片记录")
    public Result<Void> delete(@ApiParam("图片ID") @PathVariable Long id) {
        try {
            boolean success = imagesService.removeById(id);
            if (success) {
                log.info("删除图片记录成功，ID: {}", id);
                return Result.success(null, "删除成功");
            } else {
                return Result.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("删除图片记录异常", e);
            return Result.fail("删除图片记录异常: " + e.getMessage());
        }
    }
}
