package jnpf.cultivate.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.cultivate.mapper.FtbCultivateCourseStatisticesMapper;
import jnpf.cultivate.mapper.FtbCultivatePositionStatisticesMapper;
import jnpf.cultivate.service.FtbCultivateCourseStatisticesService;
import jnpf.cultivate.utils.CultivatePerUtils;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.dto.course.FtbCultivateCourseOrgStatisticsDTO;
import jnpf.model.cultivate.dto.course.FtbCultivateCoursePersonStatisticesDTO;
import jnpf.model.cultivate.v2.course.web.vo.V2InnerCultivateChapterStatisticsDto;
import jnpf.model.cultivate.v2.course.web.vo.V2InnerCultivateCourseOrgStatisticsDto;
import jnpf.model.cultivate.vo.common.InnerPowerUserVO;
import jnpf.model.cultivate.vo.course.web.FtbCultivateCourseOrgStatisticesVO;
import jnpf.model.cultivate.vo.course.web.FtbCultivateCoursePersonStatisticesVO;
import jnpf.permission.vo.v2.organzie.OrganizeGeneralDetailVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.permission.vo.v2.user.UserPageListVO;
import jnpf.personnels.service.FtbPersonnelsStaffRosterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FtbCultivateCourseStatisticesServiceImpl implements FtbCultivateCourseStatisticesService {

    private static final List<String> EMPTY_LIST = List.of("-1");

    @Resource
    private FtbCultivateCourseStatisticesMapper ftbCultivateCourseStatisticesMapper;

    @Resource
    private FtbPersonnelsStaffRosterService ftbPersonnelsStaffRosterService;

    @Resource
    private FtbCultivatePositionStatisticesMapper ftbCultivatePositionStatisticesMapper;


    @Autowired
    private UserApiV2Util userApiV2Util;


    @Autowired
    CultivatePerUtils cultivatePerUtils;


    /**
     * 返回一个空的分页结果列表
     *
     * @param statisticDTO 统计查询参数DTO
     * @return 空的分页结果列表
     */
    private PageListVO<FtbCultivateCourseOrgStatisticesVO> returnEmptyList(FtbCultivateCourseOrgStatisticsDTO statisticDTO) {
        PageListVO<FtbCultivateCourseOrgStatisticesVO> pageInfo = new PageListVO<>();
        PaginationVO pagination = new PaginationVO();
        pagination.setCurrentPage(statisticDTO.getCurrentPage());
        pagination.setPageSize(statisticDTO.getPageSize());
        pagination.setTotal(0);
        pageInfo.setList(new ArrayList<>());
        pageInfo.setPagination(pagination);
        return pageInfo;
    }

    @Override
    public PageListVO<FtbCultivateCourseOrgStatisticesVO> organizationListStatistics(FtbCultivateCourseOrgStatisticsDTO statisticDTO) {
        Page<FtbCultivateCourseOrgStatisticesVO> page = statisticDTO.coverCultivatePage();
        List<FtbCultivateCourseOrgStatisticesVO> records = new ArrayList<>();
        // 多选组织情况 根据每一个组织维度统计
        List<String> orgIds;
        List<String> powerOrgList = userApiV2Util.queryPowerOrgList();
        if (CollUtil.isEmpty(powerOrgList)) {
            return returnEmptyList(statisticDTO);
        }
        // 勾选

        if ("1".equals(statisticDTO.getSelectLogo()) && CollUtil.isNotEmpty(statisticDTO.getOrgId())) {
            List<String> allOrg = new ArrayList<>(statisticDTO.getOrgId());
            List<String> allOrganize = userApiV2Util.queryChildOrgForOrgIdsReturnOrgIds(statisticDTO.getOrgId(), true, null);
            if (CollUtil.isNotEmpty(allOrganize)) {
                allOrg.addAll(allOrganize);
            }
            List<String> intersection = UserApiV2Util.getIntersection(allOrg, powerOrgList);
            if (CollUtil.isEmpty(intersection)) {
                return returnEmptyList(statisticDTO);
            }
            orgIds = intersection;
        } else if (CollUtil.isNotEmpty(statisticDTO.getOrgId())) {
            List<String> intersection = UserApiV2Util.getIntersection(statisticDTO.getOrgId(), powerOrgList);
            if (CollUtil.isEmpty(intersection)) {
                return returnEmptyList(statisticDTO);
            }
            orgIds = intersection;
        } else {
            orgIds = powerOrgList;
        }
        // 手动输入
        String dtoOrgIds = statisticDTO.getOrgIds();
        if (StringUtils.isNotEmpty(dtoOrgIds)) {
            List<String> organizationalIdCollection = cultivatePerUtils.convertOrganizationalIdCollection(dtoOrgIds);
            if (CollUtil.isEmpty(organizationalIdCollection)) {
                return returnEmptyList(statisticDTO);
            }
            List<String> intersection = UserApiV2Util.getIntersection(orgIds, organizationalIdCollection);
            if (CollUtil.isEmpty(intersection)) {
                return returnEmptyList(statisticDTO);
            }
            orgIds = intersection;
        }

        //优化批量
        List<V2InnerCultivateCourseOrgStatisticsDto> allUserCourseStudyList = ftbCultivateCourseStatisticesMapper.organizationListStatisticsV2(statisticDTO);
        if (CollUtil.isEmpty(allUserCourseStudyList)) {
            return returnEmptyList(statisticDTO);
        }
        orgIds = UserApiV2Util.uniqueStringList(orgIds);
        Map<String, OrganizeGeneralDetailVO> orgMap = userApiV2Util.organizesByOrganizeIdsReturenMap(orgIds, null);
        Map<String, List<UserPageListVO>> userListForOrgIdsReturnMap = userApiV2Util.getUserListForOrgIdsReturnMap(orgIds, null);

        Map<String, List<V2InnerCultivateCourseOrgStatisticsDto>> userIdCourseStudyMap = allUserCourseStudyList.stream().collect(Collectors.groupingBy(V2InnerCultivateCourseOrgStatisticsDto::getUserId));
        for (String orgId : orgIds) {
            List<UserPageListVO> listFeign = userListForOrgIdsReturnMap.get(orgId);// userApiV2Util.getUserListForOrgIds(List.of(orgId), null);
            if (CollUtil.isNotEmpty(listFeign)) {
                List<String> userIds = listFeign.stream().map(UserPageListVO::getId).collect(Collectors.toList());
                List<V2InnerCultivateCourseOrgStatisticsDto> statisticsDtoList = getUserStudyCourseList(userIds, userIdCourseStudyMap);
                if (CollUtil.isEmpty(statisticsDtoList)) {
                    continue;
                }
//                statisticsDtoList按照课程id分组
                Map<String, List<V2InnerCultivateCourseOrgStatisticsDto>> statisticsDtoListMap = statisticsDtoList.stream().collect(Collectors.groupingBy(V2InnerCultivateCourseOrgStatisticsDto::getCourseId));
                List<FtbCultivateCourseOrgStatisticesVO> userCouseList = new ArrayList<>();
                for (Map.Entry<String, List<V2InnerCultivateCourseOrgStatisticsDto>> entry : statisticsDtoListMap.entrySet()) {
                    List<V2InnerCultivateCourseOrgStatisticsDto> dtoList = entry.getValue(); // 获取对应的统计列表
                    FtbCultivateCourseOrgStatisticesVO item = new FtbCultivateCourseOrgStatisticesVO();
                    item.setOrgId(orgId);
                    item.setOrganizationName(orgMap.get(orgId).getName());
                    item.setSysOrganizationID(orgMap.get(orgId).getEnCode());
                    item.setCourseTitle(dtoList.get(0).getCourseName());
                    item.setCourseId(entry.getKey());
                    item.setCourseType(dtoList.get(0).getCourseTypeName());
                    item.setCourseCreationTime(dtoList.get(0).getCourseCreationTime());
                    item.setNumberInLearning(dtoList.size());
                    item.setCourseType(dtoList.get(0).getCourseTypeName());

                    Integer studyTimeTotal = 0;
                    Integer completeNum = 0;
                    for (V2InnerCultivateCourseOrgStatisticsDto dto : dtoList) {
                        studyTimeTotal += dto.getLearnTime();
                        if (dto.getState().equals(1)) {
                            completeNum++;
                        }
                    }
                    item.setNumberHaveCourse(completeNum);
                    item.setTotalDurationOfStudy(new BigDecimal(studyTimeTotal).divide(new BigDecimal(3600), 2, RoundingMode.HALF_UP));
                    item.setAverageLearningPerson(new BigDecimal(studyTimeTotal).divide(new BigDecimal(item.getNumberInLearning()), 2, RoundingMode.HALF_UP).divide(new BigDecimal(3600), 2, RoundingMode.HALF_UP));
                    userCouseList.add(item);
                }
                records.addAll(userCouseList);
            }
        }
        return CultivatePage.paginate(records, page);
    }

    private List<V2InnerCultivateCourseOrgStatisticsDto> getUserStudyCourseList(List<String> userIds, Map<String, List<V2InnerCultivateCourseOrgStatisticsDto>> userIdCourseStudyMap) {
        List<V2InnerCultivateCourseOrgStatisticsDto> ret = new ArrayList<>();
        for (String userId : userIds) {
            List<V2InnerCultivateCourseOrgStatisticsDto> statisticsDtoList = userIdCourseStudyMap.get(userId);
            if(CollUtil.isNotEmpty(statisticsDtoList)){
                ret.addAll(statisticsDtoList);
            }
        }
        return ret;
    }

    /**
     * 返回一个空的分页结果列表
     *
     * @param statisticDTO 统计查询参数DTO
     * @return 空的分页结果列表
     */
    private PageListVO<FtbCultivateCoursePersonStatisticesVO> returnEmptyList(FtbCultivateCoursePersonStatisticesDTO statisticDTO) {
        PageListVO<FtbCultivateCoursePersonStatisticesVO> pageInfo = new PageListVO<>();
        PaginationVO pagination = new PaginationVO();
        pagination.setCurrentPage(statisticDTO.getCurrentPage());
        pagination.setPageSize(statisticDTO.getPageSize());
        pagination.setTotal(0);
        pageInfo.setList(new ArrayList<>());
        pageInfo.setPagination(pagination);
        return pageInfo;
    }

    /**
     * 组织列表统计方法
     * 对给定的统计参数进行组织列表的相关统计分析，并返回统计结果列表
     *
     * @param pr 统计参数，包含了需要进行统计的组织相关的信息
     * @return 返回一个包含组织统计结果的列表
     */
    @Override
    public PageListVO<FtbCultivateCoursePersonStatisticesVO> personListStatistics(FtbCultivateCoursePersonStatisticesDTO pr) {
        String orgId = pr.getOrgId();
        Page<FtbCultivateCoursePersonStatisticesVO> page = pr.coverCultivatePage();
        List<String> queryPeoples = new ArrayList<>();


        if (StringUtils.isNotEmpty(orgId)) {
            List<UserPageListVO> userListForOrgIds = userApiV2Util.getUserListForOrgIds(List.of(orgId), null);
            if (CollUtil.isEmpty(userListForOrgIds)) {
                return returnEmptyList(pr);
            }
            List<String> userIds = userListForOrgIds.stream().map(UserPageListVO::getId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(pr.getSelectPeoples())) {
                List<String> intersection = UserApiV2Util.getIntersection(userIds, pr.getSelectPeoples());
                if (CollUtil.isEmpty(intersection)) {
                    return returnEmptyList(pr);
                }
                queryPeoples = intersection;
            } else {
                queryPeoples = userIds;
            }
        } else {
            if (CollUtil.isNotEmpty(pr.getSelectPeoples())) {
                queryPeoples = pr.getSelectPeoples();
            }
        }
//        List<String> selectPeoples = new ArrayList<>();
//        // 关键词搜索
//        if (StringUtils.isNotEmpty(pr.getKeyWords())) {
//            boolean keywordSearch = false;
//            // 员工姓名和员工ID
//            List<Map<String, String>> userIds = ftbCultivatePositionStatisticesMapper.fuzzySearchForRosterKeywords(pr.getKeyWords());
//            if (CollUtil.isNotEmpty(userIds)) {
//                selectPeoples.addAll(userIds.stream().map(a -> a.get("userId")).collect(Collectors.toList()));
//                keywordSearch = true;
//            }
//            // 组织ID
//            List<String> organizationalIdCollection = cultivatePerUtils.convertOrganizationalIdCollection(pr.getKeyWords());
//            if (CollUtil.isNotEmpty(organizationalIdCollection)) {
//                List<UserPageListVO> tempList = userApiV2Util.getUserListForOrgIds(organizationalIdCollection, null);
//                if (CollUtil.isNotEmpty(tempList)) {
//                    List<String> userIdSe = tempList.stream().map(UserPageListVO::getId).collect(Collectors.toList());
//                    selectPeoples.addAll(userIdSe);
//                    keywordSearch = true;
//                }
//            }
//            // 岗位名称
//            List<UserBoundVO> userByPositionName = userApiV2Util.getUserListForPositions(List.of(pr.getKeyWords()), null);
//            if (CollUtil.isNotEmpty(userByPositionName)) {
//                List<String> datas = userByPositionName.stream().map(UserBoundVO::getId).collect(Collectors.toList());
//                selectPeoples.addAll(datas);
//                keywordSearch = true;
//            }
//            if (!keywordSearch) {
//                return returnEmptyList(pr);
//            }
//        }
        if (CollUtil.isNotEmpty(queryPeoples)) {
            pr.setSelectPeoples(queryPeoples);
        }
        InnerPowerUserVO innerPowerUserVO = userApiV2Util.getLoginManagerUserIdsForEncode();
        if (innerPowerUserVO.getCode() == 1) {
            if (CollUtil.isNotEmpty(pr.getSelectPeoples())) {
                List<String> intersection = UserApiV2Util.getIntersection(innerPowerUserVO.getUserIds(), pr.getSelectPeoples());
                if (CollUtil.isEmpty(intersection)) {
                    return returnEmptyList(pr);
                }
                pr.setSelectPeoples(intersection);
            } else {
                pr.setSelectPeoples(innerPowerUserVO.getUserIds());
            }
        } else if (innerPowerUserVO.getCode() == 2) {
            return returnEmptyList(pr);
        }

        page = ftbCultivateCourseStatisticesMapper.personListStatistics(page, pr);
        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            List<String> courseIds = page.getRecords().stream().map(FtbCultivateCoursePersonStatisticesVO::getCourseId).distinct().collect(Collectors.toList());
            List<FtbCultivateCoursePersonStatisticesVO> courseInfo = ftbCultivateCourseStatisticesMapper.courseInfo(courseIds);
            Map<String, FtbCultivateCoursePersonStatisticesVO> courseMap = courseInfo.stream().collect(Collectors.toMap(FtbCultivateCoursePersonStatisticesVO::getCourseId, item -> item));
            // 用户id
            List<String> userIds = page.getRecords().stream().map(FtbCultivateCoursePersonStatisticesVO::getUserId).collect(Collectors.toList());
            Map<String, UserBoundVO> userMap = userApiV2Util.getUserPrimaryBoundBatchReturnMap(userIds, null);
            List<V2InnerCultivateChapterStatisticsDto> allUserCourseChapterStudyList = ftbCultivateCourseStatisticesMapper.personListStatisticsV2(userIds, List.of(1));
            Map<String, List<V2InnerCultivateChapterStatisticsDto>> userIdCourseChapterStudyMap = new HashMap<>();
            if (CollUtil.isNotEmpty(allUserCourseChapterStudyList)) {
                userIdCourseChapterStudyMap = allUserCourseChapterStudyList.stream()
                        .collect(Collectors.groupingBy(
                                item -> item.getUserId() + "_" + item.getCourseId()
                        ));
            }
            for (FtbCultivateCoursePersonStatisticesVO item : page.getRecords()) {
                FtbCultivateCoursePersonStatisticesVO ftbCultivateCoursePersonStatisticesVO = courseMap.get(item.getCourseId());
                item.setCourseTitle(ftbCultivateCoursePersonStatisticesVO.getCourseTitle());
                item.setCourseType(ftbCultivateCoursePersonStatisticesVO.getCourseType());
                item.setCourseCreationTime(ftbCultivateCoursePersonStatisticesVO.getCourseCreationTime());
                item.setCourseFormat(ftbCultivateCoursePersonStatisticesVO.getCourseFormat());
                // 所属组织_岗位_职等
                UserBoundVO userBoundVO = userMap.get(item.getUserId());
                if (userBoundVO != null) {
                    item.setEmployeeSName(userBoundVO.getUserName());
                    item.setEmployeeId(userBoundVO.getSystemWorkerId());
                    String tempName = userBoundVO.getOrganizeName();
                    if (StringUtils.isNotEmpty(userBoundVO.getPositionName())) {
                        tempName = tempName + "_" + userBoundVO.getPositionName();
                    }
                    if (StringUtils.isNotEmpty(userBoundVO.getGradeName())) {
                        tempName = tempName + "_" + userBoundVO.getGradeName();
                    }
                    item.setAffiliatedOrgPosLevel(tempName);
                }

                // 参与学习时长(h)
                item.setParticipationTimeInStudy(CultivatePerUtils.computeDivision(item.getParticipationTimeInStudy()));
                // 学习进度 已学习章节数/总章节数
                List<V2InnerCultivateChapterStatisticsDto> v2InnerCultivateChapterStatisticsDtos = userIdCourseChapterStudyMap.get(item.getUserId() + "_" + item.getCourseId());
                Integer numberOfStudyChapters = 0;
                if (CollUtil.isNotEmpty(v2InnerCultivateChapterStatisticsDtos)) {
                    numberOfStudyChapters = v2InnerCultivateChapterStatisticsDtos.size();
                }
                Integer totalOfStudyChapters = ftbCultivateCoursePersonStatisticesVO.getChapterNumber();
                item.setLearningProgress(CultivatePerUtils.computeDivision(numberOfStudyChapters, totalOfStudyChapters));
            }
        }
        return CultivatePage.coverPageList(page);
    }

}
