package com.sundot.airport.item.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sundot.airport.common.core.domain.BaseLargeScreenQueryParamDto;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.domain.entity.SysRole;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.domain.portrait.IndicatorCalculateParams;
import com.sundot.airport.common.enums.DeptTypeEnum;
import com.sundot.airport.common.enums.RoleTypeEnum;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.utils.SecurityUtils;
import com.sundot.airport.item.domain.*;
import com.sundot.airport.item.mapper.ItemLargeScreenMapper;
import com.sundot.airport.item.service.UserRankingService;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户排名服务实现类
 */
@Service
public class UserRankingServiceImpl implements UserRankingService {

    @Autowired
    private ItemLargeScreenMapper itemLargeScreenMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDeptService sysDeptService;


    /**
     * 获取用户在指定层级的详细排名信息
     *
     * @param dto 查询参数
     * @return 用户在该层级的详细排名信息
     */
    @Override
    public ItemLargeScreenCommonDto getUserRankingByLevel(BaseLargeScreenQueryParamDto dto, String level) {
        Long deptId = dto.getDeptId();
        Long userId = dto.getUserId();
        if (deptId != null && userId == null) {
            return getDeptLevel(dto, deptId, level);
        } else if (userId != null) {
            return getUserLevel(dto, userId, level);
        } else {
            throw new ServiceException("参数类型错误");
        }

    }

    /**
     * 查询部门的详细排名信息
     *
     * @param dto
     * @param deptId
     * @param level
     * @return
     */
    private ItemLargeScreenCommonDto getDeptLevel(BaseLargeScreenQueryParamDto dto, Long deptId, String level) {
        //根据部门id查询部门信息
        SysDept dept = sysDeptService.selectDeptById(deptId);
        if (dept == null) {
            return null;
        }
        // 查询所有正常状态的部门
        List<SysDept> allDepts = sysDeptService.selectDeptInfoAll(new SysDept());
        // 根据不同层级类型查询部门排名
        List<ItemLargeScreenCommonDto> rankings;
        List<SysDept> collect = new ArrayList<>();
        switch (level) {
            case "station":
                if (dept.getDeptType().equals(DeptTypeEnum.BRIGADE.getCode())) {
                    collect = allDepts.stream().filter(de -> de.getDeptType().equals(DeptTypeEnum.BRIGADE.getCode())).collect(Collectors.toList());
                    //查所有的大队
                    rankings = itemLargeScreenMapper.rankByBrigade(dto);
                } else if (dept.getDeptType().equals(DeptTypeEnum.MANAGER.getCode())) {
                    collect = allDepts.stream().filter(de -> de.getDeptType().equals(DeptTypeEnum.MANAGER.getCode())).collect(Collectors.toList());
                    //查所有的科
                    rankings = itemLargeScreenMapper.rankByDepartment(dto);
                } else if (dept.getDeptType().equals(DeptTypeEnum.TEAMS.getCode())) {
                    //查所有的班
                    collect = allDepts.stream().filter(de -> de.getDeptType().equals(DeptTypeEnum.TEAMS.getCode())).collect(Collectors.toList());
                    rankings = itemLargeScreenMapper.rankByTeam(dto);
                } else {
                    return null;
                }
                break;
            case "brigade":
                if (dept.getDeptType().equals(DeptTypeEnum.MANAGER.getCode())) {
                    collect = allDepts.stream().filter(de -> de.getDeptType().equals(DeptTypeEnum.MANAGER.getCode())).collect(Collectors.toList());
                    //查所有的科
                    rankings = itemLargeScreenMapper.rankByDepartment(dto);
                } else if (dept.getDeptType().equals(DeptTypeEnum.TEAMS.getCode())) {
                    //查所有的班
                    collect = allDepts.stream().filter(de -> de.getDeptType().equals(DeptTypeEnum.TEAMS.getCode())).collect(Collectors.toList());
                    rankings = itemLargeScreenMapper.rankByTeam(dto);
                } else {
                    return null;
                }
                break;
            case "department":
                if (dept.getDeptType().equals(DeptTypeEnum.TEAMS.getCode())) {
                    //科下面的所有班
                    collect = allDepts.stream().filter(de -> de.getDeptType().equals(DeptTypeEnum.TEAMS.getCode()) && de.getParentId().equals(dept.getParentId())).collect(Collectors.toList());
                    //查所有的班
                    dto.setInspectDepartmentId(dept.getParentId());
                    rankings = itemLargeScreenMapper.rankByTeam(dto);
                } else {
                    return null;
                }
                break;
            default:
                return null;
        }

        // 补充未出现在排行榜中的用户，并初始化其默认值
        Set<Long> rankingIds = rankings.stream().map(ItemLargeScreenCommonDto::getId).collect(Collectors.toSet());
        List<ItemLargeScreenCommonDto> missingUsers = collect.stream()
                .filter(d -> !rankingIds.contains(d.getDeptId()))
                .map(this::buildDefaultDeptRanking)
                .collect(Collectors.toList());

        rankings.addAll(missingUsers);

        // 重新按总分排序并分配排名
        rankings.sort(Comparator.comparing(ItemLargeScreenCommonDto::getTotal).reversed());
        for (int i = 0; i < rankings.size(); i++) {
            rankings.get(i).setRank(i + 1);
            rankings.get(i).setRankCount(rankings.size());
        }
        // 查找目标部门的排名信息
        Optional<ItemLargeScreenCommonDto> targetDeptRanking = rankings.stream()
                .filter(r -> deptId.equals(r.getId()))
                .findFirst();

        return targetDeptRanking.orElse(null);
    }

