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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.sundot.airport.check.domain.CheckEfficiencyDto;
import com.sundot.airport.check.domain.CheckEfficiencyRankDto;
import com.sundot.airport.check.service.ICheckEfficiencyService;
import com.sundot.airport.check.service.ICheckLargeScreenService;
import com.sundot.airport.common.core.domain.BaseLargeScreenQueryParamDto;
import com.sundot.airport.common.core.domain.CheckLargeScreenHomePageItemDto;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.enums.DeptType;
import com.sundot.airport.common.enums.RoleTypeEnum;
import com.sundot.airport.common.utils.DeptUtils;
import com.sundot.airport.common.utils.SecurityUtils;
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.math.RoundingMode;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 巡检合格率Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-25
 */
@Service
public class CheckEfficiencyServiceImpl implements ICheckEfficiencyService {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ICheckLargeScreenService iCheckLargeScreenService;


    /**
     * 查询巡检合格率统计
     *
     * @param dto       查询参数
     * @param dimension 统计维度：1-人员、2-班级、3-科级、4-大队级
     * @return 巡检合格率统计结果
     */
    @Override
    public CheckEfficiencyDto getCheckEfficiency(BaseLargeScreenQueryParamDto dto, Integer dimension) {
        CheckEfficiencyDto result = new CheckEfficiencyDto();
        List<CheckLargeScreenHomePageItemDto> itemListAll = iCheckLargeScreenService.getCheckLargeScreenHomePageItemDtoListAndNull(dto);
//        List<SysDept> deptList = sysDeptService.selectDeptInfoAll(new SysDept());
        Long topSiteId = DeptUtils.getTopSiteId(sysDeptService.selectDeptById(SecurityUtils.getDeptId()));
        List<SysDept> deptList = sysDeptService.selectChildrenDeptById(topSiteId);

        // 获取大队效率排行
        if (dimension == null || dimension == 4) {
            List<SysDept> brigadeDeptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.BRIGADE.getCode(), item.getDeptType())).collect(Collectors.toList());
            List<CheckEfficiencyRankDto> brigadeSeizureList = brigadeDeptList
                    .stream()
                    .map(item -> {
                        CheckEfficiencyRankDto rankDto = new CheckEfficiencyRankDto();
                        rankDto.setId(item.getDeptId());
                        rankDto.setName(item.getDeptName());
                        rankDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                        return rankDto;
                    })
                    .collect(Collectors.toList());
            brigadeSeizureList.sort((a, b) -> b.getPassRate().compareTo(a.getPassRate()));
            for (int i = 0; i < brigadeSeizureList.size(); i++) {
                brigadeSeizureList.get(i).setRank(i + 1);
            }
            result.setBrigadeRankList(brigadeSeizureList);
        }

        // 获取科室效率排行
        if (dimension == null || dimension == 3) {
            List<SysDept> departmentDeptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.MANAGER.getCode(), item.getDeptType())).collect(Collectors.toList());
            List<CheckEfficiencyRankDto> departmentSeizureList = departmentDeptList
                    .stream()
                    .map(item -> {
                        CheckEfficiencyRankDto rankDto = new CheckEfficiencyRankDto();
                        rankDto.setId(item.getDeptId());
                        rankDto.setName(item.getDeptName());
                        rankDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                        return rankDto;
                    })
                    .collect(Collectors.toList());
            departmentSeizureList.sort((a, b) -> b.getPassRate().compareTo(a.getPassRate()));
            for (int i = 0; i < departmentSeizureList.size(); i++) {
                departmentSeizureList.get(i).setRank(i + 1);
            }
            result.setDepartmentRankList(departmentSeizureList);
        }

        // 获取班组效率排行
        if (dimension == null || dimension == 2) {
            List<SysDept> teamDeptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.TEAMS.getCode(), item.getDeptType())).collect(Collectors.toList());
            List<CheckEfficiencyRankDto> teamSeizureList = teamDeptList
                    .stream()
                    .map(item -> {
                        CheckEfficiencyRankDto rankDto = new CheckEfficiencyRankDto();
                        rankDto.setId(item.getDeptId());
                        rankDto.setName(item.getDeptName());
                        rankDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                        return rankDto;
                    })
                    .collect(Collectors.toList());
            teamSeizureList.sort((a, b) -> b.getPassRate().compareTo(a.getPassRate()));
            for (int i = 0; i < teamSeizureList.size(); i++) {
                teamSeizureList.get(i).setRank(i + 1);
            }
            result.setTeamRankList(teamSeizureList);
        }

        // 获取个人效率排行
        if (dimension == null || dimension == 1) {
            List<CheckEfficiencyRankDto> individualSeizureList = itemListAll
                    .stream()
                    .map(item -> {
                        CheckEfficiencyRankDto rankDto = new CheckEfficiencyRankDto();
                        rankDto.setId(item.getId());
                        rankDto.setName(item.getName());
                        rankDto.setPassRate(item.getPassRate());
                        return rankDto;
                    })
                    .collect(Collectors.toList());
            individualSeizureList.sort((a, b) -> b.getPassRate().compareTo(a.getPassRate()));
            for (int i = 0; i < individualSeizureList.size(); i++) {
                individualSeizureList.get(i).setRank(i + 1);
            }
            result.setIndividualRankList(individualSeizureList);
        }

        return result;
    }

    /**
     * 计算部门通过率
     *
     * @param itemListAll 全量数据
     * @param deptId      部门ID
     * @return 部门通过率
     */
    private BigDecimal calculate(List<CheckLargeScreenHomePageItemDto> itemListAll, Long deptId) {
        if (CollUtil.isEmpty(itemListAll)) {
            return BigDecimal.ONE;
        }
        List<SysUser> sysUserList = sysUserService.selectUserListByRoleKeyAndDeptId(Arrays.asList(RoleTypeEnum.banzuzhang.getCode(), RoleTypeEnum.SecurityCheck.getCode()), deptId);
        List<Long> userIdList = sysUserList.stream().map(SysUser::getUserId).collect(Collectors.toList());
        List<CheckLargeScreenHomePageItemDto> itemDtoList = itemListAll.stream().filter(item -> userIdList.contains(item.getId())).collect(Collectors.toList());
        BigDecimal reduce = itemDtoList.stream().map(CheckLargeScreenHomePageItemDto::getPassRate).reduce(BigDecimal.ZERO, BigDecimal::add);
        return CollUtil.isEmpty(itemDtoList) ? BigDecimal.ONE : reduce.divide(new BigDecimal(itemDtoList.size()), 4, RoundingMode.HALF_UP);
    }

}