package com.gxwebsoft.ai.controller;

import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.ai.dto.AuditEvidenceRequest;
import com.gxwebsoft.ai.service.AuditEvidenceService;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import java.util.ArrayList;
import java.util.List;

import com.gxwebsoft.ai.config.TemplateConfig;
import cn.afterturn.easypoi.word.WordExportUtil;

/**
 * 审计取证单控制器
 */
@Slf4j
@Tag(name = "审计取证单")
@RestController
@RequestMapping("/api/ai/auditEvidence")
public class AuditEvidenceController extends BaseController {

    @Autowired
    private AuditEvidenceService auditEvidenceService;
    
    @Autowired
    private TemplateConfig templateConfig;

    /**
     * 生成审计取证单
     */
    @Operation(summary = "生成审计取证单")
    @PostMapping("/generate")
    public ApiResult<?> generateAuditEvidence(@RequestBody AuditEvidenceRequest request) {
        try {
        	final User loginUser = getLoginUser();
        	request.setUserName(loginUser.getUsername());
        	
            log.info("接收到审计取证单生成请求 - 用户: {}, 项目: {}", request.getUserName(), request.getProjectName());
            JSONObject result = auditEvidenceService.generateAuditEvidence(request);
            if (Boolean.TRUE.equals(result.getBoolean("success"))) {
                return success(result);
            } else {
                return fail(result.getString("error") != null ? result.getString("error") : "生成审计取证单失败");
            }
        } catch (Exception e) {
            log.error("生成审计取证单异常", e);
            return fail("生成审计取证单异常: " + e.getMessage());
        }
    }
    
    /**
     * 下载审计取证单Word文档
     */
    @Operation(summary = "下载审计取证单Word文档")
    @PostMapping("/download")
    public void downloadAuditEvidence(@RequestBody AuditEvidenceRequest request, HttpServletResponse response) {
        double originalMinInflateRatio = ZipSecureFile.getMinInflateRatio();
        
        try {
            ZipSecureFile.setMinInflateRatio(0.001);
            
            // 准备模板数据 - 将取证单字段映射到Word模板
            Map<String, Object> map = new HashMap<>();
//            map.put("caseIndex", request.getCaseIndex() != null ? request.getCaseIndex() : "");
            map.put("caseIndex", request.getCaseIndex() != null ? String.format("%-50s", request.getCaseIndex()) : String.format("%-50s", ""));
            map.put("pageIndex", request.getPageIndex() != null ? request.getPageIndex() : "1");
            map.put("pageTotal", request.getPageTotal() != null ? request.getPageTotal() : "1");
            map.put("projectName", request.getProjectName() != null ? request.getProjectName() : "");
            map.put("auditedTarget", request.getAuditedTarget() != null ? request.getAuditedTarget() : "");
            map.put("auditMatter", request.getAuditMatter() != null ? request.getAuditMatter() : "");
            map.put("summaryTitle", request.getSummaryTitle() != null ? request.getSummaryTitle() : "");
            map.put("auditRecord", request.getAuditRecord() != null ? request.getAuditRecord() : "");
            map.put("auditFinding", request.getAuditFinding() != null ? request.getAuditFinding() : "");
            map.put("evidenceBasis", request.getEvidenceBasis() != null ? request.getEvidenceBasis() : "");
            map.put("handling", request.getHandling() != null ? request.getHandling() : "");
            map.put("attachment", request.getAttachment() != null ? request.getAttachment() : "");
            map.put("auditors", request.getAuditors() != null ? request.getAuditors() : "");
            map.put("compileDate", request.getCompileDate() != null ? request.getCompileDate() : "");
            map.put("providerOpinion", request.getProviderOpinion() != null ? request.getProviderOpinion() : "");
            map.put("providerDate", request.getProviderDate() != null ? request.getProviderDate() : "");
            map.put("attachmentPages", request.getAttachmentPages() != null ? request.getAttachmentPages() : "");
            map.put("feedbackDeadline", request.getFeedbackDeadline() != null ? request.getFeedbackDeadline() : "");
            
            // 获取登录用户信息
            final User loginUser = getLoginUser();
            if (request.getAuditors() == null || request.getAuditors().isEmpty()) {
                map.put("auditors", loginUser.getUsername());
            }
            
            // 使用 Easypoi 的 Word 模板功能生成取证单
            XWPFDocument document = WordExportUtil.exportWord07(
                templateConfig.getEvidenceTemplatePath(), // 需要配置取证单模板路径
                map
            );
            
            // 处理换行，确保 \n 转为硬回车（新段落）
            processParagraphs(document);
            
            // 设置响应头
            String fileName = "审计取证单_" + (request.getProjectName() != null ? request.getProjectName() : "取证单") + ".docx";
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
            
            // 输出文档
            try (OutputStream out = response.getOutputStream()) {
                document.write(out);
                out.flush();
            }
            
        } catch (Exception e) {
            log.error("生成审计取证单Word文档失败", e);
            throw new RuntimeException("生成审计取证单失败", e);
        } finally {
            ZipSecureFile.setMinInflateRatio(originalMinInflateRatio);
        }
    }
    
    /**
     * 处理段落换行（增强版，同时处理表格单元格）
     */
    private void processParagraphs(XWPFDocument document) {
        // 1. 处理普通段落
        List<XWPFParagraph> originalParas = new ArrayList<>(document.getParagraphs());
        
        for (XWPFParagraph para : originalParas) {
            String text = para.getText();
            if (text == null || !text.contains("\n")) {
                continue;
            }
            
            String[] parts = text.replace("\r\n", "\n").replace("\r", "\n").split("\n");
            
            // 在原段落位置之前插入新段落
            int pos = document.getPosOfParagraph(para);
            
            // 修正：按正序插入（从前往后）
            for (int i = 0; i < parts.length; i++) {
                // 创建新段落
                XWPFParagraph newPara = document.insertNewParagraph(para.getCTP().newCursor());
                
                // 复制样式
                newPara.getCTP().setPPr(para.getCTP().getPPr());
                
                XWPFRun newRun = newPara.createRun();
                newRun.setText(parts[i].trim());
                
                if (!para.getRuns().isEmpty()) {
                    newRun.getCTR().setRPr(para.getRuns().get(0).getCTR().getRPr());
                }
            }
            
            // 删除原段落
            document.removeBodyElement(pos + parts.length);
        }
        
        // 2. 处理表格单元格中的段落
        List<XWPFTable> tables = document.getTables();
        for (XWPFTable table : tables) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    List<XWPFParagraph> cellParagraphs = cell.getParagraphs();
                    for (XWPFParagraph para : cellParagraphs) {
                        String text = para.getText();
                        if (text == null || !text.contains("\n")) {
                            continue;
                        }
                        
                        // 清空原段落内容
                        for (int i = para.getRuns().size() - 1; i >= 0; i--) {
                            para.removeRun(i);
                        }
                        
                        // 分割文本并按行添加
                        String[] lines = text.replace("\r\n", "\n").replace("\r", "\n").split("\n");
                        for (int i = 0; i < lines.length; i++) {
                            XWPFRun run = para.createRun();
                            run.setText(lines[i].trim());
                            
                            // 如果不是最后一行，添加换行
                            if (i < lines.length - 1) {
                                run.addBreak();
                            }
                        }
                    }
                }
            }
        }
    }
}
