package jnpf.cultivate.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import jnpf.authority.service.FtbPermissionUsersService;
import jnpf.base.vo.PageListVO;
import jnpf.cultivate.mapper.FtbCultivatePositionCourceChapterLearningMapper;
import jnpf.cultivate.mapper.FtbCultivatePositionCourceLearningMapper;
import jnpf.cultivate.service.CultivateIdentifyApplyService;
import jnpf.cultivate.service.FtbCultivateCourseChapterService;
import jnpf.cultivate.service.FtbCultivateExamUserService;
import jnpf.cultivate.service.FtbCultivatePositionMemberService;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.cultivate.v2.service.V2CultivateBatchQueryService;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.po.course.FtbCultivateCourseChapter;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceChapterLearning;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceLearning;
import jnpf.model.cultivate.resp.AppExamListVo;
import jnpf.model.cultivate.resp.UserExamCount;
import jnpf.model.cultivate.v2.course.vo.app.V2ChapterVo;
import jnpf.model.cultivate.v2.course.vo.app.V2CourseOutlineAppVo;
import jnpf.model.cultivate.vo.identify.IdentifyApplyStatisticsApiVo;
import jnpf.model.cultivate.vo.identify.UserIdentifyPageVo;
import jnpf.model.cultivate.vo.position.FtbCultivateCourseListVO;
import jnpf.model.cultivate.vo.position.FtbCultivatePositionUserInfoVo;
import jnpf.permission.dto.v2.user.QueryPageUserDTO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.JsonUtil;
import jnpf.util.StringUtil;
import jnpf.util.UploaderUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Title:FtbCultivatePositionMemberServiceImpl
 * @Author:peng.hao
 * @create: 2023/12/2819:23
 */
@Service
public class FtbCultivatePositionMemberServiceImpl implements FtbCultivatePositionMemberService {

    @Resource
    FtbCultivateExamUserService ftbCultivateExamUserService;

    @Resource
    private FtbCultivatePositionCourceChapterLearningMapper ftbCultivatePositionCourceChapterLearningMapper;
    @Resource
    private FtbCultivatePositionCourceLearningMapper ftbCultivatePositionCourceLearningMapper;

    @Resource
    CultivateIdentifyApplyService cultivateIdentifyApplyService;

    @Autowired
    private UserApiV2Util userApiV2Util;

    @Autowired
    private FtbPermissionUsersService ftbPermissionUsersService;

    @Autowired
    private FtbCultivateCourseChapterService courseChapterService;

    @Autowired
    private V2CultivateBatchQueryService v2CultivateBatchQueryService;

