package org.dromara.ai.controller.app;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.dromara.common.core.domain.R;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * PPT控制器
 * 提供智能PPT生成和导出功能
 *
 * @author pengles
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/ppt")
public class PptController {

    /**
     * 生成PPTX文件
     *
     * @param content 文本内容（按换行符分割为多页）
     * @param theme   主题（可选，暂未实现）
     * @return PPTX文件字节流
     */
    @Operation(summary = "生成PPTX", description = "根据文本内容生成PowerPoint演示文稿，每行内容作为一页")
    @PostMapping("/generate")
    public ResponseEntity<byte[]> generate(
            @Parameter(description = "文本内容") @RequestParam @NotBlank String content,
            @Parameter(description = "主题") @RequestParam(required = false) String theme) {
        try {
            log.info("开始生成PPTX，内容长度: {}", content.length());
            XMLSlideShow ppt = new XMLSlideShow();
            try {
                String[] parts = content.split("\\n+");
                if (parts.length == 0) parts = new String[]{content};
                for (String p : parts) {
                    XSLFSlide slide = ppt.createSlide();
                    slide.createTextBox().setText(p);
                }
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ppt.write(bos);
                byte[] bytes = bos.toByteArray();
                log.info("PPTX生成成功，文件大小: {} bytes，共{}页", bytes.length, parts.length);
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"generated.pptx\"")
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .body(bytes);
            } finally {
                ppt.close();
            }
        } catch (Exception e) {
            log.error("PPTX生成失败", e);
            String msg = "{\"code\":500,\"msg\":\"" + e.getMessage().replace("\"", "\\\"") + "\",\"data\":null}";
            return ResponseEntity.status(500)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(msg.getBytes(StandardCharsets.UTF_8));
        }
    }

    /**
     * 导出PNG图片序列
     *
     * @param content 文本内容
     * @param width   图片宽度（可选）
     * @param height  图片高度（可选）
     * @return Base64编码的PNG图片列表
     */
    @Operation(summary = "导出PNG序列", description = "将PPT内容导出为PNG图片序列，每页一张图片，返回Base64编码")
    @PostMapping("/export/pngs")
    public R<List<String>> exportPngs(
            @Parameter(description = "文本内容") @RequestParam @NotBlank String content,
            @Parameter(description = "宽度") @RequestParam(required = false) Integer width,
            @Parameter(description = "高度") @RequestParam(required = false) Integer height) {
        try {
            log.info("开始导出PNG序列，内容长度: {}, 尺寸: {}x{}", content.length(), width, height);
            XMLSlideShow ppt = new XMLSlideShow();
            try {
                String[] parts = content.split("\\n+");
                if (parts.length == 0) parts = new String[]{content};
                for (String p : parts) {
                    XSLFSlide slide = ppt.createSlide();
                    slide.createTextBox().setText(p);
                }
                Dimension pgsize = ppt.getPageSize();
                int w = width != null ? width : pgsize.width;
                int h = height != null ? height : pgsize.height;
                List<String> imgs = new ArrayList<>();
                for (XSLFSlide slide : ppt.getSlides()) {
                    BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
                    Graphics2D graphics = img.createGraphics();
                    graphics.setPaint(Color.WHITE);
                    graphics.fillRect(0, 0, w, h);
                    slide.draw(graphics);
                    graphics.dispose();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    javax.imageio.ImageIO.write(img, "png", bos);
                    String b64 = Base64.getEncoder().encodeToString(bos.toByteArray());
                    imgs.add("data:image/png;base64," + b64);
                }
                log.info("PNG序列导出成功，共{}张图片", imgs.size());
                return R.ok(imgs);
            } finally {
                ppt.close();
            }
        } catch (Exception e) {
            log.error("PNG序列导出失败", e);
            return R.fail("导出失败: " + e.getMessage());
        }
    }
}
