package jnpf.cultivate.v2.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jnpf.base.UserInfo;
import jnpf.cultivate.mapper.FtbCultivateChapterTestResultMapper;
import jnpf.cultivate.mapper.FtbCultivateCourseMapper;
import jnpf.cultivate.service.FtbCultivateCourseChapterService;
import jnpf.cultivate.service.FtbCultivateCourseSettingService;
import jnpf.cultivate.service.impl.FtbCultivatePositionCourceChapterLearningService;
import jnpf.cultivate.service.impl.FtbCultivatePositionCourceLearningService;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.cultivate.v2.service.*;
import jnpf.cultivate.v2.util.CultivateMqSendUtil;
import jnpf.entity.cultivate.CultivateIdentifyApply;
import jnpf.entity.cultivate.CultivateIdentifyTable;
import jnpf.entity.cultivate.FtbCultivateCourseLearningLogEntity;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.po.course.FtbCultivateChapterTestResult;
import jnpf.model.cultivate.po.course.FtbCultivateCourse;
import jnpf.model.cultivate.po.course.FtbCultivateCourseChapter;
import jnpf.model.cultivate.po.exam.FtbCultivateExam;
import jnpf.model.cultivate.po.exam.FtbCultivateExamUser;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceChapterLearning;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceLearning;
import jnpf.model.cultivate.v2.course.vo.app.*;
import jnpf.model.cultivate.v2.enums.PositionBusinessSourceEnum;
import jnpf.model.cultivate.v2.position.req.V2MyCultivateCommonCourseForAppReq;
import jnpf.model.cultivate.vo.chapter.FtbCultivateChapterTestResultVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.UserProvider;
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.*;
import java.util.stream.Collectors;

import static jnpf.model.cultivate.v2.enums.PositionBusinessSourceEnum.GENERAL_COURSE;

@Slf4j
@Service
public class V2CultivateCourseAppServiceImpl implements V2CultivateCourseAppService {
    @Autowired
    private FtbCultivateCourseMapper cultivateCourseMapper;


    @Autowired
    private FtbCultivateChapterTestResultMapper ftbCultivateChapterTestResultMapper;

    @Autowired
    private FtbCultivatePositionCourceLearningService courseLearningService;
    @Autowired
    private FtbCultivatePositionCourceChapterLearningService chapterLearningService;

    @Autowired
    private FtbCultivateCourseChapterService courseChapterService;

    @Autowired
    protected FtbCultivateCourseSettingService ftbCultivateCourseSettingService;

    @Autowired
    private CultivateMqSendUtil cultivateMqSendUtil;
    @Autowired
    private UserApiV2Util userApiV2Util;

    @Autowired
    private V2CultivateBatchQueryService v2CultivateBatchQueryService;

    @Autowired
    private FtbCultivateCourseLearningLogService ftbCultivateCourseLearningLogService;


    @Autowired
    private V2CultivatePostStudyService v2CultivatePostStudyService;

    @Autowired
    private V2CultivateTaskStudyService v2CultivateTaskStudyService;

