package jnpf.cultivate.v2.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import jnpf.base.vo.PageListVO;
import jnpf.cultivate.mapper.FtbCultivateExamUserMapper;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.cultivate.v2.service.V2CultivateExamStatisticsService;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.resp.AppExamListVo;
import jnpf.model.cultivate.resp.StatisticsResultDto;
import jnpf.model.cultivate.v2.exam.req.V2ExamStatisticsForOrgReq;
import jnpf.model.cultivate.v2.exam.req.V2ExamStatisticsForPersonReq;
import jnpf.model.cultivate.v2.exam.vo.AiHelperExamStatisticsVo;
import jnpf.model.cultivate.v2.exam.vo.V2ExamStatisticsForOrgVo;
import jnpf.model.cultivate.v2.exam.vo.V2ExamStatisticsForPersonVo;
import jnpf.model.cultivate.vo.common.InnerPowerUserVO;
import jnpf.permission.vo.v2.organzie.OrganizeGeneralDetailVO;
import jnpf.permission.vo.v2.position.PositionVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.permission.vo.v2.user.UserPageListVO;
import jnpf.util.QuestionAnalysisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
@Slf4j
public class V2CultivateExamStatisticsServiceImpl implements V2CultivateExamStatisticsService {


    @Autowired
    private UserApiV2Util userApiV2Util;

    @Autowired
    private FtbCultivateExamUserMapper ftbCultivateExamUserMapper;


