package com.ruoyi.cms.util;

import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.core.domain.entity.Industry;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工具类：读取 Excel 并构建树结构
 */
public class IndustryUtils {

    /**
     * 读取 Excel 文件并转换为 Industry 列表
     */
    public static List<Industry> readExcel(String filePath) {
        // 读取 Excel 文件
        List<IndustryExcel> excelDataList = EasyExcel.read(filePath)
                .head(IndustryExcel.class)
                .sheet()
                .doReadSync();

        // 构建树结构
        return buildTree(excelDataList);
    }

    /**
     * 构建树结构
     */
    private static List<Industry> buildTree(List<IndustryExcel> excelDataList) {
        Map<String, Industry> level1Map = new HashMap<>(); // 一级分类缓存
        List<Industry> result = new ArrayList<>(); // 最终结果

        long industryId = 1; // 自增 ID

        for (IndustryExcel excelData : excelDataList) {
            // 处理一级分类（可能有多个，用逗号分隔）
            String[] level1Names = excelData.getLevel1().split(",");
            for (String level1Name : level1Names) {
                Industry level1 = level1Map.get(level1Name.trim());
                if (level1 == null) {
                    level1 = new Industry();
                    level1.setIndustryId(industryId++);
                    level1.setIndustryName(level1Name.trim());
                    level1.setParentId(0L); // 根节点
                    level1Map.put(level1Name.trim(), level1);
                    result.add(level1);
                }

                // 处理二级分类
                Industry level2 = new Industry();
                level2.setIndustryId(industryId++);
                level2.setIndustryName(excelData.getLevel2());
                level2.setParentId(level1.getIndustryId()); // 父节点为一级分类
                level1.getChildren().add(level2);
            }
        }

        return result;
    }
}