    /**
     * 课程详情
     *
     * @param courseId 课程id
     * @param userId   用户id
     * @return 课程详情
     */
    @Override
    public V2CourseDetailsAppVO courseDetails(V2CourseAppDto dto) {
        String courseId = dto.getCourseId();
        String userId = dto.getUserId();
        V2CourseDetailsAppVO retVo = new V2CourseDetailsAppVO();
        FtbCultivateCourse ftbCultivateCourse = cultivateCourseMapper.selectById(courseId);
        if (Objects.isNull(ftbCultivateCourse)) {
            throw new RuntimeException("课程不存在");
        }

        retVo.setCourseId(courseId);
        retVo.setCourseName(ftbCultivateCourse.getName());
        retVo.setUpdateTime(ftbCultivateCourse.getLastModifyTime());
        retVo.setViews(ftbCultivateCourse.getViews());
        retVo.setSubtitle(ftbCultivateCourse.getSubtitle());
        retVo.setTypeId(ftbCultivateCourse.getTypeId());
        retVo.setCoverId(ftbCultivateCourse.getCoverId());
        retVo.setCoverUrl(ftbCultivateCourse.getCoverUrl());
        retVo.setHighLights(ftbCultivateCourse.getHighLights());
        retVo.setNeedExamAndIdentify(ftbCultivateCourse.getNeedExamAndIdentify());

        // 学习总时长
        LambdaQueryWrapper<FtbCultivatePositionCourceLearning> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(FtbCultivatePositionCourceLearning::getCourceId, courseId)
                .eq(FtbCultivatePositionCourceLearning::getUserId, userId)
                .last("limit 1");
        FtbCultivatePositionCourceLearning courseLearning = courseLearningService.getOne(lambdaQueryWrapper);
        Optional.ofNullable(courseLearning)
                .ifPresentOrElse(
                        cl -> {
                            retVo.setDuration(cl.getLearnTime());
                            retVo.setState(cl.getState());
                        },
                        () -> {
                            retVo.setDuration(0);
                            retVo.setState(0);
                        }
                );


        //课程学习
        if (ftbCultivateCourse.getNeedExamAndIdentify() != null && ftbCultivateCourse.getNeedExamAndIdentify().equals(1)) {
            if (dto.getBusinessSource() != null && (dto.getBusinessSource().equals(PositionBusinessSourceEnum.GENERAL_COURSE)
                    || dto.getBusinessSource().equals(PositionBusinessSourceEnum.OFFLINE_CLASS))) {
                if (StringUtils.isNotEmpty(ftbCultivateCourse.getExamId())) {
                    Map<String, FtbCultivateExam> examBasicInfoMap = v2CultivateBatchQueryService.batchQueryExamsByIds(List.of(ftbCultivateCourse.getExamId()), 0);
                    FtbCultivateExam ftbCultivateExam = examBasicInfoMap.get(ftbCultivateCourse.getExamId());
                    if (ftbCultivateExam != null) {
                        AppCultivateCourseExamVo exam = new AppCultivateCourseExamVo();
                        exam.setExamId(ftbCultivateExam.getId());
                        exam.setExamName(ftbCultivateExam.getExamName());

                        Map<String, FtbCultivateExamUser> userExamStatusMap = v2CultivateBatchQueryService.batchQueryUserExamStatus(userId, List.of(ftbCultivateExam.getId()));
                        FtbCultivateExamUser ftbCultivateExamUser = userExamStatusMap.get(ftbCultivateExam.getId());
                        if (ftbCultivateExamUser != null) {
                            exam.setExamStatus(ftbCultivateExamUser.getStatus());
                            exam.setExamCompleteDate(ftbCultivateExamUser.getFinishTime());
                            exam.setUserExamId(ftbCultivateExamUser.getId());
                            exam.setUserExamScore(ftbCultivateExamUser.getScore());
                            exam.setExamTotalScore(ftbCultivateExamUser.getTotalScore());
                            exam.setUserExamDuration(ftbCultivateExamUser.getDuration());
                        } else {
                            exam.setExamStatus(0);
                            if (retVo.getState().equals(1) && dto.getBusinessSource() != null
                                    && (dto.getBusinessSource() == PositionBusinessSourceEnum.GENERAL_COURSE || dto.getBusinessSource() == PositionBusinessSourceEnum.OFFLINE_CLASS)) {
                                String userExamId = v2CultivatePostStudyService.preCommonCourseStudy(userId, courseId, UserProvider.getUser().getTenantId());
                                exam.setUserExamId(userExamId);
                            } else {
                                exam.setUserExamId("");
                            }
                        }
                        retVo.setExam(exam);
                    }
                }
                if (StringUtils.isNotEmpty(ftbCultivateCourse.getIdentifyId())) {
                    Map<String, CultivateIdentifyTable> identityBasicInfoMap = v2CultivateBatchQueryService.batchQueryIdentificationsByIds(List.of(ftbCultivateCourse.getIdentifyId()), 0);
                    CultivateIdentifyTable identityTable = identityBasicInfoMap.get(ftbCultivateCourse.getIdentifyId());
                    if (identityTable != null) {
                        AppCultivateCourseIdentityVo identity = new AppCultivateCourseIdentityVo();
                        identity.setIdentityId(identityTable.getId());
                        identity.setIdentityName(identityTable.getName());

                        Map<String, CultivateIdentifyApply> userIdentificationStatusMap = v2CultivateBatchQueryService.batchQueryUserIdentificationStatus(userId, List.of(identityTable.getId()), 1, courseId);

                        CultivateIdentifyApply identifyApply = userIdentificationStatusMap.get(identityTable.getId());
                        if (identifyApply != null) {
                            identity.setIdentificationResult(identifyApply.getResult());
                            identity.setIdentificationStatus(identifyApply.getStatus());
                            identity.setUserIdentityId(identifyApply.getId());
                        } else {
                            identity.setIdentificationStatus(0);
                            identity.setUserIdentityId("");
                        }

                        retVo.setIdentity(identity);
                    }
                }
            }
        }
        return retVo;
    }

