package jnpf.cultivate.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.base.UserInfo;
import jnpf.base.entity.SuperBaseEntity;
import jnpf.cultivate.mapper.FtbCultivateCourseMapper;
import jnpf.cultivate.mapper.FtbCultivateLearnTaskAssignmentMapper;
import jnpf.cultivate.mapper.FtbCultivatePositionCourceChapterLearningMapper;
import jnpf.cultivate.mapper.FtbCultivatePositionCourceLearningMapper;
import jnpf.cultivate.service.FtbCultivateCourseAppService;
import jnpf.cultivate.service.FtbCultivateCourseChapterService;
import jnpf.cultivate.service.FtbCultivateCourseSettingService;
import jnpf.cultivate.service.FtbCultivateCourseTriggerLogService;
import jnpf.model.cultivate.dto.course.app.FtbChapterStudyDTO;
import jnpf.model.cultivate.event.JnpfApplicationEvent;
import jnpf.model.cultivate.event.dto.course.CommonCourseProcessLearnDTO;
import jnpf.model.cultivate.event.dto.position.PositionCourseProcessDTO;
import jnpf.model.cultivate.event.dto.task.TaskCourseProcessDTO;
import jnpf.model.cultivate.po.course.FtbCultivateCourse;
import jnpf.model.cultivate.po.course.FtbCultivateCourseChapter;
import jnpf.model.cultivate.po.course.FtbCultivateCourseTriggerLog;
import jnpf.model.cultivate.po.learn.FtbCultivateLearnTaskAssignment;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceChapterLearning;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceLearning;
import jnpf.model.cultivate.vo.course.app.ChapterInformationVO;
import jnpf.model.cultivate.vo.course.app.FtbChapterAppDetails;
import jnpf.model.cultivate.vo.course.app.FtbCourseDetailsAppVO;
import jnpf.model.cultivate.vo.course.app.FtbCourseOutlineAppVO;
import jnpf.model.cultivate.vo.course.web.FtbCultivateCourseChapterDetailsVO;
import jnpf.util.context.SpringContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Title:FtbCultivateCourseAppServiceImpl
 * @Author:peng.hao
 * @create: 2023/12/2911:21
 */
@Slf4j
@Service
public class FtbCultivateCourseAppServiceImpl implements FtbCultivateCourseAppService {
    @Resource
    private FtbCultivateCourseMapper cultivateCourseMapper;
    @Resource
    private FtbCultivatePositionCourceLearningMapper ftbCultivatePositionCourceLearningMapper;
    @Resource
    private FtbCultivatePositionCourceChapterLearningMapper ftbCultivatePositionCourceChapterLearningMapper;
    @Resource
    private FtbCultivateCourseSettingService ftbCultivateCourseSettingService;
    @Resource
    private FtbCultivateCourseChapterService ftbCultivateCourseChapterService;


    @Resource
    private FtbCultivateCourseTriggerLogService ftbCultivateCourseTriggerLogService;

    @Resource
    private FtbCultivateLearnTaskAssignmentMapper ftbCultivateLearnTaskAssignmentMapper;



    @Override
    public FtbCourseDetailsAppVO courseDetails(String courseId, String userId) {
        FtbCourseDetailsAppVO ftbCourseDetailsAppVO = new FtbCourseDetailsAppVO();
        FtbCultivateCourse ftbCultivateCourse = cultivateCourseMapper.selectById(courseId);
        if (Objects.nonNull(ftbCultivateCourse)) {
            ftbCourseDetailsAppVO.setCourseId(courseId);
            ftbCourseDetailsAppVO.setCourseName(ftbCultivateCourse.getName());
            ftbCourseDetailsAppVO.setHighLights(ftbCultivateCourse.getHighLights());
            ftbCourseDetailsAppVO.setUpdateTime(ftbCultivateCourse.getLastModifyTime());
            ftbCourseDetailsAppVO.setViews(ftbCultivateCourse.getViews());
            ftbCourseDetailsAppVO.setSubtitle(ftbCultivateCourse.getSubtitle());
        }
        // 学习总时长
        LambdaQueryWrapper<FtbCultivatePositionCourceLearning> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(FtbCultivatePositionCourceLearning::getCourceId, courseId);
        lambdaQueryWrapper.eq(FtbCultivatePositionCourceLearning::getUserId, userId);
        lambdaQueryWrapper.last("limit 1");
        FtbCultivatePositionCourceLearning ftbCultivatePositionCourceLearning = ftbCultivatePositionCourceLearningMapper.selectOne(lambdaQueryWrapper);
        if (Objects.nonNull(ftbCultivatePositionCourceLearning)) {
            ftbCourseDetailsAppVO.setDuration(ftbCultivatePositionCourceLearning.getLearnTime());
        }
        // 课程学习设置
        ftbCultivateCourseSettingService.buildUpCourseLearningSettings(ftbCourseDetailsAppVO, courseId);
        return ftbCourseDetailsAppVO;
    }