    /**
     * 根据用户ID获取用户在指定层级的详细排名信息
     *
     * @param dto
     * @param level
     * @return
     */
    private ItemLargeScreenCommonDto getUserLevel(BaseLargeScreenQueryParamDto dto, Long userId, String level) {
        // 参数合法性校验
        if (dto == null || userId == null || StrUtil.isBlank(level)) {
            return null;
        }

        // 获取当前用户信息
        SysUser user = sysUserService.selectUserById(userId);
        if (user == null) {
            return null;
        }

        // 角色校验
        List<SysRole> roles = user.getRoles();
        if (CollectionUtil.isEmpty(roles)) {
            return null;
        }
        SysRole sysRole = roles.get(0);
        if (sysRole == null) {
            return null;
        }

        // 部门校验
        SysDept dept = user.getDept();
        if (dept == null) {
            return null;
        }

        // 获取部门下的所有用户
        List<SysUser> users = new ArrayList<>();
        // 查询排名数据
        List<ItemLargeScreenCommonDto> rankings = getRankingsByLevel(dto, user, sysRole, dept, level, users);
        if (CollectionUtil.isEmpty(rankings) || CollectionUtil.isEmpty(users)) {
            return null;
        }

        // 补充未出现在排行榜中的用户，并初始化其默认值
        Set<Long> rankingIds = rankings.stream().map(ItemLargeScreenCommonDto::getId).collect(Collectors.toSet());
        List<ItemLargeScreenCommonDto> missingUsers = users.stream()
                .filter(u -> !rankingIds.contains(u.getUserId()))
                .map(this::buildDefaultRanking)
                .collect(Collectors.toList());

        rankings.addAll(missingUsers);

        // 重新按总分排序并分配排名
        rankings.sort(Comparator.comparing(ItemLargeScreenCommonDto::getTotal).reversed());
        for (int i = 0; i < rankings.size(); i++) {
            rankings.get(i).setRank(i + 1);
            rankings.get(i).setRankCount(rankings.size());
        }

        // 找出目标用户的排名信息
        return rankings.stream()
                .filter(r -> userId.equals(r.getId()))
                .findFirst()
                .orElse(null);
    }

