package com.microservices.dms.utils;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.awt.*;
import java.io.*;
import java.util.List;


public class ExportWordUtil extends Component {

    public static void exportToWord(String outputPath, List<Object[]> data) throws IOException {
        // 1. 从classpath加载模板文件
//        ClassLoader classLoader = ExportWordUtilCopy.class.getClassLoader();
//        try (InputStream is = classLoader.getResourceAsStream("template.docx");
//             XWPFDocument document = is != null ? new XWPFDocument(is) : null) {
            XWPFDocument document = new XWPFDocument();
            // 检查模板是否加载成功
            if (document == null) {
                throw new FileNotFoundException("模板文件未找到: template.docx");
            }
            // 添加5.1.1项目标题
            addTitle(document, "5.1.1项目", 1);
            // 添加迭代标题
            addTitle(document, "5.1.1.1迭代", 2);
            // 添加描述段落
            addParagraph(document, "迭代测试项共包含" + data.size() + "个测试用例，相关用例概述如表5-2所示。");
            // 设置表格标题
            setTableCaption(document, "表5-2 迭代功能测试用例概述表");
            // 创建表格-填充测试用例数据
//            setStyledTable(document,data);
            // 保存文档
            saveDocument(document, outputPath);
//        }

    }

    private static void saveDocument(XWPFDocument document,String outputPath) throws IOException {
        File outputFile = new File(outputPath);
        try (FileOutputStream out = new FileOutputStream(outputFile)) {
            document.write(out);
            System.out.println("文件保存成功: " + outputFile.getAbsolutePath());
            System.out.println("文件大小: " + outputFile.length() + " bytes");
        }
        document.close();
    }

    // 添加标题
    private static void addTitle(XWPFDocument document, String text, int level) {
        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setStyle("Heading" + level);
        XWPFRun run = paragraph.createRun();
        run.setText(text);
        run.setBold(true);
        run.setFontSize(20 - level * 2);
    }

    // 添加普通段落
    private static void addParagraph(XWPFDocument document, String text) {
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText(text);
    }

    // 设置表格标题
    private static void setTableCaption(XWPFDocument document, String caption) {
        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun run = paragraph.createRun();
        run.setText(caption);
        run.setItalic(true);
    }

    // 创建带样式的表格
    private static void setStyledTable(XWPFDocument document, List<Object[]> dataRows) throws IOException {
        // 3. 添加表格（保留模板样式）
        if (!dataRows.isEmpty()) {
            // 获取模板中的表格（假设第一个表格是模板）
            XWPFTable table = document.getTables().isEmpty() ?
                    document.createTable() : document.getTables().get(0);

            // 清空模板中原有的示例数据行（保留表头和样式行）
            while (table.getNumberOfRows() > 1) {
                table.removeRow(1);
            }

            // 获取样式模板行（通常是第一行）
            XWPFTableRow styleRow = table.getRow(0);

            // 添加数据行（保留样式）
            for (Object[] rowData : dataRows) {
                addStyledTableRow(table, styleRow, rowData);
            }
        }
    }
    // 添加带样式的表格行
    private static void addStyledTableRow(XWPFTable table,
                                          XWPFTableRow styleRow,
                                          Object[] rowData) {
        // 创建新行
        XWPFTableRow newRow = table.createRow();

        // 复制样式行的格式
        if (styleRow != null) {
            deepCopyStyle(styleRow, newRow);
        }

        // 填充数据
        for (int i = 0; i < rowData.length; i++) {
            XWPFTableCell cell = newRow.getCell(i);
            if (cell == null) {
                cell = newRow.addNewTableCell();
            }

            // 清空原有内容但保留样式
            cell.removeParagraph(0);
            XWPFParagraph para = cell.addParagraph();
            para.setAlignment(ParagraphAlignment.CENTER);

            // 添加数据
            XWPFRun run = para.createRun();
            run.setText(rowData[i] != null ? rowData[i].toString() : "");
            run.setFontSize(10);
            run.setFontFamily("宋体");
        }
    }

    // 深度复制样式（解决部分样式丢失问题）
    private static void deepCopyStyle(XWPFTableRow source, XWPFTableRow target) {
        CTRow ctSourceRow = source.getCtRow();
        CTRow ctTargetRow = target.getCtRow();

        // 复制行属性
        if (ctSourceRow.getTrPr() != null) {
            ctTargetRow.setTrPr((CTTrPr) ctSourceRow.getTrPr().copy());
        }

        // 复制单元格属性
        for (int i = 0; i < source.getTableCells().size(); i++) {
            CTTc sourceTc = source.getCell(i).getCTTc();
            CTTc targetTc = target.getCell(i).getCTTc();

            // 复制单元格属性
            if (sourceTc.getTcPr() != null) {
                targetTc.setTcPr((CTTcPr) sourceTc.getTcPr().copy());
            }

            // 复制段落样式
            if (!source.getCell(i).getParagraphs().isEmpty()) {
                XWPFParagraph sourcePara = source.getCell(i).getParagraphs().get(0);
                XWPFParagraph targetPara = target.getCell(i).getParagraphs().get(0);
                targetPara.getCTP().setPPr(sourcePara.getCTP().getPPr());
            }
        }
    }
    // 填充表头
    private static void fillTableHeader(XWPFTable table, String[] headers) {
        XWPFTableRow headerRow = table.getRow(0);
        for (int i = 0; i < headers.length; i++) {
            XWPFTableCell cell = headerRow.getCell(i);
            cell.removeParagraph(0);
            XWPFParagraph para = cell.addParagraph();
            para.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun run = para.createRun();
            run.setText(headers[i]);
            run.setBold(true);

            // 设置表头背景色
            CTShd shd = cell.getCTTc().addNewTcPr().addNewShd();
            shd.setFill("D3D3D3");
        }
    }



    private static void setCellText(XWPFTableRow row, int col, String text) {
        XWPFTableCell cell = row.getCell(col);
        cell.removeParagraph(0);
        XWPFParagraph para = cell.addParagraph();
        para.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun run = para.createRun();
        run.setText(text);
    }
}