    @Override
    public PageListVO<V2ExamStatisticsForOrgVo> queryExamStatisticsForOrg(V2ExamStatisticsForOrgReq dto) {
        Page<V2ExamStatisticsForOrgVo> page = dto.coverCultivatePage();
        List<String> powerOrgList = userApiV2Util.queryPowerOrgList();
        if (CollUtil.isEmpty(powerOrgList)) {
            return CultivatePage.coverPageList(page);
        }
        if(CollUtil.isNotEmpty(dto.getOrgIds())){
            List<String> intersection = UserApiV2Util.getIntersection(powerOrgList, dto.getOrgIds());
            if (CollUtil.isEmpty(intersection)) {
                return CultivatePage.coverPageList(page);
            }
            dto.setOrgIds(intersection);
        }else{
            dto.setOrgIds(powerOrgList);
        }
        if (CollUtil.isEmpty(dto.getOrgIds())) {
            return CultivatePage.coverPageList(page);
        }
        List<String> selectOrgList = dto.getOrgIds();
        if (dto.getIsNext() == 1) {
            List<OrganizeGeneralDetailVO> organizeGeneralDetailVOS = userApiV2Util.organizesOrHaveChildByOrganizeIds(selectOrgList, true, null);
            if (CollUtil.isNotEmpty(organizeGeneralDetailVOS)) {
                List<String> collect = organizeGeneralDetailVOS.stream().map(OrganizeGeneralDetailVO::getId).collect(Collectors.toList());
                selectOrgList.addAll(collect);
            }
        }
        List<String> intersection = UserApiV2Util.getIntersection(powerOrgList, selectOrgList);
        if (CollUtil.isEmpty(intersection)) {
            return CultivatePage.coverPageList(page);
        }
        selectOrgList = intersection;
        List<UserPageListVO> userListForOrgIds = userApiV2Util.getUserListForOrgIds(selectOrgList, null);
        if (CollUtil.isEmpty(userListForOrgIds)) {
            return CultivatePage.coverPageList(page);
        }
        Map<String, List<UserPageListVO>> userOrgGroup = userListForOrgIds.stream().collect(Collectors.groupingBy(UserPageListVO::getOrganizeId));
        List<AppExamListVo> queryList = ftbCultivateExamUserMapper.countForOrgV2(dto, userListForOrgIds.stream().map(UserPageListVO::getId).collect(Collectors.toList()));

        if (CollUtil.isEmpty(queryList)) {
            return CultivatePage.coverPageList(page);
        }
        //queryList 转换成用户的map
        Map<String, List<AppExamListVo>> userExamMap = queryList.stream().collect(Collectors.groupingBy(AppExamListVo::getUserId));
        //查询组织
        Map<String, OrganizeGeneralDetailVO> organizeEntityMap = userApiV2Util.organizesByOrganizeIdsReturenMap(selectOrgList, null);
        List<V2ExamStatisticsForOrgVo> retList = new ArrayList<>();
        for (String orgId : selectOrgList) {
            List<UserPageListVO> listVOS = userOrgGroup.get(orgId);
            if (CollUtil.isEmpty(listVOS)) {
                continue;
            }
            List<String> userIds = listVOS.stream().map(UserPageListVO::getId).collect(Collectors.toList());
            List<AppExamListVo> examUserList = new ArrayList<>();
            for (String userId : userIds) {
                List<AppExamListVo> appExamListVo = userExamMap.get(userId);
                if (appExamListVo != null) {
                    examUserList.addAll(appExamListVo);
                }
            }
            if (CollUtil.isEmpty(examUserList)) {
                continue;
            }
            //按照考试分组
            Map<String, List<AppExamListVo>> examGroupUserMap = examUserList.stream()
                    .collect(Collectors.groupingBy(AppExamListVo::getExamId));
            for (Map.Entry<String, List<AppExamListVo>> examGroupEntity : examGroupUserMap.entrySet()) {
                String examId = examGroupEntity.getKey(); // 当前键
                String examName = "";
                Integer examType = null;
                String examTypeName = "";
                List<AppExamListVo> examGroupList = examGroupEntity.getValue(); // 当前值（List<AppExamListVo>）
                if (CollUtil.isNotEmpty(examGroupList)) {
                    examName = examGroupList.get(0).getExamName();
                    examType = examGroupList.get(0).getExamType();
                    if (examGroupList.get(0).getExamType() == 1) {
                        examTypeName = "岗位学习考试";
                    } else {
                        examTypeName = "自定义考试";
                    }
                }
                StatisticsResultDto statisticsResultDto = QuestionAnalysisUtil.statisticeLvForAppExam(examGroupList);
                V2ExamStatisticsForOrgVo vo = new V2ExamStatisticsForOrgVo();
                vo.setOrgId(orgId);
                OrganizeGeneralDetailVO organizeEntity = organizeEntityMap.get(orgId);
                if (null != organizeEntity) {
                    vo.setOrgName(organizeEntity.getName());
                    vo.setOrgCode(organizeEntity.getEnCode());
                }
                vo.setExamId(examId);
                vo.setExamName(examName);
                vo.setExamType(examType);
                vo.setExamTypeName(examTypeName);

                vo.setTotleNum(String.valueOf(statisticsResultDto.getTotle()));
                vo.setExcellentNum(String.valueOf(statisticsResultDto.getExcellent()));
                vo.setPassNum(String.valueOf(statisticsResultDto.getPass()));
                vo.setNoPassNum(String.valueOf(statisticsResultDto.getNoPass()));

                vo.setNoPassRate(String.valueOf(statisticsResultDto.getNoPassLv()));
                vo.setPassRate(String.valueOf(statisticsResultDto.getPassLv()));
                vo.setExcellentRate(String.valueOf(statisticsResultDto.getExcellentLv()));
                retList.add(vo);
            }
        }
        return UserApiV2Util.buildPage(retList, dto.getPageSize(), dto.getCurrentPage());
    }

    private List<Integer> buildExamStatus(V2ExamStatisticsForPersonReq dto) {
        List<Integer> innerStatus = new ArrayList<>();
        if (dto.getExamStatus().equals(0)) {
            if (dto.getExamResult() == 0) {
                innerStatus.add(0);
                innerStatus.add(1);
                innerStatus.add(2);
                innerStatus.add(3);
                innerStatus.add(4);
                innerStatus.add(5);
            } else if (dto.getExamResult() == 1) {
                innerStatus.add(5);
            } else if (dto.getExamResult() == 2) {
                innerStatus.add(3);
//                innerStatus.add(5);
            } else if (dto.getExamResult() == 3) {
                innerStatus.add(4);
            }
        } else if (dto.getExamStatus().equals(1)) {
            innerStatus.add(0);
            innerStatus.add(2);
        } else if (dto.getExamStatus().equals(2)) {
            if (dto.getExamResult() == 0) {
                innerStatus.add(1);
                innerStatus.add(3);
                innerStatus.add(4);
                innerStatus.add(5);
            } else if (dto.getExamResult() == 1) {
                innerStatus.add(5);
            } else if (dto.getExamResult() == 2) {
                innerStatus.add(3);
//                innerStatus.add(5);
            } else if (dto.getExamResult() == 3) {
                innerStatus.add(4);
            }
        }
        return innerStatus;
    }

