package com.zcloud.fire.check.domain.utils;


import com.zcloud.fire.check.domain.model.DepartmentE;

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

/**
 * @author SondonYong
 * @description
 * @date 2025/12/12/周五 15:29
 */
public class DepartmentPathUtil {

    /**
     * 构建部门路径映射
     * @param departmentList 部门列表
     * @return Map<部门路径, 部门对象>
     */
    public static Map<String, DepartmentE> buildDepartmentPathMap(List<DepartmentE> departmentList) {
        if (departmentList == null || departmentList.isEmpty()) {
            return new HashMap<>();
        }

        // 创建id到部门的映射
        Map<Long, DepartmentE> idToDepartmentMap = departmentList.stream()
                .collect(Collectors.toMap(
                        DepartmentE::getId,
                        dept -> dept,
                        (existing, replacement) -> existing
                ));

        // 创建结果映射
        Map<String, DepartmentE> result = new HashMap<>();

        for (DepartmentE department : departmentList) {
            String path = buildDepartmentPath(department, idToDepartmentMap);
            result.put(path, department);
        }

        return result;
    }

    /**
     * 构建单个部门的完整路径
     * @param department 当前部门
     * @param idToDepartmentMap ID到部门的映射
     * @return 部门路径字符串
     */
    private static String buildDepartmentPath(DepartmentE department, Map<Long, DepartmentE> idToDepartmentMap) {
        List<String> pathNames = new ArrayList<>();
        DepartmentE current = department;

        // 向上遍历父部门，直到根节点
        while (current != null) {
            pathNames.add(0, current.getName()); // 在列表头部添加，保持顺序
            Long parentId = current.getParentId();

            // 如果没有父ID或父部门不在列表中，结束遍历
            if (parentId == null || !idToDepartmentMap.containsKey(parentId)) {
                break;
            }

            current = idToDepartmentMap.get(parentId);
        }

        // 使用连字符连接路径
        return String.join("=", pathNames);
    }


// ------------------------------------------------------------------------------------
    /**
     * 构建部门ID到名称路径的映射
     * 格式：上级部门-当前部门
     * 示例：A-B, A-B-D
     *
     * @param departmentList 部门列表
     * @return Map<部门ID, 部门完整路径>
     */
    public static Map<Long, String> buildDepartmentIdToPathMap(List<DepartmentE> departmentList) {
        if (departmentList == null || departmentList.isEmpty()) {
            return new HashMap<>();
        }

        // 创建ID到部门的映射，便于快速查找
        Map<Long, DepartmentE> idToDeptMap = departmentList.stream()
                .collect(Collectors.toMap(
                        DepartmentE::getId,
                        dept -> dept,
                        (existing, replacement) -> existing
                ));

        // 缓存已计算的路径，避免重复计算
        Map<Long, String> pathCache = new HashMap<>();

        // 结果映射：部门ID -> 完整路径
        Map<Long, String> result = new HashMap<>();

        for (DepartmentE department : departmentList) {
            String path = buildPathForDepartment(department.getId(), idToDeptMap, pathCache);
            result.put(department.getId(), path);
        }

        return result;
    }

    /**
     * 为指定部门构建完整路径（递归实现）
     *
     * @param departmentId 当前部门ID
     * @param idToDeptMap ID到部门的映射
     * @param pathCache 路径缓存
     * @return 完整路径字符串
     */
    private static String buildPathForDepartment(Long departmentId,
                                                 Map<Long, DepartmentE> idToDeptMap,
                                                 Map<Long, String> pathCache) {
        // 检查缓存
        if (pathCache.containsKey(departmentId)) {
            return pathCache.get(departmentId);
        }

        DepartmentE department = idToDeptMap.get(departmentId);
        if (department == null) {
            return "";
        }

        // 获取部门名称（处理可能的空值）
        String departmentName = department.getName() != null ? department.getName() : "";

        // 如果没有父部门或父部门不在列表中，返回当前部门名称
        Long parentId = department.getParentId();
        if (parentId == null || !idToDeptMap.containsKey(parentId)) {
            String path = departmentName;
            pathCache.put(departmentId, path);
            return path;
        }

        // 递归构建父部门路径
        String parentPath = buildPathForDepartment(parentId, idToDeptMap, pathCache);

        // 拼接完整路径
        String fullPath;
        if (parentPath.isEmpty()) {
            fullPath = departmentName;
        } else {
            fullPath = parentPath + "=" + departmentName;
        }

        // 缓存结果
        pathCache.put(departmentId, fullPath);

        return fullPath;
    }

}
