package com.microservices.dms.utils;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTrPr;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ExportWordUtilCopy extends Component {

    public static void exportToWord(String outputPath,
                                                  List<Object[]> dataRows) throws Exception {
        // 1. 从classpath加载模板文件
        ClassLoader classLoader = ExportWordUtilCopy.class.getClassLoader();
        try (InputStream is = classLoader.getResourceAsStream("template.docx");
             XWPFDocument document = is != null ? new XWPFDocument(is) : null) {

            // 检查模板是否加载成功
            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, "迭代测试项共包含" + dataRows.size() + "个测试用例，相关用例概述如表5-2所示。");
            // 设置表格标题
            setTableCaption(document, "表5-2 迭代功能测试用例概述表");

            // 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);
                }
            }
            //5.添加表尾
            addFooter(document);
            // 4. 保存文档
            saveDocument(document, outputPath);
        }
        System.out.println("导出完成: " + outputPath);
    }

    // 设置表格标题
    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 addParagraph(XWPFDocument document, String text) {
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText(text);
    }

    // 添加带样式的表格行
    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 addNoDataRow(XWPFTable table) {
        XWPFTableRow newRow = table.createRow();
        XWPFTableCell cell = newRow.getCell(0);
        if (cell == null) return;

        cell.removeParagraph(0);
        XWPFParagraph para = cell.addParagraph();
        XWPFRun run = para.createRun();
        run.setText("查询结果为空");
        run.setBold(true);
        run.setColor("FF0000");
    }

    // 复制行样式
    private static void copyRowStyle(XWPFTableRow source, XWPFTableRow target) {
        // 复制行属性
        if (source.getCtRow().getTrPr() != null) {
            target.getCtRow().setTrPr((CTTrPr) source.getCtRow().getTrPr().copy());
        }

        // 复制单元格属性
        for (int i = 0; i < source.getTableCells().size(); i++) {
            XWPFTableCell sourceCell = source.getCell(i);
            XWPFTableCell targetCell = target.getCell(i);

            if (sourceCell != null && targetCell != null) {
                // 复制单元格属性
                if (sourceCell.getCTTc().getTcPr() != null) {
                    targetCell.getCTTc().setTcPr((CTTcPr) sourceCell.getCTTc().getTcPr().copy());
                }
            }
        }
    }

    private static void addDataRow(XWPFTable table, XWPFTableRow templateRow,
                                   Object[] rowData, int rowIndex) {
        XWPFTableRow newRow = table.createRow();

        // 复制基础行样式
        if (templateRow.getCtRow().getTrPr() != null) {
            newRow.getCtRow().setTrPr(templateRow.getCtRow().getTrPr());
        }

        // 确保单元格数量足够
        while (newRow.getTableCells().size() < rowData.length) {
            newRow.addNewTableCell();
        }

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

            cell.removeParagraph(0);
            XWPFParagraph para = cell.addParagraph();
            para.setAlignment(ParagraphAlignment.CENTER);

            XWPFRun run = para.createRun();
            run.setText(rowData[i] != null ? rowData[i].toString() : "NULL");
            run.setFontSize(10);
//            run.setFontFamily("宋体");
            // 特殊格式处理
            if (i == 0) {
                run.setBold(true); // 首列加粗
            }
        }
        // 进度提示
        if ((rowIndex + 1) % 100 == 0) {
            System.out.println("已处理 " + (rowIndex + 1) + " 行数据");
        }
    }

    private static void saveDocument(XWPFDocument document,String outputPath) throws Exception {
        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");
        }
    }
    private static void addDataTable(XWPFDocument document,
                                     List<Object[]> dataRows) {
        // 获取模板中的表格（假设第一个表格是模板）
        XWPFTable table = document.getTables().isEmpty() ?
                document.createTable() : document.getTables().get(0);

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

        // 3. 获取模板行（第一行）
        XWPFTableRow templateRow = table.getRow(0);
        if (templateRow == null) {
            throw new RuntimeException("模板行获取失败");
        }
        // 4. 处理数据
        System.out.println("待处理数据行数: " + dataRows.size());
        if (dataRows.isEmpty()) {
            System.out.println("警告: 无数据，添加提示行");
            addNoDataRow(table);
        } else {
            for (int i = 0; i < dataRows.size(); i++) {
                addDataRow(table, templateRow, dataRows.get(i), i);
            }
        }
    }

    // 添加标题
    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);
    }



    // 模拟数据库数据
    public static List<Object[]> mockData() {
        List<Object[]> data = new ArrayList<>();
        data.add(new Object[]{1, "GN_RJGC_XM_DD_XJDDGLQX", "新建迭代关联缺陷", "关联缺陷","正常"});
        data.add(new Object[]{2, "GN_RJGC_XM_DD_XJDDGLRW", "新建迭代关联任务", "关联任务","正常"});
        data.add(new Object[]{3, "GN_RJGC_XM_DD_XJDDGLXQ", "新建迭代关联需求", "关联需求","正常"});
        return data;
    }


    private File getExportDirectory(String locationType) {
        String userHome = System.getProperty("user.home");
        File exportDir;

        switch (locationType) {
            case "用户文档目录":
                exportDir = new File(userHome, "Documents");
                break;
            case "桌面":
                exportDir = new File(userHome, "Desktop");
                break;
            case "临时目录":
                exportDir = new File(System.getProperty("java.io.tmpdir"));
                break;
            case "自定义路径":
            default:
                JFileChooser chooser = new JFileChooser();
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int result = chooser.showSaveDialog(this);
                if (result == JFileChooser.APPROVE_OPTION) {
                    exportDir = chooser.getSelectedFile();
                } else {
                    exportDir = new File(userHome);
                }
                break;
        }

        // 确保目录存在
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }

        return exportDir;
    }

    private File getUniqueFile(File file) {
        if (!file.exists()) {
            return file;
        }

        String name = file.getName();
        String baseName = name.substring(0, name.lastIndexOf('.'));
        String extension = name.substring(name.lastIndexOf('.'));

        int counter = 1;
        File newFile;
        do {
            newFile = new File(file.getParentFile(), baseName + "(" + counter + ")" + extension);
            counter++;
        } while (newFile.exists());

        return newFile;
    }


    private static void addFooter(XWPFDocument document) {
        // 添加空行
        document.createParagraph();

        // 创建页脚段落
        XWPFParagraph footerPara = document.createParagraph();
        footerPara.setAlignment(ParagraphAlignment.CENTER);

        XWPFRun footerRun = footerPara.createRun();
        footerRun.setText("© 2023 数据导出系统 | 自动生成报告");
        footerRun.setFontSize(9);
        footerRun.setFontFamily("宋体");
        footerRun.setColor("7F7F7F");
        footerRun.setItalic(true);
    }


}