    /**
     * 课程大纲
     *
     * @param courseId 课程id
     * @param userId   用户id
     * @return 课程详情
     */
    @Override
    public V2CourseOutlineAppVo courseOutline(String courseId, String userId) {

        FtbCultivateCourse ftbCultivateCourse = cultivateCourseMapper.selectById(courseId);
        if (Objects.isNull(ftbCultivateCourse)) {
            throw new RuntimeException("课程不存在");
        }

        V2CourseOutlineAppVo ftbCourseOutlineAppVO = new V2CourseOutlineAppVo();
        ftbCourseOutlineAppVO.initData();
        ftbCourseOutlineAppVO.setCourseId(courseId);
        ftbCourseOutlineAppVO.setCourseName(ftbCultivateCourse.getName());
        ftbCourseOutlineAppVO.setCoverUrl(ftbCultivateCourse.getCoverUrl());
        ftbCourseOutlineAppVO.setHighLights(ftbCultivateCourse.getHighLights());
        // 查询课程章节信息
        List<FtbCultivateCourseChapter> chapters = getCourseChapters(courseId);
        // 批量查询课程章节学习信息
        if (CollUtil.isEmpty(chapters)) {
            return ftbCourseOutlineAppVO;
        }

        List<String> chapterList = chapters.stream().map(FtbCultivateCourseChapter::getId).collect(Collectors.toList());
        Map<String, FtbCultivatePositionCourceChapterLearning> chapterLearningMap = v2CultivateBatchQueryService.batchQueryCourseChapterLearningState(userId, chapterList);
        List<V2ChapterVo> chapterTree = V2CourseOutlineAppVo.buildChapterVoTree(chapters, chapterLearningMap);
        ftbCourseOutlineAppVO.setChapterVoList(chapterTree);
        ftbCourseOutlineAppVO.setChapterTotalNumber(chapters.size());
        ftbCourseOutlineAppVO.setChapterFinishedNumber(V2CourseOutlineAppVo.calCompleteChapterNumber(chapterLearningMap));
        return ftbCourseOutlineAppVO;
    }


    /**
     * 章节详情
     *
     * @param id 章节id,必填
     * @return 课程章节详情
     */
    @Override
    public V2ChapterAppDetails chapterDetails(String id, String userId) {
        V2ChapterAppDetails retVo = courseChapterService.courseDetailsV2(id);
        Map<String, FtbCultivatePositionCourceChapterLearning> chapterLearningMap = v2CultivateBatchQueryService.batchQueryCourseChapterLearningState(userId, List.of(id));
        FtbCultivatePositionCourceChapterLearning chapterLearning = chapterLearningMap.get(id);
        if (chapterLearning != null) {
            retVo.setState(chapterLearning.getState());
            retVo.setChapterTime(chapterLearning.getChapterTime());
            retVo.setLastVideoStudyTime(chapterLearning.getLastVideoStudyTime());
        } else {
            retVo.setState(0);
            retVo.setChapterTime(0);
        }


        LambdaQueryWrapper<FtbCultivateChapterTestResult> testResultQuery = Wrappers.lambdaQuery();
        testResultQuery.eq(FtbCultivateChapterTestResult::getCourseId, retVo.getCourseId());
        testResultQuery.eq(FtbCultivateChapterTestResult::getCourseChapterId, id);
        testResultQuery.eq(FtbCultivateChapterTestResult::getUserId, userId);
        testResultQuery.eq(FtbCultivateChapterTestResult::getEnableMark, 0);
        testResultQuery.orderByDesc(FtbCultivateChapterTestResult::getCreatorTime);
        List<FtbCultivateChapterTestResult> ftbCultivateChapterTestResults = ftbCultivateChapterTestResultMapper.selectList(testResultQuery);

        if (CollUtil.isNotEmpty(ftbCultivateChapterTestResults)) {
            FtbCultivateChapterTestResult testResult = ftbCultivateChapterTestResults.get(0);
            if (StringUtils.isNotEmpty(testResult.getChapterTestOptions())) {
                List<FtbCultivateChapterTestResultVO> chapterTestList = JSONObject.parseArray(testResult.getChapterTestOptions(), FtbCultivateChapterTestResultVO.class);
                retVo.setUserTestResultList(chapterTestList);
            }
        }

        // 查询课程章节信息
        List<FtbCultivateCourseChapter> chapters = getCourseChapters(retVo.getCourseId());
        // 批量查询课程章节学习信息
        if (CollUtil.isEmpty(chapters)) {
            return retVo;
        }

        List<V2ChapterVo> chapterTree = V2CourseOutlineAppVo.buildChapterVoTree(chapters, new HashMap<>());
        Map<String, String> stringStringMap = V2ChapterAppDetails.lineVo(chapterTree, id);
        retVo.setPreId(stringStringMap.get("preId"));
        retVo.setNextId(stringStringMap.get("nextId"));
        return retVo;
    }

