package com.storlead.system.controller;

import com.storlead.framework.web.properties.FileProperties;
import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;
import javax.annotation.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2025-08-11 11:11
 */
@RestController
@RequestMapping("/view")
@Api(tags = "平台中心 - 系统: 图片显示")
@Log4j2
public class ThumbnailPreviewController {

    @Resource
    private FileProperties fileProperties;

    @GetMapping("/thumbnail")
    public ResponseEntity<byte[]> thumbnail(@RequestParam String url) throws Exception {

        try {
            // 1. 构建文件路径
            String fileUrl = fileProperties.getPath().getPath() + url;
            String normalizedPath = fileUrl.replace('/', File.separatorChar)
                    .replace('\\', File.separatorChar);

            // 2. 读取原始图片
            BufferedImage originalImage = ImageIO.read(new File(normalizedPath));
            if (originalImage == null) {
                return ResponseEntity.notFound().build();
            }
            // 3. 压缩图片
            byte[] compressedImage = compressImage(originalImage, 0.2f);
            // 5. 返回压缩后的图片流
            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(compressedImage);

        } catch (Exception e) {
            log.error("thumbnail error", e);
            return ResponseEntity.notFound().build();
        }
    }

    private byte[] compressImage(BufferedImage image, float quality) throws IOException {
        ByteArrayOutputStream compressed = new ByteArrayOutputStream();

        // 获取JPEG编码器
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
        if (!writers.hasNext()) {
            throw new IllegalStateException("不支持JPEG编码");
        }

        ImageWriter writer = writers.next();
        try (ImageOutputStream ios = ImageIO.createImageOutputStream(compressed)) {
            writer.setOutput(ios);

            // 设置压缩参数
            ImageWriteParam param = writer.getDefaultWriteParam();
            if (param.canWriteCompressed()) {
                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                param.setCompressionQuality(quality); // 设置压缩质量 (0.0-1.0)
            }

            // 写入压缩后的图片
            writer.write(null, new IIOImage(image, null, null), param);
        } finally {
            writer.dispose();
        }

        return compressed.toByteArray();
    }

    private String getCleanFileName(String path) {
        int lastSeparator = path.lastIndexOf(File.separatorChar);
        String fileName = (lastSeparator >= 0) ? path.substring(lastSeparator + 1) : path;

        int lastDot = fileName.lastIndexOf('.');
        if (lastDot > 0) {
            int secondLastDot = fileName.lastIndexOf('.', lastDot - 1);
            if (secondLastDot > 0) {
                return fileName.substring(0, lastDot);
            }
        }
        return fileName;
    }

    private MediaType determineContentType(String fileName) {
        if (fileName.toLowerCase().endsWith(".png")) {
            return MediaType.IMAGE_PNG;
        } else if (fileName.toLowerCase().endsWith(".gif")) {
            return MediaType.IMAGE_GIF;
        }
        return MediaType.IMAGE_JPEG;
    }

}
