package com.hotent.util.wordexcelutils;/**
 * @program: cbjs-mvue-master
 * @description:
 * @author: zhao yue yue
 * @create: 2025-12-03 18:01
 */
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import javax.xml.namespace.QName;
import java.util.*;
import java.io.*;
import java.math.BigInteger;
/**
 *@author: zhao yue yue
 *@create: 2025-12-03 18:01
 */
public class TableWidthEnforcer {

    /**
     * 强制表格宽度生效（最可靠的方法）
     */
    public static void enforceTableWidth(XWPFTable table, int totalWidthPercent) {
        if (table == null) return;

        System.out.println("强制表格宽度生效: " + totalWidthPercent + "%");

        try {
            // 1. 设置表格整体宽度
            setTableWidthDirectly(table, totalWidthPercent);

            // 2. 设置表格布局为固定
            setTableLayoutFixed(table);

            // 3. 设置表格样式
            setTableGridStyle(table);

            // 4. 设置列宽
            distributeColumnWidths(table, totalWidthPercent);

            // 5. 验证宽度设置
            verifyWidthSettings(table);

            System.out.println("✅ 表格宽度强制生效完成");

        } catch (Exception e) {
            System.err.println("强制宽度失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 直接设置表格宽度（XML级别）
     */
    private static void setTableWidthDirectly(XWPFTable table, int percent) {
        try {
            CTTbl ctTbl = table.getCTTbl();
            CTTblPr tblPr = ctTbl.getTblPr();
            if (tblPr == null) {
                tblPr = ctTbl.addNewTblPr();
            }

            // 清除现有的宽度设置
            if (tblPr.isSetTblW()) {
                tblPr.unsetTblW();
            }

            // 创建新的宽度设置
            CTTblWidth tblWidth = tblPr.addNewTblW();
            tblWidth.setType(STTblWidth.PCT);  // 使用百分比
            tblWidth.setW(BigInteger.valueOf(percent * 50)); // 百分比值 * 50

            System.out.println("表格宽度设置为: " + percent + "% (" + (percent * 50) + "单位)");

        } catch (Exception e) {
            throw new RuntimeException("设置表格宽度失败", e);
        }
    }

    /**
     * 设置表格布局为固定
     */
    private static void setTableLayoutFixed(XWPFTable table) {
        try {
            CTTbl ctTbl = table.getCTTbl();
            CTTblPr tblPr = ctTbl.getTblPr();
            if (tblPr == null) {
                tblPr = ctTbl.addNewTblPr();
            }

            // 设置布局类型为固定
            CTTblLayoutType layoutType = tblPr.isSetTblLayout() ?
                    tblPr.getTblLayout() : tblPr.addNewTblLayout();
            layoutType.setType(STTblLayoutType.FIXED);  // 关键：FIXED

            System.out.println("表格布局设置为: FIXED");

        } catch (Exception e) {
            System.err.println("设置表格布局失败: " + e.getMessage());
        }
    }

    /**
     * 设置表格样式为TableGrid
     */
    private static void setTableGridStyle(XWPFTable table) {
        try {
            CTTbl ctTbl = table.getCTTbl();
            CTTblPr tblPr = ctTbl.getTblPr();
            if (tblPr == null) {
                tblPr = ctTbl.addNewTblPr();
            }

            // 设置表格样式
            CTString style = tblPr.isSetTblStyle() ?
                    tblPr.getTblStyle() : tblPr.addNewTblStyle();
            style.setVal("TableGrid");

            System.out.println("表格样式设置为: TableGrid");

        } catch (Exception e) {
            System.err.println("设置表格样式失败: " + e.getMessage());
        }
    }

    /**
     * 分配列宽
     */
    private static void distributeColumnWidths(XWPFTable table, int totalWidthPercent) {
        if (table.getRows().isEmpty()) return;

        XWPFTableRow firstRow = table.getRow(0);
        int columnCount = firstRow.getTableCells().size();

        System.out.println("分配 " + columnCount + " 列的宽度");

        // 为成本核定表设计的列宽比例
        int[] columnPercentages = getCostTableColumnPercentages(columnCount);

        // 应用到所有行
        for (XWPFTableRow row : table.getRows()) {
            for (int i = 0; i < Math.min(row.getTableCells().size(), columnCount); i++) {
                setColumnWidth(row.getTableCells().get(i), columnPercentages[i]);
            }
        }
    }

    /**
     * 获取成本核定表的列宽比例
     */
    private static int[] getCostTableColumnPercentages(int columnCount) {
        if (columnCount == 5) { // 成本项目 + 行次 + 3个年份
            return new int[]{30, 10, 20, 20, 20}; // 百分比
        } else if (columnCount == 6) { // 成本项目 + 行次 + 4个年份
            return new int[]{25, 10, 16, 16, 16, 16};
        } else if (columnCount == 4) { // 成本项目 + 行次 + 2个年份
            return new int[]{35, 10, 27, 27};
        } else {
            // 默认均匀分配
            int[] percentages = new int[columnCount];
            int base = 100 / columnCount;
            for (int i = 0; i < columnCount; i++) {
                percentages[i] = base;
            }
            return percentages;
        }
    }

    /**
     * 设置列宽（XML级别）
     */
    private static void setColumnWidth(XWPFTableCell cell, int percentage) {
        try {
            CTTc ctTc = cell.getCTTc();
            CTTcPr tcPr = ctTc.getTcPr();
            if (tcPr == null) {
                tcPr = ctTc.addNewTcPr();
            }

            // 清除现有的宽度设置
            if (tcPr.isSetTcW()) {
                tcPr.unsetTcW();
            }

            // 设置新的宽度
            CTTblWidth tcWidth = tcPr.addNewTcW();
            tcWidth.setType(STTblWidth.PCT);  // 百分比
            tcWidth.setW(BigInteger.valueOf(percentage * 50)); // 百分比 * 50

            // 设置单元格无自动换行
            CTOnOff noWrap = tcPr.isSetNoWrap() ? tcPr.getNoWrap() : tcPr.addNewNoWrap();
            noWrap.setVal(STOnOff.ON);

        } catch (Exception e) {
            System.err.println("设置列宽失败: " + e.getMessage());
        }
    }

    /**
     * 验证宽度设置
     */
    private static void verifyWidthSettings(XWPFTable table) {
        try {
            CTTbl ctTbl = table.getCTTbl();
            CTTblPr tblPr = ctTbl.getTblPr();

            System.out.println("\n=== 宽度设置验证 ===");

            // 验证表格宽度
            if (tblPr != null && tblPr.getTblW() != null) {
                CTTblWidth tblWidth = tblPr.getTblW();
                System.out.println("表格宽度类型: " + tblWidth.getType());
                System.out.println("表格宽度值: " + tblWidth.getW());
            } else {
                System.out.println("❌ 表格无宽度设置");
            }

            CTTblLayoutType layout = tblPr.isSetTblLayout() ? tblPr.getTblLayout() : tblPr.addNewTblLayout();
            layout.setType(STTblLayoutType.AUTOFIT);
            // 验证表格布局
            if (tblPr != null && tblPr.getTblLayout() != null) {
                System.out.println("表格布局: " + tblPr.getTblLayout().getType());
            }

            // 验证第一行单元格宽度
            if (!table.getRows().isEmpty()) {
                XWPFTableRow firstRow = table.getRow(0);
                System.out.println("第一行列数: " + firstRow.getTableCells().size());

                for (int i = 0; i < firstRow.getTableCells().size(); i++) {
                    XWPFTableCell cell = firstRow.getTableCells().get(i);
                    CTTc ctTc = cell.getCTTc();
                    if (ctTc.getTcPr() != null && ctTc.getTcPr().getTcW() != null) {
                        CTTblWidth cellWidth = ctTc.getTcPr().getTcW();
                        System.out.println("  列" + (i+1) + "宽度: " + cellWidth.getW() + " (" + cellWidth.getType() + ")");
                    } else {
                        System.out.println("  列" + (i+1) + ": 无宽度设置");
                    }
                }
            }

        } catch (Exception e) {
            System.err.println("验证失败: " + e.getMessage());
        }
    }

}