    // 根据层级获取排名数据（）
    private List<ItemLargeScreenCommonDto> getRankingsByLevel(BaseLargeScreenQueryParamDto dto,
                                                              SysUser user,
                                                              SysRole sysRole,
                                                              SysDept dept,
                                                              String level,
                                                              List<SysUser> users) {
        // 先查这个人的站的id，在根据这个站id，查询角色是班和质检员的用户
        Long stationId = findStationIdByUser(user);
        List<SysUser> stationUsers = new ArrayList<>();
        if (stationId != null) {
            stationUsers = sysUserService.selectUserListByRoleKeyAndDeptId(
                    Arrays.asList(RoleTypeEnum.banzuzhang.getCode(), RoleTypeEnum.SecurityCheck.getCode()),
                    stationId);
            if (CollectionUtil.isEmpty(stationUsers)) {
                return null;
            }
        }
        Long brigadeId = findBrigadeIdByUser(user);
        List<SysUser> brigadeIdUsers = new ArrayList<>();
        if (brigadeId != null) {
            brigadeIdUsers = sysUserService.selectUserListByRoleKeyAndDeptId(
                    Arrays.asList(RoleTypeEnum.banzuzhang.getCode(), RoleTypeEnum.SecurityCheck.getCode()),
                    brigadeId);
            if (CollectionUtil.isEmpty(brigadeIdUsers)) {
                return null;
            }
        }
        switch (level) {
            case "station":
                // 查询站下所有用户
                users.addAll(stationUsers);
                return itemLargeScreenMapper.rankByIndividual(dto);
            case "brigade":
                // 查询大队下所有用户
                users.addAll(brigadeIdUsers);
                dto.setInspectBrigadeId(brigadeId);
                return itemLargeScreenMapper.rankByIndividual(dto);
            case "department":
                if (RoleTypeEnum.banzuzhang.getCode().equals(sysRole.getRoleKey()) ||
                        RoleTypeEnum.SecurityCheck.getCode().equals(sysRole.getRoleKey())) {
                    dto.setInspectDepartmentId(dept.getParentId());
                } else {
                    dto.setInspectDepartmentId(user.getDeptId());
                }
                //获取部门下的所有用户包括下属
                List<SysUser> collect = stationUsers.stream().filter(item -> item.getDept().getDeptId().equals(dto.getInspectDepartmentId()) || item.getDept().getParentId().equals(dto.getInspectDepartmentId())).collect(Collectors.toList());
                users.addAll(collect);
                return itemLargeScreenMapper.rankByIndividual(dto);
            case "team":
                dto.setInspectTeamId(user.getDeptId());
                List<SysUser> collectTeam = stationUsers.stream().filter(item -> item.getDeptId().equals(dto.getInspectTeamId())).collect(Collectors.toList());
                users.addAll(collectTeam);
                return itemLargeScreenMapper.rankByIndividual(dto);
            default:
                return null;
        }
    }

    /**
     * 根据用户查找其所属的站点ID
     *
     * @param user 用户
     * @return 站点ID
     */
    private Long findStationIdByUser(SysUser user) {
        // 获取用户所在部门
        SysDept userDept = user.getDept();
        if (userDept == null) {
            return null;
        }

        // 如果用户所在部门就是站点
        if (DeptTypeEnum.STATION.getCode().equals(userDept.getDeptType())) {
            return userDept.getDeptId();
        }

        // 向上查找父级部门，直到找到站点
        SysDept currentDept = userDept;
        while (currentDept != null && !DeptTypeEnum.STATION.getCode().equals(currentDept.getDeptType())) {
            currentDept = sysDeptService.selectDeptById(currentDept.getParentId());
        }

        return currentDept != null ? currentDept.getDeptId() : null;
    }

    /**
     * 根据用户查找其所属的大队ID
     *
     * @param user 用户
     * @return 站点ID
     */
    private Long findBrigadeIdByUser(SysUser user) {
        // 获取用户所在部门
        SysDept userDept = user.getDept();
        if (userDept == null) {
            return null;
        }

        // 如果用户所在部门就是大队
        if (DeptTypeEnum.BRIGADE.getCode().equals(userDept.getDeptType())) {
            return userDept.getDeptId();
        }

        // 向上查找父级部门，直到找到大队
        SysDept currentDept = userDept;
        while (currentDept != null && !DeptTypeEnum.BRIGADE.getCode().equals(currentDept.getDeptType())) {
            currentDept = sysDeptService.selectDeptById(currentDept.getParentId());
        }

        return currentDept != null ? currentDept.getDeptId() : null;
    }