    /**
     * 章节学习
     *
     * @param req 章节学习参数
     */
    @Override
    public void chapterStudy(V2ChapterStudyVo req) {
        // 获取当前用户信息

        UserInfo user = UserProvider.getUser();
        String userId = user.getUserId();
        String tenantId = user.getTenantId();

        // 查询课程的所有章节并检查是否存在
        List<FtbCultivateCourseChapter> chapterList = getCourseChapters(req.getCourseId());
        if (CollUtil.isEmpty(chapterList)) {
            return;
        }

        // 完成课程章节学习
        completeCourseChapterLearning(req, userId, tenantId);

        // 计算并更新课程整体学习状态
        List<String> allChapterIds = chapterList.stream()
                .map(FtbCultivateCourseChapter::getId)
                .collect(Collectors.toList());
        Integer courseState = calculateCourseState(req.getCourseId(), userId, allChapterIds);
        updateOrCreateCourseLearning(req, userId, tenantId, courseState);
        // 如果课程已完成，发送消息通知
        if (Objects.equals(courseState, 1)) {
            //记录学习记录
            ftbCultivateCourseLearningLogService.save(FtbCultivateCourseLearningLogEntity.builder()
                    .courseId(req.getCourseId()).learnTime(0).creatorUserId(userId).creatorTime(new Date())
                    .tenantId(user.getTenantId()).enabledMark(0).status(1).build()
            );
            if (req.getBusinessSource() != null) {
                switch (req.getBusinessSource()) {
                    case POST_LEARNING:
                        v2CultivatePostStudyService.prePositionCourseStudy(userId, req.getCourseId(), req.getBusinessSourceId(), req.getGradeId(), tenantId);
                        break;
                    case TASK_LEARNING:
                        v2CultivateTaskStudyService.preTaskCourseStudy(userId, req.getCourseId(), req.getBusinessSourceId(), tenantId);
                        break;
                    default:
                        v2CultivatePostStudyService.preCommonCourseStudy(userId, req.getCourseId(), tenantId);
                        break;
                }
            }
            cultivateMqSendUtil.sendCourseCompletionMessage(req, userId, tenantId);
        }
    }

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

    /**
     * 完成章节学习记录
     *
     * @param req      章节学习参数
     * @param userId   用户ID
     * @param tenantId 租户ID
     */
    private void completeCourseChapterLearning(V2ChapterStudyVo req, String userId, String tenantId) {
        String params = buildStudyParam(req, userId);
        LambdaQueryWrapper<FtbCultivatePositionCourceChapterLearning> queryChapterWrapper = Wrappers.lambdaQuery();
        queryChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getCourceId, req.getCourseId());
        queryChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getChapterId, req.getChapterId());
        queryChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getUserId, userId);
        queryChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getEnabledMark, 0);
        List<FtbCultivatePositionCourceChapterLearning> existingChapter = chapterLearningService.list(queryChapterWrapper);

        if (CollUtil.isNotEmpty(existingChapter)) {
            // 更新现有章节学习记录
            LambdaUpdateWrapper<FtbCultivatePositionCourceChapterLearning> updateChapterWrapper = Wrappers.lambdaUpdate();
            updateChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getCourceId, req.getCourseId());
            updateChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getChapterId, req.getChapterId());
            updateChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getUserId, userId);
            updateChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getEnabledMark, 0);
            updateChapterWrapper.set(FtbCultivatePositionCourceChapterLearning::getState, 1);
            updateChapterWrapper.set(FtbCultivatePositionCourceChapterLearning::getLastModifyTime, new Date());
            updateChapterWrapper.set(FtbCultivatePositionCourceChapterLearning::getLastStudyParams, params);
