package com.sundot.airport.web.controller.quality;

import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.AjaxResult;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.enums.DeptTypeEnum;
import com.sundot.airport.common.utils.DeptUtils;
import com.sundot.airport.item.domain.dto.QualificationLevelStatsDTO;
import com.sundot.airport.system.domain.QualificationLevelConverter;
import com.sundot.airport.system.domain.portrait.QualificationStats;
import com.sundot.airport.system.mapper.portrait.QualificationLevelIndicatorMapper;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.ISysPostService;
import com.sundot.airport.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 资质等级统计控制器
 * 提供资质等级统计的API接口
 *
 * @author wangxx
 */
@Api(tags = "资质等级统计")
@RestController
@RequestMapping("/statistics/qualification")
public class QualificationLevelStatsController extends BaseController {

    @Autowired
    private QualificationLevelIndicatorMapper qualificationLevelMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysPostService sysPostService;


    /**
     * 固定的资质等级列表（初级、中级、高级）
     */
    private static final List<String> QUALIFICATION_LEVELS = Arrays.asList(
            "初级", "中级", "高级"
    );

    /**
     * 获取饼状图数据（资质等级分布）
     * 支持按部门 ID、用户 ID 进行统计
     */
    @ApiOperation("获取饼状图数据")
    @GetMapping("/pie-chart")
    public AjaxResult getPieChartData(
            @RequestParam(required = false) Long deptId) {

        try {
            List<Long> targetUserIds;

            if (deptId != null) {
                // 按部门（大队/科室/班组）统计
                targetUserIds = getAllUserIdsUnderDept(deptId);
            } else {
                // 默认按全站统计
                Long topSiteId = DeptUtils.getTopSiteId(sysDeptService.selectDeptById(getDeptId()));
                if (topSiteId == null) {
                    return AjaxResult.error("无法找到有效的站点信息");
                }
                targetUserIds = getAllUserIdsUnderSite(topSiteId);
            }

            if (targetUserIds.isEmpty()) {
                return AjaxResult.success("获取成功", new QualificationLevelStatsDTO.PieChartData());
            }

            QualificationLevelStatsDTO.PieChartData pieChart = calculatePieChartData(targetUserIds);
            return AjaxResult.success("获取成功", pieChart);

        } catch (Exception e) {
            logger.error("获取饼状图数据失败", e);
            return AjaxResult.error("获取饼状图数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取柱状图数据（资质等级分布）
     * 支持按大队ID、科室ID、班组ID、用户ID 进行统计
     */
    @ApiOperation("获取柱状图数据")
    @GetMapping("/bar-chart")
    public AjaxResult getBarChartData(
            @RequestParam(required = false) Long deptId,
            @RequestParam(required = false) Long userId) {

        try {
            QualificationLevelStatsDTO.BarChartData barChart;

            // 优先处理用户 ID 参数
            if (userId != null) {
                // 按个人统计，返回该用户的资质等级
                barChart = calculateBarChartDataForUser(userId);
            } else if (deptId != null) {
                // 按部门 ID 统计，根据部门类型决定返回逻辑
                barChart = calculateBarChartDataForDept(deptId);
            } else {
                // 未传参，默认统计全站下各科室的分布
                Long topSiteId = DeptUtils.getTopSiteId(sysDeptService.selectDeptById(getDeptId()));
                if (topSiteId == null) {
                    return AjaxResult.error("无法找到有效的站点信息");
                }
                barChart = calculateBarChartDataOptimized(topSiteId);
            }

            return AjaxResult.success("获取成功", barChart);

        } catch (Exception e) {
            logger.error("获取柱状图数据失败", e);
            return AjaxResult.error("获取柱状图数据失败: " + e.getMessage());
        }
    }

    /**
     * 计算饼状图数据（全站范围资质等级分布）
     */
    private QualificationLevelStatsDTO.PieChartData calculatePieChartData(List<Long> userIds) {
        QualificationLevelStatsDTO.PieChartData pieChart = new QualificationLevelStatsDTO.PieChartData();

        // 查询资质等级统计（暂不考虑时间参数，后续可根据需要扩展）
        List<QualificationStats> statsList = qualificationLevelMapper.queryOrgQualificationLevelStats(userIds, null);

        // 转换为分布数据
        List<QualificationLevelStatsDTO.LevelDistribution> distributions = new ArrayList<>();
        int totalPersons = 0;

        // 统计实际存在的等级数据，按数据库存储的枚举值分组
        Map<String, Integer> levelCountMap = statsList.stream()
                .collect(Collectors.toMap(
                        QualificationStats::getLevelName,
                        QualificationStats::getCount,
                        Integer::sum
                ));

        // 按（初级、中级、高级）分组统计
        int juniorCount = levelCountMap.getOrDefault("LEVEL_FIVE", 0);  // 初级
        int intermediateCount = levelCountMap.getOrDefault("LEVEL_FOUR", 0);  // 中级
        int seniorCount = levelCountMap.getOrDefault("LEVEL_ONE", 0) +
                levelCountMap.getOrDefault("LEVEL_TWO", 0) +
                levelCountMap.getOrDefault("LEVEL_THREE", 0);  // 高级

        totalPersons = userIds.size();

        // 初级
        QualificationLevelStatsDTO.LevelDistribution juniorDist = new QualificationLevelStatsDTO.LevelDistribution();
        juniorDist.setLevelName("初级");
        juniorDist.setCount(juniorCount);
        juniorDist.setPercentage(totalPersons > 0 ?
                new BigDecimal(juniorCount * 100.0 / totalPersons).setScale(2, RoundingMode.HALF_UP) :
                BigDecimal.ZERO);
        distributions.add(juniorDist);

        // 中级
        QualificationLevelStatsDTO.LevelDistribution intermediateDist = new QualificationLevelStatsDTO.LevelDistribution();
        intermediateDist.setLevelName("中级");
        intermediateDist.setCount(intermediateCount);
        intermediateDist.setPercentage(totalPersons > 0 ?
                new BigDecimal(intermediateCount * 100.0 / totalPersons).setScale(2, RoundingMode.HALF_UP) :
                BigDecimal.ZERO);
        distributions.add(intermediateDist);

        // 高级
        QualificationLevelStatsDTO.LevelDistribution seniorDist = new QualificationLevelStatsDTO.LevelDistribution();
        seniorDist.setLevelName("高级");
        seniorDist.setCount(seniorCount);
        seniorDist.setPercentage(totalPersons > 0 ?
                new BigDecimal(seniorCount * 100.0 / totalPersons).setScale(2, RoundingMode.HALF_UP) :
                BigDecimal.ZERO);
        distributions.add(seniorDist);

        pieChart.setData(distributions);
        pieChart.setTotalPersons(totalPersons);

        return pieChart;
    }

    /**
     * 计算柱状图数据
     * - 站级/大队级/科级：返回下属组织的资质等级统计
     * - 班组：返回班组内每个员工的资质等级
     */
    private QualificationLevelStatsDTO.BarChartData calculateBarChartDataForDept(Long deptId) {
        QualificationLevelStatsDTO.BarChartData barChart = new QualificationLevelStatsDTO.BarChartData();

        SysDept sysDept = sysDeptService.selectDeptById(deptId);
        if (sysDept == null) {
            barChart.setBrigades(new ArrayList<>());
            return barChart;
        }

        List<SysDept> targetDepts = new ArrayList<>();

        // 根据部门类型决定查询逻辑
        if (DeptTypeEnum.TEAMS.getCode().equals(sysDept.getDeptType())) {
            // 班组级别：查询该班组下的所有用户，返回每个人的资质等级
            return calculateBarChartDataForTeam(deptId);
        } else {
            // 站级/大队级/科级：查询该部门下的所有子部门
            List<SysDept> children = sysDeptService.selectChildrenDeptById(deptId);
            if (DeptTypeEnum.MANAGER.getCode().equals(sysDept.getDeptType())) {
                targetDepts.addAll(children.stream()
                        .filter(dept -> DeptTypeEnum.TEAMS.getCode().equals(dept.getDeptType()))
                        .collect(Collectors.toList()));
            } else if (DeptTypeEnum.BRIGADE.getCode().equals(sysDept.getDeptType())) {
                targetDepts.addAll(children.stream()
                        .filter(dept -> DeptTypeEnum.MANAGER.getCode().equals(dept.getDeptType()))
                        .collect(Collectors.toList()));
            } else if (DeptTypeEnum.STATION.getCode().equals(sysDept.getDeptType())) {
                targetDepts.addAll(children.stream()
                        .filter(dept -> DeptTypeEnum.BRIGADE.getCode().equals(dept.getDeptType()))
                        .collect(Collectors.toList()));

            }
            if (targetDepts.isEmpty()) {
                barChart.setBrigades(new ArrayList<>());
                return barChart;
            }
        }

        // 批量获取所有子部门的用户 ID
        Map<Long, List<Long>> deptUserIdsMap = batchGetUserIdsByBrigades(targetDepts);

        // 批量查询所有子部门的资质统计数据
        Map<Long, List<QualificationStats>> deptStatsMap = batchQueryQualificationStats(deptUserIdsMap);

        // 构建部门数据
        List<QualificationLevelStatsDTO.BrigadeData> deptDataList = targetDepts.stream()
                .map(dept -> {
                    QualificationLevelStatsDTO.BrigadeData deptData = new QualificationLevelStatsDTO.BrigadeData();
                    deptData.setDeptId(dept.getDeptId());
                    deptData.setDeptName(dept.getDeptName());

                    List<QualificationStats> deptStats = deptStatsMap.get(dept.getDeptId());
                    if (deptStats != null && !deptStats.isEmpty()) {
                        List<QualificationLevelStatsDTO.LevelCount> levelCounts = convertToLevelCounts(deptStats);
                        deptData.setLevelCounts(levelCounts);
                    } else {
                        // 部门无用户或无统计数据，初始化为空数据
                        List<QualificationLevelStatsDTO.LevelCount> emptyCounts = QUALIFICATION_LEVELS.stream()
                                .map(level -> {
                                    QualificationLevelStatsDTO.LevelCount count = new QualificationLevelStatsDTO.LevelCount();
                                    count.setLevelName(level);
                                    count.setCount(0);
                                    return count;
                                })
                                .collect(Collectors.toList());
                        deptData.setLevelCounts(emptyCounts);
                    }

                    return deptData;
                })
                .collect(Collectors.toList());

        barChart.setBrigades(deptDataList);
        return barChart;
    }

    /**
     * 计算班组的柱状图数据（返回班组内每个员工的资质等级）
     */
    private QualificationLevelStatsDTO.BarChartData calculateBarChartDataForTeam(Long teamId) {
        QualificationLevelStatsDTO.BarChartData barChart = new QualificationLevelStatsDTO.BarChartData();

        // 获取班组下的所有用户
        List<Long> userIds = getAllUserIdsUnderDept(teamId);

        if (userIds.isEmpty()) {
            barChart.setBrigades(new ArrayList<>());
            return barChart;
        }

        // 查询每个用户的资质等级
        List<QualificationLevelStatsDTO.BrigadeData> userDataList = new ArrayList<>();
        for (Long uid : userIds) {
            SysUser user = sysUserService.selectUserById(uid);
            if (user == null || "2".equals(user.getDelFlag()) || "1".equals(user.getStatus())) {
                continue; // 跳过已删除或停用的用户
            }

            // 查询该用户的资质等级
            String level = qualificationLevelMapper.queryPersonalQualificationLevel(uid);
            String displayLevel = convertToDisplayLevel(level);

            QualificationLevelStatsDTO.BrigadeData userData = new QualificationLevelStatsDTO.BrigadeData();
            userData.setDeptId(uid); // 使用用户 ID 作为标识
            userData.setDeptName(user.getNickName() != null ? user.getNickName() : user.getUserName());
            userData.setQualificationLevel(displayLevel); // 直接设置资质等级

            userDataList.add(userData);
        }

        barChart.setBrigades(userDataList);
        return barChart;
    }

    /**
     * 计算个人的柱状图数据（返回单个用户的资质等级）
     */
    private QualificationLevelStatsDTO.BarChartData calculateBarChartDataForUser(Long userId) {
        QualificationLevelStatsDTO.BarChartData barChart = new QualificationLevelStatsDTO.BarChartData();

        SysUser user = sysUserService.selectUserById(userId);
        if (user == null || "2".equals(user.getDelFlag()) || "1".equals(user.getStatus())) {
            barChart.setBrigades(new ArrayList<>());
            return barChart;
        }

        // 查询该用户的资质等级
        String level = qualificationLevelMapper.queryPersonalQualificationLevel(userId);
        String displayLevel = convertToDisplayLevel(level);

        // 构建用户数据
        QualificationLevelStatsDTO.BrigadeData userData = new QualificationLevelStatsDTO.BrigadeData();
        userData.setDeptId(userId);
        userData.setDeptName(user.getNickName() != null ? user.getNickName() : user.getUserName());
        userData.setQualificationLevel(displayLevel); // 直接设置资质等级
        userData.setSysPostList(sysPostService.selectPostListsByUserId(userId));

        List<QualificationLevelStatsDTO.BrigadeData> departments = new ArrayList<>();
        departments.add(userData);
        barChart.setBrigades(departments);

        return barChart;
    }

    /**
     * 将数据库枚举值转换为显示名称
     */
    private String convertToDisplayLevel(String dbValue) {
        if (dbValue == null || dbValue.trim().isEmpty()) {
            return null;
        }
        switch (dbValue.toUpperCase()) {
            case "LEVEL_FIVE":
                return "初级";
            case "LEVEL_FOUR":
                return "中级";
            case "LEVEL_ONE":
            case "LEVEL_TWO":
            case "LEVEL_THREE":
                return "高级";
            default:
                return dbValue;
        }
    }

    /**
     * 计算柱状图数据（各大队资质等级分布）
     */
    private QualificationLevelStatsDTO.BarChartData calculateBarChartDataOptimized(Long siteId) {
        QualificationLevelStatsDTO.BarChartData barChart = new QualificationLevelStatsDTO.BarChartData();

        // 获取站点下的所有大队
        List<SysDept> brigades = getBrigadesUnderSite(siteId);
        if (brigades.isEmpty()) {
            barChart.setBrigades(new ArrayList<>());
            return barChart;
        }

        // 批量获取所有大队的用户ID
        Map<Long, List<Long>> deptUserIdsMap = batchGetUserIdsByBrigades(brigades);

        // 批量查询所有大队的资质统计数据
        Map<Long, List<QualificationStats>> deptStatsMap = batchQueryQualificationStats(deptUserIdsMap);

        // 构建大队数据
        List<QualificationLevelStatsDTO.BrigadeData> deptDataList = brigades.stream()
                .map(dept -> {
                    QualificationLevelStatsDTO.BrigadeData deptData = new QualificationLevelStatsDTO.BrigadeData();
                    deptData.setDeptId(dept.getDeptId());
                    deptData.setDeptName(dept.getDeptName());

                    List<QualificationStats> deptStats = deptStatsMap.get(dept.getDeptId());
                    if (deptStats != null && !deptStats.isEmpty()) {
                        List<QualificationLevelStatsDTO.LevelCount> levelCounts = convertToLevelCounts(deptStats);
                        deptData.setLevelCounts(levelCounts);
                    } else {
                        // 大队无用户或无统计数据，初始化为空数据
                        List<QualificationLevelStatsDTO.LevelCount> emptyCounts = QUALIFICATION_LEVELS.stream()
                                .map(level -> {
                                    QualificationLevelStatsDTO.LevelCount count = new QualificationLevelStatsDTO.LevelCount();
                                    count.setLevelName(level);
                                    count.setCount(0);
                                    return count;
                                })
                                .collect(Collectors.toList());
                        deptData.setLevelCounts(emptyCounts);
                    }

                    return deptData;
                })
                .collect(Collectors.toList());

        barChart.setBrigades(deptDataList);
        return barChart;
    }

    /**
     * 批量获取大队用户ID映射
     */
    private Map<Long, List<Long>> batchGetUserIdsByBrigades(List<SysDept> brigades) {
        Map<Long, List<Long>> deptUserIdsMap = new HashMap<>();

        for (SysDept dept : brigades) {
            List<Long> deptUserIds = getAllUserIdsUnderDept(dept.getDeptId());
            deptUserIdsMap.put(dept.getDeptId(), deptUserIds);
        }

        return deptUserIdsMap;
    }

    /**
     * 批量查询资质统计数据
     */
    private Map<Long, List<QualificationStats>> batchQueryQualificationStats(Map<Long, List<Long>> deptUserIdsMap) {
        Map<Long, List<QualificationStats>> deptStatsMap = new HashMap<>();

        // 过滤掉没有用户的大队
        Map<Long, List<Long>> validDeptUserIdsMap = deptUserIdsMap.entrySet().stream()
                .filter(entry -> !entry.getValue().isEmpty())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        if (validDeptUserIdsMap.isEmpty()) {
            return deptStatsMap;
        }

        for (Map.Entry<Long, List<Long>> entry : validDeptUserIdsMap.entrySet()) {
            Long deptId = entry.getKey();
            List<Long> userIds = entry.getValue();
            List<QualificationStats> stats = qualificationLevelMapper.queryOrgQualificationLevelStats(userIds, null);
            deptStatsMap.put(deptId, stats);
        }

        return deptStatsMap;
    }

    /**
     * 将资质统计转换为等级人数数据（初级、中级、高级）
     */
    private List<QualificationLevelStatsDTO.LevelCount> convertToLevelCounts(List<QualificationStats> statsList) {
        // 按数据库存储的枚举值分组统计
        Map<String, Integer> countMap = statsList.stream()
                .collect(Collectors.toMap(QualificationStats::getLevelName, QualificationStats::getCount));

        // 计算初级、中级、高级的人数
        int juniorCount = countMap.getOrDefault("LEVEL_FIVE", 0);  // 初级
        int intermediateCount = countMap.getOrDefault("LEVEL_FOUR", 0);  // 中级
        int seniorCount = countMap.getOrDefault("LEVEL_ONE", 0) +
                countMap.getOrDefault("LEVEL_TWO", 0) +
                countMap.getOrDefault("LEVEL_THREE", 0);  // 高级

        List<QualificationLevelStatsDTO.LevelCount> levelCounts = new ArrayList<>();

        QualificationLevelStatsDTO.LevelCount junior = new QualificationLevelStatsDTO.LevelCount();
        junior.setLevelName("初级");
        junior.setCount(juniorCount);
        levelCounts.add(junior);

        QualificationLevelStatsDTO.LevelCount intermediate = new QualificationLevelStatsDTO.LevelCount();
        intermediate.setLevelName("中级");
        intermediate.setCount(intermediateCount);
        levelCounts.add(intermediate);

        QualificationLevelStatsDTO.LevelCount senior = new QualificationLevelStatsDTO.LevelCount();
        senior.setLevelName("高级");
        senior.setCount(seniorCount);
        levelCounts.add(senior);

        return levelCounts;
    }


    /**
     * 获取站点下的所有用户ID
     */
    private List<Long> getAllUserIdsUnderSite(Long siteId) {
        List<Long> userIds = new ArrayList<>();

        // 获取站点本身及其下属部门
        List<SysDept> allDepts = sysDeptService.selectChildrenDeptById(siteId);
        allDepts.add(0, sysDeptService.selectDeptById(siteId)); // 添加站点本身

        // 获取各部门下的用户
        for (SysDept dept : allDepts) {
            if (Objects.nonNull(dept)) {
                List<Long> deptUserIds = sysUserService.selectUserByDeptId(dept.getDeptId()).stream()
                        .map(SysUser::getUserId)
                        .collect(Collectors.toList());
                userIds.addAll(deptUserIds);
            }
        }

        return userIds.stream().distinct().collect(Collectors.toList());
    }

    /**
     * 获取站点下的所有大队
     */
    private List<SysDept> getBrigadesUnderSite(Long siteId) {
        List<SysDept> children = sysDeptService.selectChildrenDeptById(siteId);
        return children.stream()
                .filter(dept -> DeptTypeEnum.BRIGADE.getCode().equals(dept.getDeptType()))
                .collect(Collectors.toList());
    }

    /**
     * 获取部门下的所有用户ID
     */
    private List<Long> getAllUserIdsUnderDept(Long deptId) {
        List<SysUser> sysUserList = sysUserService.selectUserByDeptId(deptId);
        return sysUserList.stream()
                .map(SysUser::getUserId)
                .collect(Collectors.toList());
    }

}