    @Override
    @Transactional
    public void chapterStudy(UserInfo userInfo, FtbChapterStudyDTO ftbChapterStudyDTO) {
        log.error("chapterStudy={}", ftbChapterStudyDTO);
        // 课程学习类型,0岗位学习，1通用课程，2任务学习
        JnpfApplicationEvent<?> jpfApplicationEvent = new JnpfApplicationEvent<>(Void.TYPE);
        if (ftbChapterStudyDTO.getType() == 0) {
            jpfApplicationEvent = new JnpfApplicationEvent<>(
                    new PositionCourseProcessDTO(
                            userInfo.getUserId(),
                            ftbChapterStudyDTO.getCourseId(),
                            ftbChapterStudyDTO.getChapterId(),
                            ftbChapterStudyDTO.getDuration(),
                            ftbChapterStudyDTO.getFtbChapterTestDTOs(),
                            ftbChapterStudyDTO.getGradeId(),
                            ftbChapterStudyDTO.getType()
                    ));
        } else if (ftbChapterStudyDTO.getType() == 1) {
            jpfApplicationEvent = new JnpfApplicationEvent<>(
                    new CommonCourseProcessLearnDTO(
                            userInfo.getUserId(),
                            ftbChapterStudyDTO.getCourseId(),
                            ftbChapterStudyDTO.getChapterId(),
                            ftbChapterStudyDTO.getDuration(),
                            ftbChapterStudyDTO.getFtbChapterTestDTOs()
                    ));
        } else if (ftbChapterStudyDTO.getType() == 2) {
            //任务完成也就不再触发
            LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> taskWrapper = Wrappers.lambdaQuery();
            taskWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, ftbChapterStudyDTO.getTaskId());
            taskWrapper.eq(FtbCultivateLearnTaskAssignment::getUserId, userInfo.getUserId());
            taskWrapper.eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0);