    @Override
    public PageListVO<FtbCultivatePositionUserInfoVo> listUser(QueryPageUserDTO searchDto) {
//        UserQueryDto queryDto = new UserQueryDto();
//        queryDto.setQueryCondition(keyWords);
//        queryDto.setCurrentPage((int) page.getCurrentPage());
//        queryDto.setPageSize((int) page.getPageSize());
        //查询所有用户
//        PageListVO<PartUserInfoVo> partUserInfoPage = userApi.getPartUserInfoPage(queryDto);
//        PageListVO<UserBoundVO> partUserInfoPage = userApiV2Util.listAllUserForPage(page.getPageSize(), page.getCurrentPage(), keyWords, null);
        QueryPageUserDTO dto = new QueryPageUserDTO();
        dto.setTenantId(userApiV2Util.getCurrentLoginTenantId());
        if (searchDto.getPageSize() == 0) {
            dto.setPageSize(10L);
        } else {
            dto.setPageSize(searchDto.getPageSize());
        }
        if (searchDto.getCurrentPage() <= 1) {
            dto.setCurrentPage(1L);
        } else {
            dto.setCurrentPage(searchDto.getCurrentPage());
        }
        if (StringUtil.isNotEmpty(searchDto.getKeyword())) {
            dto.setKeyword(searchDto.getKeyword());
        }
        if (CollUtil.isNotEmpty(searchDto.getOrganizeIds())) {
            dto.setOrganizeIds(searchDto.getOrganizeIds());
        }
        if (StringUtil.isNotEmpty(searchDto.getPositionId())) {
            dto.setPositionId(searchDto.getPositionId());
        }
        PageListVO<UserBoundVO> partUserInfoPage = ftbPermissionUsersService.pagePost(dto);

        PageListVO<FtbCultivatePositionUserInfoVo> userInfoPage = new PageListVO<>();
        userInfoPage.setPagination(partUserInfoPage.getPagination());

        List<UserBoundVO> list = partUserInfoPage.getList();
        List<FtbCultivatePositionUserInfoVo> infoVoList = JsonUtil.getJsonToList(JsonUtil.getObjectToString(list), FtbCultivatePositionUserInfoVo.class);
        infoVoList.forEach(item -> {
            item.setHeadIcon(UploaderUtil.uploaderImg(item.getHeadIcon()));
        });
        userInfoPage.setList(infoVoList);
        List<String> positionIds = infoVoList.stream().map(FtbCultivatePositionUserInfoVo::getPositionId).collect(Collectors.toList());
        //筛选出所有的用户ids
        List<String> userIds = infoVoList.stream().map(FtbCultivatePositionUserInfoVo::getId).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(positionIds)) {
            return userInfoPage;
        }
        // 鉴定统计
        Map<String, IdentifyApplyStatisticsApiVo> userIdentifyStatistics = cultivateIdentifyApplyService.getUserIdentifyStatistics(userIds);
        // 接入课程统计
        Map<String, FtbCultivateCourseListVO> stringFtbCultivateCourseListVOMap = doAccessCourseStatistics(userIds);
        // 考试统计
        Map<String, UserExamCount> stringUserExamCountMap = ftbCultivateExamUserService.queryExamTotalAndCompleteNumForUserIds(userIds);
        infoVoList.forEach(item -> {
            UserExamCount userExamCount = stringUserExamCountMap.get(item.getId());
            if (Objects.nonNull(userExamCount)) {
                item.setFinishExamNumber(userExamCount.getCompleteNum().longValue());
                item.setTotalExamNumber(userExamCount.getTotleNum().longValue());
            }
            FtbCultivateCourseListVO ftbCultivateCourseListVO = stringFtbCultivateCourseListVOMap.get(item.getId());
            if (Objects.nonNull(ftbCultivateCourseListVO)) {
                item.setTotalCourseNumber(ftbCultivateCourseListVO.getTotalNumberOfStudies().longValue());
                item.setFinishCourseNumber(ftbCultivateCourseListVO.getNumbersLearned().longValue());
            }
            IdentifyApplyStatisticsApiVo identifyApplyStatisticsApiVo = userIdentifyStatistics.get(item.getId());
            if (Objects.nonNull(identifyApplyStatisticsApiVo)) {
                item.setTotalIdentifyNumber(identifyApplyStatisticsApiVo.getTotalNumber().longValue());
                item.setFinishIdentifyNumber(identifyApplyStatisticsApiVo.getAlreadyNumber().longValue());
            }
        });
        return userInfoPage;
    }

    /**
     * 获取课程所有章节
     *
     * @param courseId 课程ID
     * @return 章节列表
     */
    private List<FtbCultivateCourseChapter> getCourseChapters(String courseId) {
        LambdaQueryWrapper<FtbCultivateCourseChapter> courseChapterWrapper = Wrappers.lambdaQuery();
        courseChapterWrapper.eq(FtbCultivateCourseChapter::getCourseId, courseId);
        courseChapterWrapper.eq(FtbCultivateCourseChapter::getEnableMark, 0);
        return courseChapterService.list(courseChapterWrapper);
    }

    /**
     * 批量查询用户学习状态
     *
     * @param userId      用户ID
     * @param chapterList 章节ID列表
     * @return 章节学习状态列表
     */
    public Map<String, FtbCultivatePositionCourceChapterLearning> batchQueryCourseChapterLearningState(String userId, List<String> chapterList) {

        Map<String, FtbCultivatePositionCourceChapterLearning> chapterLearningMap = new HashMap<>();
        LambdaQueryWrapper<FtbCultivatePositionCourceChapterLearning> queryChapterWrapper = Wrappers.lambdaQuery();
        queryChapterWrapper.in(FtbCultivatePositionCourceChapterLearning::getChapterId, chapterList);
        queryChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getUserId, userId);
        queryChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getEnabledMark, 0);
        List<FtbCultivatePositionCourceChapterLearning> list = ftbCultivatePositionCourceChapterLearningMapper.selectList(queryChapterWrapper);
        if (CollUtil.isEmpty(list)) {
            return chapterLearningMap;
        }
        return list.stream()
                .collect(Collectors.toMap(FtbCultivatePositionCourceChapterLearning::getId, item -> item));
    }

    /**
     * 获取用户课程列表
     *
     * @param userId 用户ID
     * @param page   分页参数
     * @return 课程列表
     */
    @Override
    public PageListVO<FtbCultivateCourseListVO> listCourse(String userId, CultivatePage page) {
        Page<FtbCultivateCourseListVO> pageList = page.coverCultivatePage();
        pageList = ftbCultivatePositionCourceChapterLearningMapper.getCourseInformationList(pageList, userId);
        
        // 提取所有课程ID
        List<String> courseIds = pageList.getRecords().stream()
                .map(FtbCultivateCourseListVO::getCourseId)
                .collect(Collectors.toList());
        
        // 使用V2批量查询接口，一次性获取所有课程的章节及学习状态
        Map<String, List<V2ChapterVo>> courseChapterMap = v2CultivateBatchQueryService.batchQueryUserCourseChapterLearnStatus(userId, courseIds);
        
        // 填充每个课程的信息
        pageList.getRecords().forEach(ftbCultivateCourseListVO -> {
            String courseId = ftbCultivateCourseListVO.getCourseId();
            List<V2ChapterVo> chapterTree = courseChapterMap.getOrDefault(courseId, new java.util.ArrayList<>());
            
            // 计算已学章节数和总章节数
            long completedCount = chapterTree.stream()
                    .flatMap(this::flattenChapters)
                    .filter(chapter -> chapter.getState() != null && chapter.getState() == 1)
                    .count();
            long totalCount = chapterTree.stream()
                    .flatMap(this::flattenChapters)
                    .count();
            
            ftbCultivateCourseListVO.setNumbersLearned((int) completedCount);
            ftbCultivateCourseListVO.setTotalNumberOfStudies((int) totalCount);
            ftbCultivateCourseListVO.setChapterInformationVOS(chapterTree);
            ftbCultivateCourseListVO.setUserId(userId);
        });
        return CultivatePage.coverPageList(pageList);
    }

    /**
     * 递归展平章节树，用于统计所有章节数量
     */
    private java.util.stream.Stream<V2ChapterVo> flattenChapters(V2ChapterVo chapter) {
        java.util.stream.Stream<V2ChapterVo> selfStream = java.util.stream.Stream.of(chapter);
        if (CollUtil.isNotEmpty(chapter.getChild())) {
            return java.util.stream.Stream.concat(
                    selfStream,
                    chapter.getChild().stream().flatMap(this::flattenChapters)
            );
        }
        return selfStream;
    }

    private Map<String, FtbCultivateCourseListVO> doAccessCourseStatistics(List<String> userIds) {
        if (CollUtil.isEmpty(userIds)) {
            return new HashMap<>();
        }
        List<FtbCultivatePositionCourceLearning> positionCourceLearningList =
                ftbCultivatePositionCourceLearningMapper.accessCourseStatistics(userIds);
        if (CollUtil.isEmpty(positionCourceLearningList)) {
            return new HashMap<>();
        }
        // 按用户分组
        Map<String, List<FtbCultivatePositionCourceLearning>> collected = positionCourceLearningList
                .stream()
                .collect(Collectors.groupingBy(FtbCultivatePositionCourceLearning::getUserId));
        // 组装数据
        return collected
                .entrySet()
                .stream()
                .collect(Collectors.toMap(Map.Entry::getKey, entry -> {
                    FtbCultivateCourseListVO ftbCultivateCourseListVO = new FtbCultivateCourseListVO();
                    ftbCultivateCourseListVO.setTotalNumberOfStudies(entry.getValue().size());
                    List<FtbCultivatePositionCourceLearning> collect = entry.getValue().stream().filter(item -> item.getState() == 1).collect(Collectors.toList());
                    ftbCultivateCourseListVO.setNumbersLearned(collect.size());
                    return ftbCultivateCourseListVO;
                }));
    }

    /**
     * 考试用户服务
     */

    @Autowired
    private FtbCultivateExamUserService examUserService;

    /**
     * 根据用户ID 分页查询考试列表
     *
     * @param userId 用户ID
     * @param page
     * @return
     */
    @Override
    public PageInfo<AppExamListVo> listExam(String userId, CultivatePage page) {
        return examUserService.queryExamListForUserId(userId, page);
    }

    @Override
    public PageListVO<UserIdentifyPageVo> listIdentify(String userId, CultivatePage page) {
        PageListVO<UserIdentifyPageVo> userIdentifyPage = cultivateIdentifyApplyService.getUserIdentifyPage(userId, page);
        return userIdentifyPage;
    }


}
