package top.tqx.demo_1.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import top.tqx.demo_1.common.Result;
import top.tqx.demo_1.dto.ImageCreateRequest;
import top.tqx.demo_1.dto.ImageListResponse;
import top.tqx.demo_1.dto.ImageStatsResponse;
import top.tqx.demo_1.dto.ImageUpdateRequest;
import top.tqx.demo_1.entity.Image;
import top.tqx.demo_1.service.ImageService;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "图片管理", description = "知识库图片相关接口")
@RestController
@RequestMapping("/image")
@Slf4j
public class ImageController {

    @Autowired
    private ImageService imageService;

    @Operation(summary = "创建图片记录", description = "创建新的图片记录")
    @PostMapping
    public Result<Image> createImage(@RequestBody ImageCreateRequest request) {
        if (request.getImageId() == null || request.getImageId().isEmpty()) {
            return Result.error(400, "图片ID不能为空");
        }
        if (request.getPath() == null || request.getPath().isEmpty()) {
            return Result.error(400, "图片路径不能为空");
        }

        try {
            Image image = imageService.createImage(request);
            log.info("创建图片记录成功: id={}, imageId={}", image.getId(), image.getImageId());
            return Result.success("图片记录创建成功", image);
        } catch (Exception e) {
            log.error("创建图片记录失败: {}", e.getMessage(), e);
            return Result.error(500, "创建图片记录失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取图片列表", description = "分页获取知识库中的图片列表")
    @GetMapping({"/list", "/images/list"})
    public Result<ImageListResponse> getImageList(
            @Parameter(description = "返回数量，默认50") @RequestParam(defaultValue = "50") Integer limit,
            @Parameter(description = "偏移量，默认0") @RequestParam(defaultValue = "0") Integer offset) {
        try {
            ImageListResponse response = imageService.getImageList(limit, offset);
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取图片列表失败", e);
            return Result.error(500, "获取图片列表失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取图片详情", description = "根据图片ID获取图片详细信息")
    @GetMapping("/{id}")
    public Result<Image> getImageById(
            @Parameter(description = "图片ID") @PathVariable Long id) {
        try {
            Image image = imageService.getImageById(id);
            if (image == null) {
                return Result.error(404, "图片不存在");
            }
            return Result.success(image);
        } catch (Exception e) {
            log.error("获取图片详情失败: {}", e.getMessage(), e);
            return Result.error(500, "获取图片详情失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取单张图片", description = "通过图片ID获取图片文件")
    @GetMapping(value = "/{id}/data", produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_GIF_VALUE})
    public byte[] getImageData(@Parameter(description = "图片ID") @PathVariable String id) {
        try {
            log.info("获取图片: id={}", id);
            byte[] imageData = imageService.getImage(id);
            if (imageData == null || imageData.length == 0) {
                log.warn("图片数据为空: id={}", id);
                // 返回一个1x1的透明像素作为占位符
                return createPlaceholderImage();
            }
            return imageData;
        } catch (Exception e) {
            log.error("获取图片失败: id={}, error={}", id, e.getMessage());
            // 返回一个1x1的透明像素作为占位符，避免页面报错
            return createPlaceholderImage();
        }
    }
    
    /**
     * 创建一个1x1的透明占位图
     */
    private byte[] createPlaceholderImage() {
        // 这是一个1x1的透明PNG图片的字节数组
        return new byte[] {
            (byte)0x89, (byte)0x50, (byte)0x4E, (byte)0x47, (byte)0x0D, (byte)0x0A, (byte)0x1A, (byte)0x0A,
            (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0D, (byte)0x49, (byte)0x48, (byte)0x44, (byte)0x52,
            (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01,
            (byte)0x08, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x1F, (byte)0x15, (byte)0xC4,
            (byte)0x89, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0A, (byte)0x49, (byte)0x44, (byte)0x41,
            (byte)0x54, (byte)0x08, (byte)0xD7, (byte)0x63, (byte)0x60, (byte)0x00, (byte)0x00, (byte)0x00,
            (byte)0x02, (byte)0x00, (byte)0x01, (byte)0xE2, (byte)0x26, (byte)0x05, (byte)0x9B, (byte)0x00,
            (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x49, (byte)0x45, (byte)0x4E, (byte)0x44, (byte)0xAE,
            (byte)0x42, (byte)0x60, (byte)0x82
        };
    }

    @Operation(summary = "更新图片记录", description = "更新图片记录信息，支持部分字段更新")
    @PutMapping("/{id}")
    public Result<Image> updateImage(
            @Parameter(description = "图片ID") @PathVariable Long id,
            @RequestBody ImageUpdateRequest request) {
        try {
            Image existing = imageService.getImageById(id);
            if (existing == null) {
                return Result.error(404, "图片不存在");
            }

            Image updated = imageService.updateImage(id, request);
            log.info("更新图片记录成功: id={}", id);
            return Result.success("图片记录更新成功", updated);
        } catch (Exception e) {
            log.error("更新图片记录失败: {}", e.getMessage(), e);
            return Result.error(500, "更新图片记录失败: " + e.getMessage());
        }
    }

    @Operation(summary = "删除图片", description = "根据ID删除图片记录")
    @DeleteMapping("/{id}")
    public Result<Void> deleteImage(
            @Parameter(description = "图片ID") @PathVariable Long id) {
        try {
            Image existing = imageService.getImageById(id);
            if (existing == null) {
                return Result.error(404, "图片不存在");
            }

            boolean success = imageService.deleteImage(id);
            if (success) {
                log.info("删除图片成功: id={}", id);
                return Result.success("图片删除成功");
            } else {
                return Result.error(500, "删除图片失败");
            }
        } catch (Exception e) {
            log.error("删除图片失败: {}", e.getMessage(), e);
            return Result.error(500, "删除图片失败: " + e.getMessage());
        }
    }

    @Operation(summary = "批量删除图片", description = "根据ID列表批量删除图片")
    @DeleteMapping("/batch")
    public Result<Integer> batchDeleteImages(
            @Parameter(description = "图片ID列表") @RequestParam String ids) {
        try {
            List<Long> idList = Arrays.stream(ids.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Long::parseLong)
                    .collect(Collectors.toList());

            if (idList.isEmpty()) {
                return Result.error(400, "ID列表不能为空");
            }

            int deletedCount = imageService.batchDeleteImages(idList);
            log.info("批量删除图片成功: count={}", deletedCount);
            return Result.success("批量删除成功", deletedCount);
        } catch (NumberFormatException e) {
            return Result.error(400, "ID格式不正确，请提供逗号分隔的数字ID");
        } catch (Exception e) {
            log.error("批量删除图片失败: {}", e.getMessage(), e);
            return Result.error(500, "批量删除失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取图片统计", description = "获取图片统计信息，包括总数量、总大小、格式分布等")
    @GetMapping("/stats")
    public Result<ImageStatsResponse> getImageStats() {
        try {
            ImageStatsResponse response = imageService.getImageStats();
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取图片统计失败", e);
            return Result.error(500, "获取图片统计失败: " + e.getMessage());
        }
    }
}