package com.ruoyi.web.common.service.impl;

import com.ruoyi.web.common.model.ExportField;
import com.ruoyi.web.common.model.MultiLevelHeader;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MultiLevelHeaderServiceImpl {

    /**
     * 重新构建多级表头结构 - 修复版本
     */
    public List<MultiLevelHeader> buildMultiLevelHeaders(List<ExportField> selectedFields) {
        // 首先构建完整的树形结构
        List<ExportField> rootFields = buildTreeStructure(selectedFields);

        // 计算每个节点的列跨度
        calculateColumnSpan(rootFields);

        // 转换为多级表头
        return convertToMultiLevelHeaders(rootFields, 0, 0);
    }

    /**
     * 构建树形结构
     */
    private List<ExportField> buildTreeStructure(List<ExportField> allFields) {
        // 找出所有根节点（level=0）
        List<ExportField> rootFields = allFields.stream()
                .filter(field -> field.getLevel() == 0)
                .sorted(Comparator.comparingInt(ExportField::getOrder))
                .collect(Collectors.toList());

        // 为每个根节点构建子树
        for (ExportField root : rootFields) {
            buildChildren(root, allFields);
        }

        return rootFields;
    }

    /**
     * 递归构建子节点
     */
    private void buildChildren(ExportField parent, List<ExportField> allFields) {
        if (!parent.isHasChildren()) {
            return;
        }

        List<ExportField> children = allFields.stream()
                .filter(field -> parent.getFieldName().equals(field.getParent()))
                .sorted(Comparator.comparingInt(ExportField::getOrder))
                .collect(Collectors.toList());

        parent.setChildren(children);

        for (ExportField child : children) {
            buildChildren(child, allFields);
        }
    }

    /**
     * 计算每个节点的列跨度
     */
    private int calculateColumnSpan(List<ExportField> fields) {
        int totalSpan = 0;
        for (ExportField field : fields) {
            if (field.isHasChildren() && !field.getChildren().isEmpty()) {
                int childSpan = calculateColumnSpan(field.getChildren());
                field.setColumnSpan(childSpan);
                totalSpan += childSpan;
            } else {
                field.setColumnSpan(1);
                totalSpan += 1;
            }
        }
        return totalSpan;
    }

    /**
     * 转换为多级表头
     */
    private List<MultiLevelHeader> convertToMultiLevelHeaders(List<ExportField> fields, int level, int startCol) {
        List<MultiLevelHeader> headers = new ArrayList<>();
        int currentCol = startCol;

        for (ExportField field : fields) {
            MultiLevelHeader header = new MultiLevelHeader();
            header.setHeaderName(field.getColumnName());
            header.setLevel(level);
            header.setStartCol(currentCol);

            if (field.isHasChildren() && !field.getChildren().isEmpty()) {
                // 有子节点，递归处理
                List<MultiLevelHeader> childHeaders = convertToMultiLevelHeaders(
                        field.getChildren(), level + 1, currentCol);
                header.setChildren(childHeaders);

                int span = field.getColumnSpan();
                header.setEndCol(currentCol + span - 1);
                currentCol += span;
            } else {
                // 叶子节点
                header.setEndCol(currentCol);
                header.setChildren(new ArrayList<>());
                currentCol++;
            }

            headers.add(header);
        }

        return headers;
    }

    /**
     * 获取所有叶子节点（实际数据列）
     */
    public List<ExportField> getLeafFields(List<ExportField> selectedFields) {
        List<ExportField> rootFields = buildTreeStructure(selectedFields);
        List<ExportField> leafFields = new ArrayList<>();
        extractLeafFields(rootFields, leafFields);
        return leafFields;
    }

    private void extractLeafFields(List<ExportField> fields, List<ExportField> leafFields) {
        for (ExportField field : fields) {
            if (field.isHasChildren() && !field.getChildren().isEmpty()) {
                extractLeafFields(field.getChildren(), leafFields);
            } else {
                leafFields.add(field);
            }
        }
    }

    /**
     * 计算总行数（最大层级+1）
     */
    public int calculateTotalRows(List<MultiLevelHeader> headers) {
        if (headers == null || headers.isEmpty()) {
            return 0;
        }
        return calculateMaxLevel(headers) + 1;
    }

    private int calculateMaxLevel(List<MultiLevelHeader> headers) {
        int maxLevel = 0;
        for (MultiLevelHeader header : headers) {
            maxLevel = Math.max(maxLevel, header.getLevel());
            if (!header.getChildren().isEmpty()) {
                maxLevel = Math.max(maxLevel, calculateMaxLevel(header.getChildren()));
            }
        }
        return maxLevel;
    }

    /**
     * 打印表头结构（用于调试）
     */
    public void printHeaderStructure(List<MultiLevelHeader> headers) {
        System.out.println("=== 多级表头结构 ===");
        printHeaders(headers, 0);
    }

    private void printHeaders(List<MultiLevelHeader> headers, int indent) {
        String prefix = StringUtils.repeat("  ",indent);
        for (MultiLevelHeader header : headers) {
            System.out.println(prefix + header.getHeaderName() +
                    " [列:" + header.getStartCol() + "-" + header.getEndCol() +
                    ", 层级:" + header.getLevel() + "]");
            if (!header.getChildren().isEmpty()) {
                printHeaders(header.getChildren(), indent + 1);
            }
        }
    }
}