    private List<String> queryUserIdsForPositionIds(List<String> positionIds) {
        List<UserBoundVO> voList = userApiV2Util.getUserListForPositions(positionIds, null);
        if (CollUtil.isEmpty(voList)) {
            return new ArrayList<>();
        }
        return voList.stream().map(UserBoundVO::getId).collect(Collectors.toList());
    }

    @Override
    public PageInfo<V2ExamStatisticsForPersonVo> queryExamStatisticsForPerson(V2ExamStatisticsForPersonReq dto) {
        if (null == dto.getCurrentPage() || null == dto.getPageSize()) {
            throw new RuntimeException("请传入分页信息");
        }

        if (dto.getExamStatus().equals(1) && !dto.getExamResult().equals(0)) {
            return PageInfo.emptyPageInfo();
        }


        //0待考试，1待批阅，2已逾期，3合格，4不合格 5、优秀
        List<Integer> innerStatus = buildExamStatus(dto);
        Page<V2ExamStatisticsForPersonVo> page = Page.of(dto.getCurrentPage(), dto.getPageSize());
        List<String> innerUserIds = new ArrayList<>();
        if (StringUtils.isNotEmpty(dto.getPersonPositionId()) && CollUtil.isNotEmpty(dto.getUserIds())) {
            List<String> positionUserIds = queryUserIdsForPositionIds(List.of(dto.getPersonPositionId()));
            if (CollUtil.isEmpty(positionUserIds)) {
                return PageInfo.emptyPageInfo();
            }
            List<String> intersection = UserApiV2Util.getIntersection(positionUserIds, dto.getUserIds());
            if (CollUtil.isEmpty(intersection)) {
                return PageInfo.emptyPageInfo();
            }
            innerUserIds = intersection;
        } else if (CollUtil.isNotEmpty(dto.getUserIds())) {
            innerUserIds.addAll(dto.getUserIds());
        } else if (StringUtils.isNotEmpty(dto.getPersonPositionId())) {
            List<String> positionUserIds = queryUserIdsForPositionIds(List.of(dto.getPersonPositionId()));
            if (CollUtil.isEmpty(positionUserIds)) {
                return PageInfo.emptyPageInfo();
            }
            innerUserIds = positionUserIds;
        }
        if (StringUtils.isNotEmpty(dto.getOrgId())) {
            String[] split = dto.getOrgId().split(",");
            List<UserPageListVO> userListForOrgIds = userApiV2Util.getUserListForOrgIds(Arrays.asList(split), null);
            if (CollUtil.isEmpty(userListForOrgIds)) {
                return PageInfo.emptyPageInfo();
            }
            if (CollUtil.isEmpty(innerUserIds)) {
                innerUserIds = userListForOrgIds.stream().map(UserPageListVO::getId).collect(Collectors.toList());
            } else {
                List<String> intersection = UserApiV2Util.getIntersection(userListForOrgIds.stream().map(UserPageListVO::getId).collect(Collectors.toList()), innerUserIds);
                if (CollUtil.isEmpty(intersection)) {
                    return PageInfo.emptyPageInfo();
                }
                innerUserIds = intersection;
            }
        }

        InnerPowerUserVO powerUserVO = userApiV2Util.getLoginManagerUserIdsForEncode();
        if (powerUserVO.getCode() == 1) {
            if (CollUtil.isNotEmpty(innerUserIds)) {
                List<String> intersection = UserApiV2Util.getIntersection(powerUserVO.getUserIds(), innerUserIds);
                if (CollUtil.isEmpty(intersection)) {
                    return PageInfo.emptyPageInfo();
                }
                innerUserIds = intersection;
            } else {
                innerUserIds = powerUserVO.getUserIds();
            }
        } else if (powerUserVO.getCode() == 2) {
            return PageInfo.emptyPageInfo();
        }

        Page<V2ExamStatisticsForPersonVo> queryPage = ftbCultivateExamUserMapper.queryExamStatisticsForPersonV2(page, dto, innerUserIds, innerStatus);
        List<V2ExamStatisticsForPersonVo> list = queryPage.getRecords();
        if (CollUtil.isNotEmpty(list)) {
            List<String> tempUserId = new ArrayList<>();
            List<String> tempPostionId = new ArrayList<>();
            for (V2ExamStatisticsForPersonVo examStatisticsForPersonVo : list) {
                tempUserId.add(examStatisticsForPersonVo.getUserId());
                if (examStatisticsForPersonVo.getExamSource() == 1 || examStatisticsForPersonVo.getExamSource() == 2) {
                    tempPostionId.add(examStatisticsForPersonVo.getRelationPositionId());
                }
            }

            Map<String, UserBoundVO> userPrimaryBoundBatch = userApiV2Util.getUserPrimaryBoundBatch(tempUserId, null);
            Map<String, PositionVO> tempPositionMap = userApiV2Util.listPositionDetailInfoByIdsReturnMap(tempPostionId, null);
            for (V2ExamStatisticsForPersonVo examStatisticsForPersonVo : list) {
                if (examStatisticsForPersonVo.getExamSource() == 1 || examStatisticsForPersonVo.getExamSource() == 2) {
                    PositionVO positionEntity = tempPositionMap.get(examStatisticsForPersonVo.getRelationPositionId());
                    if (null != positionEntity) {
                        examStatisticsForPersonVo.setStudyPositionName(positionEntity.getFullName());
                    }
                }
                UserBoundVO userPrimaryBoundOne = userPrimaryBoundBatch.get(examStatisticsForPersonVo.getUserId());
                if (userPrimaryBoundOne != null) {
                    examStatisticsForPersonVo.setOrganizeId(userPrimaryBoundOne.getOrganizeId());
                    examStatisticsForPersonVo.setOrganizeName(userPrimaryBoundOne.getOrganizeName());
                    examStatisticsForPersonVo.setOrganizeEnCode(userPrimaryBoundOne.getOrganizeEnCode());
                    examStatisticsForPersonVo.setPositionId(userPrimaryBoundOne.getPositionId());
                    examStatisticsForPersonVo.setPositionName(userPrimaryBoundOne.getPositionName());
                    examStatisticsForPersonVo.setPositionEnCode(userPrimaryBoundOne.getPositionEnCode());
                    examStatisticsForPersonVo.setGradeId(userPrimaryBoundOne.getGradeId());
                    examStatisticsForPersonVo.setGradeName(userPrimaryBoundOne.getGradeName());
                }
                if (null != examStatisticsForPersonVo.getExamTime()) {
                    examStatisticsForPersonVo.setExamTime(examStatisticsForPersonVo.getExamTime() / 60);
                }
            }
        }

        PageInfo<V2ExamStatisticsForPersonVo> pageInfo = new PageInfo<>();
        pageInfo.setList(list);
        pageInfo.setPageSize((int) queryPage.getSize());
        pageInfo.setPageNum((int) queryPage.getCurrent());
        pageInfo.setTotal((int) queryPage.getTotal());
        return pageInfo;
    }

    @Override
    public AiHelperExamStatisticsVo getExamStatistics(String examId) {
        if (StringUtils.isEmpty(examId)) {
            throw new RuntimeException("考试ID不能为空");
        }
        AiHelperExamStatisticsVo statistics = ftbCultivateExamUserMapper.getExamStatistics(examId);
        if (statistics == null) {
            statistics = new AiHelperExamStatisticsVo();
            statistics.setTotalParticipants(0);
            statistics.setQualifiedCount(0);
            statistics.setPassRate(java.math.BigDecimal.ZERO);
            statistics.setPendingReviewCount(0);
        }
        return statistics;
    }
}