            List<FtbCultivateLearnTaskAssignment> ftbCultivateLearnTaskAssignments = ftbCultivateLearnTaskAssignmentMapper.selectList(taskWrapper);
            if (CollUtil.isEmpty(ftbCultivateLearnTaskAssignments)) {
                return;
            }
            if (ftbCultivateLearnTaskAssignments.get(0).getStudyStats().equals(2)) {
                return;
            }
            jpfApplicationEvent = new JnpfApplicationEvent<>(
                    new TaskCourseProcessDTO(
                            userInfo.getUserId(),
                            ftbChapterStudyDTO.getCourseId(),
                            ftbChapterStudyDTO.getChapterId(),
                            ftbChapterStudyDTO.getDuration(),
                            ftbChapterStudyDTO.getFtbChapterTestDTOs(),
                            ftbChapterStudyDTO.getTaskId(),
                            ftbChapterStudyDTO.getType()
                    ));
        } else if (ftbChapterStudyDTO.getType() == 3) {
            jpfApplicationEvent = new JnpfApplicationEvent<>(
                    new CommonCourseProcessLearnDTO(
                            userInfo.getUserId(),
                            ftbChapterStudyDTO.getCourseId(),
                            ftbChapterStudyDTO.getChapterId(),
                            ftbChapterStudyDTO.getDuration(),
                            ftbChapterStudyDTO.getFtbChapterTestDTOs()
                    ));
        }
        SpringContext.getApplicationContext().publishEvent(jpfApplicationEvent);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void courseBrowsing(String courseId) {
        FtbCultivateCourse ftbCultivateCourse = cultivateCourseMapper.selectById(courseId);
        if (Objects.nonNull(ftbCultivateCourse)) {
            LambdaUpdateWrapper<FtbCultivateCourse> ftbCultivateCourseLambdaUpdateWrapper = Wrappers.lambdaUpdate();
            ftbCultivateCourseLambdaUpdateWrapper.eq(FtbCultivateCourse::getId, courseId);
            Integer views = ftbCultivateCourse.getViews() == null ? 1 : ftbCultivateCourse.getViews() + 1;
            ftbCultivateCourseLambdaUpdateWrapper.set(FtbCultivateCourse::getViews, views);
            cultivateCourseMapper.update(null, ftbCultivateCourseLambdaUpdateWrapper);
        }
    }


    /**
     * 获取课程所有章节
     *
     * @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 ftbCultivateCourseChapterService.list(courseChapterWrapper);
    }

    private 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;
        }

        for (FtbCultivatePositionCourceChapterLearning chapterLearning : list) {
            chapterLearningMap.put(chapterLearning.getChapterId(),chapterLearning);
        }
        return chapterLearningMap;
    }

    @Override
    public FtbCourseOutlineAppVO courseOutline(String courseId, String userId) {
        FtbCourseOutlineAppVO ftbCourseOutlineAppVO = new FtbCourseOutlineAppVO();
        LambdaQueryWrapper<FtbCultivateCourse> ftbCultivateCourseLambdaQueryWrapper = Wrappers.lambdaQuery();
        ftbCultivateCourseLambdaQueryWrapper.select(FtbCultivateCourse::getFormat);
        ftbCultivateCourseLambdaQueryWrapper.eq(SuperBaseEntity.SuperIBaseEntity::getId, courseId);
        FtbCultivateCourse ftbCultivateCourse = cultivateCourseMapper.selectOne(ftbCultivateCourseLambdaQueryWrapper);
        if (ftbCultivateCourse==null) {
           throw new RuntimeException("课程不存在");
        }
        List<ChapterInformationVO> chapterInformations = new ArrayList<>();
        List<FtbCultivateCourseChapter> courseChaptersList = getCourseChapters(courseId);
        if (CollUtil.isNotEmpty(courseChaptersList)) {
            List<String> chapterIds = courseChaptersList.stream().map(FtbCultivateCourseChapter::getId).collect(Collectors.toList());
            Map<String, FtbCultivatePositionCourceChapterLearning> chapterLearningMap = batchQueryCourseChapterLearningState(userId, chapterIds);
            chapterInformations = buildChapterInformations(courseChaptersList, chapterLearningMap,ftbCultivateCourse,courseId,userId);
        }
        ftbCourseOutlineAppVO.setChapterInformations(chapterInformations);
        ftbCourseOutlineAppVO.setChapterTotalNumber(chapterInformations.size());
        List<ChapterInformationVO> collect = chapterInformations.stream()
                .filter(chapterInformationVO -> chapterInformationVO.getState() == 1).collect(Collectors.toList());
        ftbCourseOutlineAppVO.setChapterFinishedNumber(collect.size());
        return ftbCourseOutlineAppVO;
    }

    private List<ChapterInformationVO> buildChapterInformations(List<FtbCultivateCourseChapter> courseChaptersList,
                                                                Map<String, FtbCultivatePositionCourceChapterLearning> chapterLearningMap,
                                                                FtbCultivateCourse ftbCultivateCourse,
                                                                String courseId, String userId
    ) {
        List<ChapterInformationVO> ret = new ArrayList<>();
        List<FtbCultivatePositionCourceChapterLearning> addChapterLearningList = new ArrayList<>();
        for (FtbCultivateCourseChapter chapter : courseChaptersList) {
            FtbCultivatePositionCourceChapterLearning chapterLearning = chapterLearningMap.get(chapter.getId());
            ChapterInformationVO chapterInformationVO = new ChapterInformationVO();
            chapterInformationVO.setChapterId(chapter.getId());
            chapterInformationVO.setChapterName(chapter.getName());
            chapterInformationVO.setSortCode(chapter.getSortCode());
            if (chapterLearning != null) {
                chapterInformationVO.setState(chapterLearning.getState());
                chapterInformationVO.setChapterTime(chapterLearning.getChapterTime());
            }else{
                chapterInformationVO.setState(0);
                chapterInformationVO.setChapterTime(0);

                FtbCultivatePositionCourceChapterLearning newLearnChapterLearning = new FtbCultivatePositionCourceChapterLearning();
                newLearnChapterLearning.setUserId(userId);
                newLearnChapterLearning.setChapterId(chapter.getId());
                newLearnChapterLearning.setCourceId(courseId);
                newLearnChapterLearning.setState(0);
                newLearnChapterLearning.setEnabledMark(0);
                addChapterLearningList.add(newLearnChapterLearning);
            }
            chapterInformationVO.setFormat(ftbCultivateCourse.getFormat());
            ret.add(chapterInformationVO);
        }
        if(CollUtil.isNotEmpty(addChapterLearningList)){
            for (FtbCultivatePositionCourceChapterLearning chapterLearning : addChapterLearningList) {
                ftbCultivatePositionCourceChapterLearningMapper.insert(chapterLearning);
            }
        }
        return ret;
    }

    @Override
    @Transactional
    public void durationRecord(UserInfo userInfo, FtbChapterStudyDTO ftbChapterStudyDTO) {
        // 学习课程章节时长增加
        LambdaUpdateWrapper<FtbCultivatePositionCourceChapterLearning> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(FtbCultivatePositionCourceChapterLearning::getChapterId, ftbChapterStudyDTO.getChapterId());
        updateWrapper.eq(FtbCultivatePositionCourceChapterLearning::getUserId, userInfo.getUserId());
        updateWrapper.eq(FtbCultivatePositionCourceChapterLearning::getEnabledMark, 0);
        updateWrapper.set(FtbCultivatePositionCourceChapterLearning::getChapterTime, ftbChapterStudyDTO.getDuration());
        ftbCultivatePositionCourceChapterLearningMapper.update(new FtbCultivatePositionCourceChapterLearning(), updateWrapper);
        // 学习课程状态变更
        LambdaQueryWrapper<FtbCultivatePositionCourceLearning> courceLearningLambdaQueryWrapper = Wrappers.lambdaQuery();
        courceLearningLambdaQueryWrapper.eq(FtbCultivatePositionCourceLearning::getCourceId, ftbChapterStudyDTO.getCourseId());
        courceLearningLambdaQueryWrapper.eq(FtbCultivatePositionCourceLearning::getUserId, userInfo.getUserId());
        courceLearningLambdaQueryWrapper.eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0);
        courceLearningLambdaQueryWrapper.last("limit 1");
        FtbCultivatePositionCourceLearning ftbCultivatePositionCourceLearning = ftbCultivatePositionCourceLearningMapper.selectOne(courceLearningLambdaQueryWrapper);
        ftbCultivatePositionCourceLearning.setLearnTime(ftbCultivatePositionCourceLearning.getLearnTime() + ftbChapterStudyDTO.getDuration());
        ftbCultivatePositionCourceLearningMapper.updateById(ftbCultivatePositionCourceLearning);


        //补充触发
        if (ftbCultivatePositionCourceLearning != null && ftbCultivatePositionCourceLearning.getState().equals(1)) {
            supplementLearningTrigger(userInfo.getUserId(), ftbChapterStudyDTO);
        }
    }


    private void supplementLearningTrigger(String userId, FtbChapterStudyDTO ftbChapterStudyDTO) {
        log.error("补充触发:chapterStudy={}", ftbChapterStudyDTO);
        // 课程学习类型,0岗位学习，1通用课程，2任务学习
        LambdaQueryWrapper<FtbCultivateCourseTriggerLog> triggerLogLambdaQueryWrapper = Wrappers.lambdaQuery();
        triggerLogLambdaQueryWrapper.eq(FtbCultivateCourseTriggerLog::getUserId, userId);
        triggerLogLambdaQueryWrapper.eq(FtbCultivateCourseTriggerLog::getCourseId, ftbChapterStudyDTO.getCourseId());
        triggerLogLambdaQueryWrapper.eq(FtbCultivateCourseTriggerLog::getType, ftbChapterStudyDTO.getType());
        if (ftbChapterStudyDTO.getType() == 0) {
            triggerLogLambdaQueryWrapper.eq(FtbCultivateCourseTriggerLog::getBusinessId, ftbChapterStudyDTO.getGradeId());
            long count = ftbCultivateCourseTriggerLogService.count(triggerLogLambdaQueryWrapper);
            if (count > 0) {
                return;
            }
            SpringContext.getApplicationContext().publishEvent(new JnpfApplicationEvent<>(
                    new PositionCourseProcessDTO(
                            userId,
                            ftbChapterStudyDTO.getCourseId(),
                            ftbChapterStudyDTO.getChapterId(),
                            ftbChapterStudyDTO.getDuration(),
                            ftbChapterStudyDTO.getFtbChapterTestDTOs(),
                            ftbChapterStudyDTO.getGradeId(),
                            ftbChapterStudyDTO.getType()
                    )));
        } else if (ftbChapterStudyDTO.getType() == 2) {
            if (StringUtils.isNotEmpty(ftbChapterStudyDTO.getTaskId())) {
                log.error("补充触发:chapterStudy={},任务id不能为null", ftbChapterStudyDTO);
                return;
            }
            //任务完成也就不再触发
            LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> taskWrapper = Wrappers.lambdaQuery();
            taskWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, ftbChapterStudyDTO.getTaskId());
            taskWrapper.eq(FtbCultivateLearnTaskAssignment::getUserId, userId);
            taskWrapper.eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0);

            List<FtbCultivateLearnTaskAssignment> ftbCultivateLearnTaskAssignments = ftbCultivateLearnTaskAssignmentMapper.selectList(taskWrapper);
            if (CollUtil.isEmpty(ftbCultivateLearnTaskAssignments)) {
                return;
            }
            if (ftbCultivateLearnTaskAssignments.get(0).getStudyStats().equals(2)) {
                return;
            }
            triggerLogLambdaQueryWrapper.eq(FtbCultivateCourseTriggerLog::getBusinessId, ftbChapterStudyDTO.getTaskId());
            long count = ftbCultivateCourseTriggerLogService.count(triggerLogLambdaQueryWrapper);
            if (count > 0) {
                return;
            }

            SpringContext.getApplicationContext().publishEvent(new JnpfApplicationEvent<>(
                    new TaskCourseProcessDTO(
                            userId,
                            ftbChapterStudyDTO.getCourseId(),
                            ftbChapterStudyDTO.getChapterId(),
                            ftbChapterStudyDTO.getDuration(),
                            ftbChapterStudyDTO.getFtbChapterTestDTOs(),
                            ftbChapterStudyDTO.getTaskId(),
                            ftbChapterStudyDTO.getType()
                    )));
        }
    }


    @Override
    public FtbChapterAppDetails chapterDetails(String id) {
        FtbCultivateCourseChapterDetailsVO ftbCultivateCourseChapterDetailsVO = ftbCultivateCourseChapterService.courseDetails(id);
        FtbChapterAppDetails ftbChapterAppDetails = FtbChapterAppDetails.convertFtbChapterAppDetails(ftbCultivateCourseChapterDetailsVO);
        // 上一章和下一章节id
        LambdaQueryWrapper<FtbCultivateCourseChapter> ftbCultivateCourseChapterLambdaQueryWrapper = Wrappers.lambdaQuery();
        ftbCultivateCourseChapterLambdaQueryWrapper.eq(FtbCultivateCourseChapter::getCourseId, ftbChapterAppDetails.getCourseId());
        ftbCultivateCourseChapterLambdaQueryWrapper.eq(FtbCultivateCourseChapter::getEnableMark, 0);
        ftbCultivateCourseChapterLambdaQueryWrapper.orderByAsc(FtbCultivateCourseChapter::getSortCode, SuperBaseEntity.SuperIBaseEntity::getId);
        List<FtbCultivateCourseChapter> ftbCultivateCourseChapters = ftbCultivateCourseChapterService.getBaseMapper()
                .selectList(ftbCultivateCourseChapterLambdaQueryWrapper);
        FtbCultivateCourseChapter[] ftbCultivateCourseChaptersArray = ftbCultivateCourseChapters.toArray(new FtbCultivateCourseChapter[0]);
        int j = 0;
        for (int i = 0; i < ftbCultivateCourseChaptersArray.length; i++) {
            if (ftbCultivateCourseChaptersArray[i].getId().equals(ftbChapterAppDetails.getId())) {
                j = i;
                break;
            }
        }
        if (j + 1 > ftbCultivateCourseChaptersArray.length - 1) {
            ftbChapterAppDetails.setNextId(null);
        } else {
            ftbChapterAppDetails.setNextId(ftbCultivateCourseChaptersArray[j + 1].getId());
        }
        if (j - 1 < 0) {
            ftbChapterAppDetails.setPreId(null);
        } else {
            ftbChapterAppDetails.setPreId(ftbCultivateCourseChaptersArray[j - 1].getId());
        }
        // 章节详情
        FtbCultivateCourse ftbCultivateCourse = cultivateCourseMapper.selectById(ftbChapterAppDetails.getCourseId());
        if (ftbCultivateCourse != null) {
            ftbChapterAppDetails.setFormat(ftbCultivateCourse.getFormat());
        }
        return ftbChapterAppDetails;
    }


}
