package com.gxwebsoft.ai.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.ai.service.AuditReportService;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * 审计报告控制器 - 重构版
 */
@Tag(name = "审计报告")
@RestController
@RequestMapping("/api/ai/auditReport2")
public class AuditReportController2 extends BaseController {
    
    @Autowired
    private AuditReportService auditReportService;
    
    /**
     * 生成审计核查报告 - 重构版
     */
    @Operation(summary = "生成审计核查报告")
    @PostMapping("/generate")
    public ApiResult<?> generateAuditReport(
            @RequestPart("file") MultipartFile file,
            @RequestPart(value = "kbId", required = false) String kbId,
            @RequestPart(value = "libraryIds", required = false) String libraryIds,
            @RequestPart(value = "analysisLibrary", required = false) String analysisLibrary,
            @RequestPart(value = "projectLibrary", required = false) String projectLibrary) {
        
        final User loginUser = getLoginUser();
        try {
            // 1. 解析文件五、六点内容
            String auditContent = extractAuditContent(file);
            if (StrUtil.isBlank(auditContent)) {
                return fail("未能提取到审计内容");
            }
            
            // 2. 生成完整审计报告
            JSONObject auditReport = auditReportService.generateCompleteAuditReport(
                auditContent, file.getOriginalFilename(), kbId, libraryIds, 
                analysisLibrary, projectLibrary, loginUser.getUsername()
            );
            
            return success(auditReport);
            
        } catch (Exception e) {
            return fail("生成审计报告失败: " + e.getMessage());
        }
    }
    
    /**
     * 提取审计内容（五、六点）
     */
    private String extractAuditContent(MultipartFile file) throws IOException {
        StringBuilder content = new StringBuilder();
        
        // 保存原来的最小解压比率
        double originalMinInflateRatio = ZipSecureFile.getMinInflateRatio();
        // 设置新的最小解压比率
        ZipSecureFile.setMinInflateRatio(0.001);

        try (InputStream is = file.getInputStream();
             XWPFDocument doc = new XWPFDocument(is)) {
            
            boolean inSection5 = false;
            boolean inSection6 = false;
            
            for (XWPFParagraph para : doc.getParagraphs()) {
                String text = para.getText();
                if (StrUtil.isBlank(text)) continue;
                
                // 检测第五部分
                if (text.contains("五、") || text.contains("5、")) {
                    inSection5 = true;
                    inSection6 = false;
                    content.append("【第五部分】\n");
                    continue;
                }
                
                // 检测第六部分  
                if (text.contains("六、") || text.contains("6、")) {
                    inSection5 = false;
                    inSection6 = true;
                    content.append("【第六部分】\n");
                    continue;
                }
                
                // 检测结束
                if ((text.contains("七、") || text.contains("7、")) && inSection6) {
                    break;
                }
                
                // 收集内容
                if (inSection5 || inSection6) {
                    content.append(text).append("\n");
                }
            }
        } finally {
            // 恢复原来的最小解压比率
            ZipSecureFile.setMinInflateRatio(originalMinInflateRatio);
        }
        
        return content.toString();
    }
}