    // 构建默认排名对象
    private ItemLargeScreenCommonDto buildDefaultRanking(SysUser user) {
        ItemLargeScreenCommonDto dto = new ItemLargeScreenCommonDto();
        dto.setId(user.getUserId());
        dto.setName(user.getUserName());
        dto.setTotal(BigDecimal.ZERO);
        dto.setScale(BigDecimal.ZERO);
        dto.setRank(0); // 初始占位符，后续会更新
        return dto;
    }

    private ItemLargeScreenCommonDto buildDefaultDeptRanking(SysDept dept) {
        ItemLargeScreenCommonDto dto = new ItemLargeScreenCommonDto();
        dto.setId(dept.getDeptId());
        dto.setName(dept.getDeptName());
        dto.setTotal(BigDecimal.ZERO);
        dto.setScale(BigDecimal.ZERO);
        dto.setRank(0); // 初始占位符，后续会更新
        return dto;
    }


    /**
     * 计算站级查获统计
     *
     * @param params 指标计算参数
     * @return 站级查获统计
     */
    @Override
    public List<ItemLargeScreenStatsDto> calculateStationItemSeizure(IndicatorCalculateParams params) {
        List<ItemLargeScreenStatsDto> result = new ArrayList<>();
        if (params.getDeptId() == null) {
            return result;
        }

        // 直接查询部门信息
        SysDept queryDept = new SysDept();
        queryDept.setDeptId(params.getDeptId());
        queryDept.setDeptType(DeptTypeEnum.BRIGADE.getCode());
        //查询站和大队的信息
        List<SysDept> sysDeptList = sysDeptService.selectDeptInfo(queryDept);
        if (CollectionUtil.isEmpty(sysDeptList)) {
            return result;
        }
        // 默认查询最近30天的数据
        Date endTime = ObjectUtil.isEmpty(params.getEndTime()) ? new Date() : params.getEndTime();
        Date startTime = ObjectUtil.isEmpty(params.getStartTime()) ? new Date(endTime.getTime() - 91L * 24 * 60 * 60 * 1000) : params.getStartTime();
        sysDeptList.forEach(sysDept -> {
            BaseLargeScreenQueryParamDto dto = new BaseLargeScreenQueryParamDto();
            if (!sysDept.getDeptId().equals(params.getDeptId())) {
                dto.setInspectBrigadeId(sysDept.getDeptId());
            }
            dto.setStartDate(startTime);
            dto.setEndDate(endTime);
            ItemLargeScreenTotalSomeDto before = itemLargeScreenMapper.getTotalSome(dto);
            ItemLargeScreenStatsDto itemLargeScreenStatsDto = new ItemLargeScreenStatsDto();
            itemLargeScreenStatsDto.setDeptId(sysDept.getDeptId());
            itemLargeScreenStatsDto.setDeptName(sysDept.getDeptName());
            if (ObjectUtil.isNotEmpty(before)) {
                itemLargeScreenStatsDto.setEffectiveSeizureCount(before.getTotal());
                itemLargeScreenStatsDto.setConcealTotal(before.getConcealTotal());
                itemLargeScreenStatsDto.setPoliceTotal(before.getPoliceTotal());
            }
            result.add(itemLargeScreenStatsDto);
        });
        return result;
    }

    /**
     * 获取按天统计的查获趋势数据
     *
     * @param queryDto 查询参数
     * @return 按天统计的查获趋势数据
     */
    @Override
    public List<ItemLargeScreenDailyTrendDto> getDailyTrendData(BaseLargeScreenQueryParamDto queryDto) {
        return itemLargeScreenMapper.dailyTrend(queryDto);
    }
}