//            updateChapterWrapper.setSql("F_ChapterTime = F_ChapterTime + " + req.getDuration());//前端沟通完成后，取消学习时长累加
            chapterLearningService.update(new FtbCultivatePositionCourceChapterLearning(), updateChapterWrapper);
        } else {
            // 创建新的章节学习记录
            FtbCultivatePositionCourceChapterLearning chapterLearning = new FtbCultivatePositionCourceChapterLearning();
            chapterLearning.setCourceId(req.getCourseId());
            chapterLearning.setChapterId(req.getChapterId());
            chapterLearning.setUserId(userId);
            chapterLearning.setEnabledMark(0);
            chapterLearning.setState(1);
//            chapterLearning.setChapterTime(req.getDuration());
            chapterLearning.setTenantId(tenantId);
            chapterLearning.setLastModifyTime(new Date());
            chapterLearning.setLastStudyParams(params);
            chapterLearningService.save(chapterLearning);
        }
    }

    /**
     * 计算课程学习状态
     *
     * @param courseId      课程ID
     * @param userId        用户ID
     * @param allChapterIds 课程所有章节ID列表
     * @return 课程学习状态：0-未学习，1-已学习，2-学习中
     */
    private Integer calculateCourseState(String courseId, String userId, List<String> allChapterIds) {
        LambdaQueryWrapper<FtbCultivatePositionCourceChapterLearning> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(FtbCultivatePositionCourceChapterLearning::getCourceId,
                FtbCultivatePositionCourceChapterLearning::getUserId,
                FtbCultivatePositionCourceChapterLearning::getChapterId);
        queryWrapper.eq(FtbCultivatePositionCourceChapterLearning::getCourceId, courseId);
        queryWrapper.eq(FtbCultivatePositionCourceChapterLearning::getUserId, userId);
        queryWrapper.eq(FtbCultivatePositionCourceChapterLearning::getState, 1);
        queryWrapper.eq(FtbCultivatePositionCourceChapterLearning::getEnabledMark, 0);
        List<FtbCultivatePositionCourceChapterLearning> courseLearningList = chapterLearningService.list(queryWrapper);

        if (CollUtil.isNotEmpty(courseLearningList)) {
            List<String> completedChapterIds = courseLearningList.stream()
                    .map(FtbCultivatePositionCourceChapterLearning::getChapterId)
                    .collect(Collectors.toList());
            // 如果已完成的章节ID列表包含所有章节ID，则课程已完成
            if (new HashSet<>(completedChapterIds).containsAll(allChapterIds)) {
                return 1; // 已学习
            }
        }

        return 2; // 学习中
    }

    /**
     * 更新或创建课程学习记录
     *
     * @param req         章节学习参数
     * @param userId      用户ID
     * @param tenantId    租户ID
     * @param courseState 课程学习状态
     */
    private void updateOrCreateCourseLearning(V2ChapterStudyVo req, String userId, String tenantId, Integer courseState) {
        LambdaQueryWrapper<FtbCultivatePositionCourceLearning> courseLearningWrapper = Wrappers.lambdaQuery();
        courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getCourceId, req.getCourseId());
        courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getUserId, userId);
        courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0);
        List<FtbCultivatePositionCourceLearning> courseLearningList = courseLearningService.list(courseLearningWrapper);

        if (CollUtil.isNotEmpty(courseLearningList)) {
            // 更新现有课程学习记录
            LambdaUpdateWrapper<FtbCultivatePositionCourceLearning> updateCourseWrapper = Wrappers.lambdaUpdate();
            updateCourseWrapper.eq(FtbCultivatePositionCourceLearning::getCourceId, req.getCourseId());
            updateCourseWrapper.eq(FtbCultivatePositionCourceLearning::getUserId, userId);
            updateCourseWrapper.eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0);
            updateCourseWrapper.set(FtbCultivatePositionCourceLearning::getState, courseState);
            updateCourseWrapper.set(FtbCultivatePositionCourceLearning::getLastModifyTime, new Date());
//            updateCourseWrapper.setSql("F_LearnTime = F_LearnTime + " + req.getDuration());
            courseLearningService.update(updateCourseWrapper);
        } else {
            // 创建新的课程学习记录
            FtbCultivatePositionCourceLearning courseLearning = new FtbCultivatePositionCourceLearning();
            courseLearning.setCourceId(req.getCourseId());
            courseLearning.setUserId(userId);
//            courseLearning.setLearnTime(req.getDuration());
            courseLearning.setState(courseState);
            courseLearning.setEnabledMark(0);
            courseLearning.setTenantId(tenantId);
            courseLearning.setLastModifyTime(new Date());
            courseLearning.setCreatorTime(new Date());
            courseLearningService.save(courseLearning);
        }
    }

    private String buildStudyParam(V2ChapterStudyVo req, String userId) {
        LastStudyCourseVo lastStudyCourse = new LastStudyCourseVo();
        lastStudyCourse.setCourseId(req.getCourseId());
        lastStudyCourse.setChapterId(req.getChapterId());
        if (req.getBusinessSource() != null) {
            lastStudyCourse.setBusinessSourceCode(req.getBusinessSource().getCode());
            lastStudyCourse.setBusinessSourceId(req.getBusinessSourceId());
        } else {
            lastStudyCourse.setBusinessSourceCode(1);
            lastStudyCourse.setBusinessSourceId(req.getCourseId());
        }
        return JSONUtil.toJsonStr(lastStudyCourse);
    }

    /**
     * 处理随堂测试结果
     *
     * @param req    章节学习参数
     * @param userId 用户ID
     */
    private void handleOnsiteTestResults(V2ChapterStudyVo req, String userId) {
        ftbCultivateCourseSettingService.onSiteTestResultStorageV2(
                req.getFtbChapterTestDTOs(),
                req.getCourseId(),
                req.getChapterId(),
                userId
        );
    }


    /**
     * 课程学习时长记录
     *
     * @param req 章节学习参数
     */
    @Override
    public void durationRecord(V2ChapterStudyVo req) {
        UserInfo user = UserProvider.getUser();
        String userId = user.getUserId();
        // 更新或创建章节学习时长
        recordChapterLearningTime(req, userId);
        //记录课程学习时长
        FtbCultivatePositionCourceLearning ftbCultivatePositionCourceLearning = recordCourseLearningTime(req, userId);
        // 处理随堂测试结果
        handleOnsiteTestResults(req, userId);

        //记录学习记录
        ftbCultivateCourseLearningLogService.save(FtbCultivateCourseLearningLogEntity.builder()
                .courseId(req.getCourseId()).learnTime(req.getDuration()).creatorUserId(userId).creatorTime(new Date())
                .tenantId(user.getTenantId()).enabledMark(0).status(ftbCultivatePositionCourceLearning.getState().equals(1) ? 1 : 0).build()
        );

    }

    /**
     * 记录章节学习时长
     *
     * @param req    章节学习参数
     * @param userId 用户ID
     */
    private FtbCultivatePositionCourceLearning recordCourseLearningTime(V2ChapterStudyVo req, String userId) {
        LambdaQueryWrapper<FtbCultivatePositionCourceLearning> courseLearningWrapper = Wrappers.lambdaQuery();
        courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getCourceId, req.getCourseId());
        courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getUserId, userId);
        courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0);
        List<FtbCultivatePositionCourceLearning> courseLearningList = courseLearningService.list(courseLearningWrapper);

        if (CollUtil.isNotEmpty(courseLearningList)) {
            // 更新现有课程学习记录
            LambdaUpdateWrapper<FtbCultivatePositionCourceLearning> updateCourseWrapper = Wrappers.lambdaUpdate();
            updateCourseWrapper.eq(FtbCultivatePositionCourceLearning::getCourceId, req.getCourseId());
            updateCourseWrapper.eq(FtbCultivatePositionCourceLearning::getUserId, userId);
            updateCourseWrapper.eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0);
            updateCourseWrapper.set(FtbCultivatePositionCourceLearning::getLastModifyTime, new Date());
            updateCourseWrapper.set(courseLearningList.get(0).getState() == 0, FtbCultivatePositionCourceLearning::getState, 2);
            updateCourseWrapper.setSql("F_LearnTime = F_LearnTime + " + req.getDuration());
            courseLearningService.update(updateCourseWrapper);
            return courseLearningList.get(0);
        } else {
            // 创建新的课程学习记录
            FtbCultivatePositionCourceLearning courseLearning = new FtbCultivatePositionCourceLearning();
            courseLearning.setCourceId(req.getCourseId());
            courseLearning.setUserId(userId);
            courseLearning.setLearnTime(req.getDuration());
            courseLearning.setState(2);
            courseLearning.setEnabledMark(0);
            courseLearning.setLastModifyTime(new Date());
            courseLearningService.save(courseLearning);
            return courseLearning;
        }
    }

    /**
     * 记录课程章节学习时长
     *
     * @param userId 用户id
     */
    private void recordChapterLearningTime(V2ChapterStudyVo req, String userId) {
        String params = buildStudyParam(req, userId);
        LambdaQueryWrapper<FtbCultivatePositionCourceChapterLearning> queryChapterWrapper = Wrappers.lambdaQuery();
        queryChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getCourceId, req.getCourseId());
        queryChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getChapterId, req.getChapterId());
        queryChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getUserId, userId);
        queryChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getEnabledMark, 0);
        List<FtbCultivatePositionCourceChapterLearning> existingChapter = chapterLearningService.list(queryChapterWrapper);

        if (CollUtil.isNotEmpty(existingChapter)) {
            // 更新现有章节学习记录
            LambdaUpdateWrapper<FtbCultivatePositionCourceChapterLearning> updateChapterWrapper = Wrappers.lambdaUpdate();
            updateChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getCourceId, req.getCourseId());
            updateChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getChapterId, req.getChapterId());
            updateChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getUserId, userId);
            updateChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getEnabledMark, 0);
            updateChapterWrapper.set(FtbCultivatePositionCourceChapterLearning::getLastStudyParams, params);
            updateChapterWrapper.set(FtbCultivatePositionCourceChapterLearning::getLastModifyTime, new Date());
            if (req.getLastVideoStudyTime() != null) {
                updateChapterWrapper.set(FtbCultivatePositionCourceChapterLearning::getLastVideoStudyTime, req.getLastVideoStudyTime());
            }
            updateChapterWrapper.setSql("F_ChapterTime = F_ChapterTime + " + req.getDuration());
            chapterLearningService.update(new FtbCultivatePositionCourceChapterLearning(), updateChapterWrapper);
        } else {
            // 创建新的章节学习记录
            FtbCultivatePositionCourceChapterLearning chapterLearning = new FtbCultivatePositionCourceChapterLearning();
            chapterLearning.setCourceId(req.getCourseId());
            chapterLearning.setChapterId(req.getChapterId());
            chapterLearning.setUserId(userId);
            chapterLearning.setEnabledMark(0);
            chapterLearning.setState(0);
            chapterLearning.setChapterTime(req.getDuration());
            chapterLearning.setLastModifyTime(new Date());
            chapterLearning.setLastStudyParams(params);
            chapterLearning.setLastVideoStudyTime(req.getLastVideoStudyTime());
            chapterLearningService.save(chapterLearning);
        }
    }

    /**
     * 课程浏览
     *
     * @param courseId 课程id
     */
    @Override
    public void courseBrowsing(String courseId) {
        // 直接执行原子更新操作，避免并发问题和多次数据库交互
        LambdaUpdateWrapper<FtbCultivateCourse> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(FtbCultivateCourse::getId, courseId)
                .setSql("F_Views = IFNULL(F_Views, 0) + 1");
        cultivateCourseMapper.update(null, wrapper);
    }

    /**
     * 通用课程列表
     *
     * @param dto  参数
     * @param page 分页参数
     * @return 课程列表
     */
    @Override
    public Page<AppCommonCourseSimpleVo> commonCourseList(V2MyCultivateCommonCourseForAppReq dto, CultivatePage page) {
        String userId = dto.getUserId();
        UserBoundVO userBoundVO = userApiV2Util.getUserPrimaryBoundOne(userId, null);
        if (userBoundVO == null) {
            throw new RuntimeException("用户信息不存在");
        }
        Page<AppCommonCourseSimpleVo> pageResult = cultivateCourseMapper.queryCommonCourseApp(page.coverCultivatePage(), dto);
        List<AppCommonCourseSimpleVo> records = pageResult.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            List<String> courseIds = records.stream().map(AppCommonCourseSimpleVo::getCourseId).collect(Collectors.toList());
            Map<String, Long> studyNumMap = v2CultivateBatchQueryService.batchQueryCourseLearningCount(courseIds);
            Map<String, FtbCultivatePositionCourceLearning> learningStateMap = v2CultivateBatchQueryService.batchQueryUserCourseLearnStatus(userId, courseIds);
            for (AppCommonCourseSimpleVo record : records) {
                record.setLearnTotalNumber(studyNumMap.getOrDefault(record.getCourseId(), 0L));
                FtbCultivatePositionCourceLearning state = learningStateMap.get(record.getCourseId());
                if (state == null) {
                    record.setLearnState(0); // 未学习
                } else {
                    record.setLearnState(state.getState()); // 0未学习，1已学习，2学习中
                }
                record.setBusinessSource(GENERAL_COURSE);
                record.setBusinessSourceId(record.getCourseId());
            }
        }
        return pageResult;
    }

    @Override
    public LastStudyCourseVo queryLastStudyCourse() {
        LastStudyCourseVo vo = new LastStudyCourseVo();
        String userId = UserProvider.getUser().getUserId();
        LambdaQueryWrapper<FtbCultivatePositionCourceChapterLearning> queryChapterWrapper = Wrappers.lambdaQuery();
        queryChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getUserId, userId);
        queryChapterWrapper.eq(FtbCultivatePositionCourceChapterLearning::getEnabledMark, 0);
        queryChapterWrapper.orderByDesc(FtbCultivatePositionCourceChapterLearning::getLastModifyTime);
        queryChapterWrapper.last("LIMIT 1");
        List<FtbCultivatePositionCourceChapterLearning> chapterLearningList = chapterLearningService.list(queryChapterWrapper);
        if (CollUtil.isEmpty(chapterLearningList)) {
            return vo;
        }
        FtbCultivatePositionCourceChapterLearning chapterLearning = chapterLearningList.get(0);
        if (StringUtils.isEmpty(chapterLearning.getLastStudyParams())) {
            return vo;
        }
        FtbCultivateCourse ftbCultivateCourse = cultivateCourseMapper.selectById(chapterLearning.getCourceId());
        if (ftbCultivateCourse == null || ftbCultivateCourse.getEnableMark().equals(1) || ftbCultivateCourse.getIsGroundIng().equals(0)) {
            return vo;
        }
        if (chapterLearning.getState().equals(0)) {
            LastStudyCourseVo lastStudyCourseVo = JSONUtil.toBean(chapterLearning.getLastStudyParams(), LastStudyCourseVo.class);
            lastStudyCourseVo.setCourseId(chapterLearning.getCourceId());
            lastStudyCourseVo.setChapterId(chapterLearning.getChapterId());
            lastStudyCourseVo.setBusinessSource(PositionBusinessSourceEnum.getByCode(lastStudyCourseVo.getBusinessSourceCode()));
            if (!lastStudyCourseVo.getBusinessSourceCode().equals(1)) {
                lastStudyCourseVo.setBusinessSourceId(lastStudyCourseVo.getBusinessSourceId());
            } else {
                lastStudyCourseVo.setBusinessSourceId(chapterLearning.getCourceId());
            }
            lastStudyCourseVo.setState(2);
            vo = lastStudyCourseVo;
        }
        String courseId = chapterLearning.getCourceId();
        LambdaQueryWrapper<FtbCultivatePositionCourceLearning> courseLearningWrapper = Wrappers.lambdaQuery();
        courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getCourceId, courseId);
        courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getUserId, userId);
        courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0);
        List<FtbCultivatePositionCourceLearning> courseLearningList = courseLearningService.list(courseLearningWrapper);
        if (CollUtil.isEmpty(courseLearningList)) {
            return vo;
        }
        FtbCultivatePositionCourceLearning courseLearning = courseLearningList.get(0);
        vo.setState(courseLearning.getState());
        if (!courseLearning.getState().equals(1)) {
            LastStudyCourseVo lastStudyCourseVo = JSONUtil.toBean(chapterLearning.getLastStudyParams(), LastStudyCourseVo.class);
            lastStudyCourseVo.setCourseId(chapterLearning.getCourceId());
            lastStudyCourseVo.setChapterId(chapterLearning.getChapterId());
            lastStudyCourseVo.setBusinessSource(PositionBusinessSourceEnum.getByCode(lastStudyCourseVo.getBusinessSourceCode()));
            return lastStudyCourseVo;
        }
        return vo;
    }

    @Override
    public CommonCourseCountVo commonCourseCount(V2MyCultivateCommonCourseForAppReq dto) {
        String userId = dto.getUserId();
        UserBoundVO userBoundVO = userApiV2Util.getUserPrimaryBoundOne(userId, null);
        if (userBoundVO == null) {
            throw new RuntimeException("用户信息不存在");
        }
        List<String> courseIds = cultivateCourseMapper.commonCourseCount(dto);
        CommonCourseCountVo vo = new CommonCourseCountVo();
        vo.init();
        if (CollUtil.isNotEmpty(courseIds)) {
            vo.setTotalCourse(courseIds.size());
            Map<String, FtbCultivatePositionCourceLearning> learningStateMap = v2CultivateBatchQueryService.batchQueryUserCourseLearnStatus(userId, courseIds);
            //统计已经完成的学习数量
            for (String courseId : courseIds) {
                FtbCultivatePositionCourceLearning state = learningStateMap.get(courseId);
                if (state != null && state.getState().equals(1)) {
                    vo.setAlreadyLearnedCourse(vo.getAlreadyLearnedCourse() + 1);
                }
            }
        }

        return vo;
    }

}