package jnpf.cultivate.v2.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 com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jnpf.base.UserInfo;
import jnpf.cultivate.mapper.*;
import jnpf.cultivate.service.CultivateCourseMsgService;
import jnpf.cultivate.service.FtbCultivateChapterTestOptionService;
import jnpf.cultivate.service.FtbCultivateChapterTestService;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.cultivate.v2.service.FtbCultivateCourseSettingGlobalService;
import jnpf.cultivate.v2.service.V2CultivateCourseService;
import jnpf.entity.cultivate.CultivateIdentifyTable;
import jnpf.model.cultivate.dto.course.testoption.FtbCultivateChapterTestOptionDTO;
import jnpf.model.cultivate.po.FtbCultivateCourseSettingGlobal;
import jnpf.model.cultivate.po.course.*;
import jnpf.model.cultivate.po.course.app.CultivateCourseMsg;
import jnpf.model.cultivate.po.label.FtbCultivateLabel;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceChapterLearning;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceLearning;
import jnpf.model.cultivate.v2.course.vo.AiHelperCourseStatisticsVo;
import jnpf.model.cultivate.v2.course.vo.UserLearningStatusVo;
import jnpf.model.cultivate.v2.course.vo.app.AppCultivateCourseExamVo;
import jnpf.model.cultivate.v2.course.vo.app.AppCultivateCourseIdentityVo;
import jnpf.model.cultivate.v2.course.vo.app.V2CultivateChapterTestAddDTO;
import jnpf.model.cultivate.v2.course.web.req.V2CultivateCourseChapterReq;
import jnpf.model.cultivate.v2.course.web.req.V2CultivateCourseListReq;
import jnpf.model.cultivate.v2.course.web.req.V2CultivateCourseReq;
import jnpf.model.cultivate.v2.course.web.req.V2CultivateCourseSelectReq;
import jnpf.model.cultivate.v2.course.web.vo.V2CultivateCourseChapterVo;
import jnpf.model.cultivate.v2.course.web.vo.V2CultivateCourseDetailsVo;
import jnpf.model.cultivate.v2.course.web.vo.V2CultivateCoursePageVo;
import jnpf.model.cultivate.v2.course.web.vo.V2CultivateCourseSelectVo;
import jnpf.model.enums.SelfrowingEnum;
import jnpf.util.SelfGrowthUtil;
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 org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class V2CultivateCourseServiceImpl implements V2CultivateCourseService {

    @Autowired
    private FtbCultivatePositionCourceLearningMapper ftbCultivatePositionCourceLearningMapper;

    @Autowired
    private FtbCultivatePositionCourceChapterLearningMapper ftbCultivatePositionCourceChapterLearningMapper;

    @Autowired
    private FtbCultivateChapterTestResultMapper ftbCultivateChapterTestResultMapper;

    @Autowired
    private FtbCultivateCourseMapper ftbCultivateCourseMapper;

    @Autowired
    private FtbCultivateCourseChapterMapper ftbCultivateCourseChapterMapper;


    @Autowired
    private FtbCultivateLabelMapper ftbCultivateLabelMapper;

    @Autowired
    private CultivateIdentifyTableMapper cultivateIdentifyTableMapper;

    @Autowired
    private FtbCultivateChapterTestOptionService ftbCultivateChapterTestOptionService;

    @Autowired
    private CultivateCourseMsgService cultivateCourseMsgService;

    @Autowired
    private UserApiV2Util userApiV2Util;

    @Resource
    private ThreadPoolExecutor cultivateThreadPool;

    @Autowired
    private FtbCultivateChapterTestService ftbCultivateChapterTestService;

    @Autowired
    private FtbCultivateCourseSettingGlobalService ftbCultivateCourseSettingGlobalService;

    @Autowired
    private FtbCultivateExamUserMapper ftbCultivateExamUserMapper;

    @Autowired
    private CultivateIdentifyApplyMapper cultivateIdentifyApplyMapper;

    /**
     * 课程列表分页查询
     *
     * @param req 课程列表分页查询参数
     * @return 分页数据
     */
    @Override
    public Page<V2CultivateCoursePageVo> webList(V2CultivateCourseListReq req) {
        return ftbCultivateCourseMapper.webList(Page.of(req.getCurrentPage(), req.getPageSize()), req);
    }

    /**
     * 添加课程
     *
     * @param req 添加课程参数
     * @return 课程ID
     */
    @Override
    @Transactional
    public String add(V2CultivateCourseReq req) {
        // 参数验证
        req.validateCourseParams();
        // 检查课程名称是否重复
        LambdaQueryWrapper<FtbCultivateCourse> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbCultivateCourse::getName, req.getName())
                .eq(FtbCultivateCourse::getEnableMark, 0); // 只检查有效的课程
        long count = ftbCultivateCourseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("课程名称不能重复");
        }

        // 创建课程实体
        FtbCultivateCourse course = new FtbCultivateCourse();
        buildCultivateCourse(req, course);
        course.setChapterNumber(calChapterNum(req.getChapterReqList())); // 初始章节数为0
        course.setEnableMark(0); // 设置为有效
        course.setHighLights(req.getHighLights());
        course.setCourseId(SelfGrowthUtil.provideACustomIDBasedOnTheModule(SelfrowingEnum.COURSE));
        course.setLastModifyTime(new Date());
        course.setLastModifyUserId(UserProvider.getLoginUserId());
        // 插入课程
        ftbCultivateCourseMapper.insert(course);
        String courseId = course.getId();

        // 如果有章节信息，则处理章节及随堂测试
        updateAndAddCourseChapters(req.getChapterReqList(), courseId, null, "");
        return courseId;
    }

    private void buildCultivateCourse(V2CultivateCourseReq req, FtbCultivateCourse course) {
        course.setName(req.getName());
        course.setLabel(req.getLabel());
        course.setTypeId(req.getTypeId());
        course.setCoverId(req.getCoverId());
        course.setCoverUrl(req.getCoverUrl());
        course.setNeedExamAndIdentify(req.getNeedExamAndIdentify());
        course.setExamId(req.getExamId());
        course.setIdentifyId(req.getIdentifyId());
    }

    /**
     * 计算章节数
     *
     * @param chapterReqList 章节请求列表
     * @return 章节数量
     */
    private Integer calChapterNum(List<V2CultivateCourseChapterReq> chapterReqList) {
        if (CollUtil.isEmpty(chapterReqList)) {
            return 0;
        }

        return chapterReqList.stream()
                .mapToInt(chapter -> 1 + calChapterNum(chapter.getChildChapter()))
                .sum();
    }


    /**
     * 处理章节随堂测试
     */
    private void handleChapterTests(List<V2CultivateChapterTestAddDTO> testList, String courseId, String chapterId) {

        LambdaUpdateWrapper<FtbCultivateChapterTest> testUpdateWrapper = Wrappers.lambdaUpdate();
        testUpdateWrapper.in(FtbCultivateChapterTest::getCourseChapterId, chapterId);
        testUpdateWrapper.set(FtbCultivateChapterTest::getEnableMark, 1); // 逻辑删除
        ftbCultivateChapterTestService.update(new FtbCultivateChapterTest(), testUpdateWrapper);

        if (CollUtil.isEmpty(testList)) {
            return;
        }
        for (V2CultivateChapterTestAddDTO test : testList) {
            // 创建随堂测试实体
            FtbCultivateChapterTest chapterTest = new FtbCultivateChapterTest();
            chapterTest.setCourseId(courseId);
            chapterTest.setCourseChapterId(chapterId);
            chapterTest.setForcedStudy(test.getForcedStudy());
            chapterTest.setTopicName(test.getTopicName());
            chapterTest.setAnswerAnalysis(test.getAnswerAnalysis());
            chapterTest.setEnableMark(0); // 设置为有效

            // 插入随堂测试
            ftbCultivateChapterTestService.save(chapterTest);
            String testId = chapterTest.getId();

            // 处理测试选项
            if (CollUtil.isNotEmpty(test.getFetchChapterTestOptions())) {
                List<FtbCultivateChapterTestOption> optionList = new ArrayList<>();
                for (FtbCultivateChapterTestOptionDTO optionDTO : test.getFetchChapterTestOptions()) {
                    optionList.add(optionDTO.convert(testId));
                }

                // 批量插入测试选项
                if (CollUtil.isNotEmpty(optionList)) {
                    ftbCultivateChapterTestOptionService.saveBatch(optionList);
                }
            }
        }
    }


    /**
     * 更新课程
     *
     * @param req 更新课程参数
     */
    @Override
    @Transactional
    public void update(V2CultivateCourseReq req) {
        // 参数验证
        req.validateCourseParams();

        // 获取原课程信息
        FtbCultivateCourse course = ftbCultivateCourseMapper.selectById(req.getId());
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }

        // 检查课程名称是否与其他课程重复
        LambdaQueryWrapper<FtbCultivateCourse> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbCultivateCourse::getName, req.getName())
                .ne(FtbCultivateCourse::getId, req.getId())
                .eq(FtbCultivateCourse::getEnableMark, 0); // 只检查有效的课程
        long count = ftbCultivateCourseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("课程名称不能重复");
        }

        // 更新课程基本信息
        buildCultivateCourse(req, course);
        course.setHighLights(req.getHighLights());

        dealDeleteCourseChapter(req.getChapterReqList(), req.getId());
        // 处理章节更新 - 智能更新章节，保留章节ID

        updateAndAddCourseChapters(req.getChapterReqList(), req.getId(), null, "");

        // 更新课程章节数
        course.setChapterNumber(calChapterNum(req.getChapterReqList()));
        course.setLastModifyTime(new Date());
        course.setLastModifyUserId(UserProvider.getLoginUserId());
        ftbCultivateCourseMapper.updateById(course);
    }

    /**
     * 处理章节更新 - 智能更新章节，保留章节ID
     */
    private void updateAndAddCourseChapters(List<V2CultivateCourseChapterReq> chapterList, String courseId, String parentId, String path) {
        for (V2CultivateCourseChapterReq chapterReq : chapterList) {
            // 创建章节实体
            FtbCultivateCourseChapter chapter = chapterReq.convertFtbCultivateCourseChapter(chapterReq);
            chapter.setCourseId(courseId);
            chapter.setEnableMark(0); // 设置为有效

            // 计算路径 - 先保存章节以获取ID
            if (StringUtils.isEmpty(parentId)) {
                chapter.setParentId("0");
                chapter.setPath("");
            } else {
                chapter.setParentId(parentId);
                chapter.setPath(path);
            }
            if (StringUtils.isEmpty(chapterReq.getId())) {
                ftbCultivateCourseChapterMapper.insert(chapter);
            } else {
                chapter.setId(chapterReq.getId());
                ftbCultivateCourseChapterMapper.updateById(chapter);
            }

            String chapterId = chapter.getId();
            String newPath = "";
            if (StringUtils.isEmpty(parentId)) {
                newPath = chapterId;
            } else {
                newPath = parentId + "-" + chapterId;
            }
            // 处理随堂测试

            handleChapterTests(chapterReq.getCultivateChapterTest(), courseId, chapterId);


            // 递归处理子章节
            if (CollUtil.isNotEmpty(chapterReq.getChildChapter())) {
                updateAndAddCourseChapters(chapterReq.getChildChapter(), courseId, chapterId, newPath);
            }
        }
    }

    /**
     * 递归删除章节（包括子章节和随堂测试）
     */
    private void dealDeleteCourseChapter(List<V2CultivateCourseChapterReq> chapterReqList, String courseId) {

        // 获取当前父级下的现有章节
        LambdaQueryWrapper<FtbCultivateCourseChapter> existingQuery = Wrappers.lambdaQuery();
        existingQuery.eq(FtbCultivateCourseChapter::getCourseId, courseId);
        existingQuery.eq(FtbCultivateCourseChapter::getEnableMark, 0);
        List<FtbCultivateCourseChapter> existingChapters = ftbCultivateCourseChapterMapper.selectList(existingQuery);
        if (CollUtil.isEmpty(existingChapters)) {
            return;
        }
        List<String> existingChapterIds = existingChapters.stream().map(FtbCultivateCourseChapter::getId).collect(Collectors.toList());
        List<String> chapterListIds = new ArrayList<>();
        getAllReqChapterIds(chapterReqList, chapterListIds);
        List<String> deleteChapterIds = new ArrayList<>();
        for (String existingChapterId : existingChapterIds) {
            if (!chapterListIds.contains(existingChapterId)) {
                deleteChapterIds.add(existingChapterId);
            }
        }
        if (CollUtil.isEmpty(deleteChapterIds)) {
            return;
        }


        // 删除随堂测试
        LambdaUpdateWrapper<FtbCultivateChapterTest> testUpdateWrapper = Wrappers.lambdaUpdate();
        testUpdateWrapper.in(FtbCultivateChapterTest::getCourseChapterId, deleteChapterIds);
        testUpdateWrapper.set(FtbCultivateChapterTest::getEnableMark, 1); // 逻辑删除
        ftbCultivateChapterTestService.update(new FtbCultivateChapterTest(), testUpdateWrapper);


        // 删除当前章节
        LambdaUpdateWrapper<FtbCultivateCourseChapter> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(FtbCultivateCourseChapter::getId, deleteChapterIds);
        updateWrapper.set(FtbCultivateCourseChapter::getEnableMark, 1); // 逻辑删除
        ftbCultivateCourseChapterMapper.update(new FtbCultivateCourseChapter(), updateWrapper);
    }

    private void getAllReqChapterIds(List<V2CultivateCourseChapterReq> chapterReqList, List<String> chapterListIds) {

        for (V2CultivateCourseChapterReq chapterReq : chapterReqList) {
            if (StringUtils.isNotEmpty(chapterReq.getId())) {
                chapterListIds.add(chapterReq.getId());
            }
            if (CollUtil.isNotEmpty(chapterReq.getChildChapter())) {
                List<String> chapterListIdsChild1 = new ArrayList<>();
                getAllReqChapterIds(chapterReq.getChildChapter(), chapterListIdsChild1);
                chapterListIds.addAll(chapterListIdsChild1);
            }
        }
    }


    /**
     * 删除课程
     *
     * @param courseId 课程ID
     */
    @Override
    public void delete(String courseId) {

        LambdaUpdateWrapper<FtbCultivateCourse> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(FtbCultivateCourse::getId, courseId);
        updateWrapper.set(FtbCultivateCourse::getEnableMark, 1);
        ftbCultivateCourseMapper.update(new FtbCultivateCourse(), updateWrapper);

        // 删除当前章节
        LambdaUpdateWrapper<FtbCultivateCourseChapter> updateChapterWrapper = Wrappers.lambdaUpdate();
        updateChapterWrapper.eq(FtbCultivateCourseChapter::getCourseId, courseId);
        updateChapterWrapper.set(FtbCultivateCourseChapter::getEnableMark, 1); // 逻辑删除
        ftbCultivateCourseChapterMapper.update(new FtbCultivateCourseChapter(), updateChapterWrapper);

        // 随堂测试
        LambdaUpdateWrapper<FtbCultivateChapterTest> chapterTestLambdaUpdateWrapper = Wrappers.lambdaUpdate();
        chapterTestLambdaUpdateWrapper.eq(FtbCultivateChapterTest::getCourseId, courseId);
        chapterTestLambdaUpdateWrapper.set(FtbCultivateChapterTest::getEnableMark, 1);
        ftbCultivateChapterTestService.update(new FtbCultivateChapterTest(), chapterTestLambdaUpdateWrapper);

    }

    /**
     * 查询课程详情
     *
     * @param courseId 课程ID
     * @return {@link V2CultivateCourseDetailsVo}
     */
    @Override
    public V2CultivateCourseDetailsVo detail(String courseId) {
        // 1. 查询课程基本信息
        FtbCultivateCourse course = ftbCultivateCourseMapper.selectById(courseId);
        if (course == null || course.getEnableMark() != 0) {
            throw new RuntimeException("课程不存在或已被删除");
        }

        // 2. 构建返回VO
        V2CultivateCourseDetailsVo courseDetailsVo = new V2CultivateCourseDetailsVo();
        courseDetailsVo.convert(course);

        // 3. 查询课程类型名称
        if (StringUtils.isNotEmpty(course.getTypeId())) {
            FtbCultivateLabel courseType = ftbCultivateLabelMapper.selectById(course.getTypeId());
            if (courseType != null && courseType.getEnabledMark() == 0) {
                courseDetailsVo.setTypeName(courseType.getName());
            }
        }

        // 4. 查询课程章节信息
        List<FtbCultivateCourseChapter> chapters = getCourseChapters(courseId);

        // 5. 构建章节树形结构
        List<V2CultivateCourseChapterVo> chapterTree = buildChapterTree(chapters);
        courseDetailsVo.setChapterVoList(chapterTree);

        // 6. 查询考试信息
        if (course.getNeedExamAndIdentify() != null && course.getNeedExamAndIdentify().equals(1) && StringUtils.isNotEmpty(course.getExamId())) {
            courseDetailsVo.setExam(getExamInfo(course.getExamId()));
        }

        // 7. 查询鉴定信息
        if (course.getNeedExamAndIdentify() != null && course.getNeedExamAndIdentify().equals(1) && StringUtils.isNotEmpty(course.getIdentifyId())) {
            courseDetailsVo.setIdentity(getIdentityInfo(course.getIdentifyId()));
        }

        return courseDetailsVo;
    }

    /**
     * 查询课程章节列表
     */
    private List<FtbCultivateCourseChapter> getCourseChapters(String courseId) {
        LambdaQueryWrapper<FtbCultivateCourseChapter> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbCultivateCourseChapter::getCourseId, courseId);
        queryWrapper.eq(FtbCultivateCourseChapter::getEnableMark, 0);
        queryWrapper.orderByAsc(FtbCultivateCourseChapter::getSortCode);
        return ftbCultivateCourseChapterMapper.selectList(queryWrapper);
    }

    /**
     * 构建章节树形结构
     */
    private List<V2CultivateCourseChapterVo> buildChapterTree(List<FtbCultivateCourseChapter> chapters) {
        if (CollUtil.isEmpty(chapters)) {
            return new ArrayList<>();
        }

        // 转换为VO对象
        List<V2CultivateCourseChapterVo> chapterVos = chapters.stream().map(this::convertToChapterVo).collect(Collectors.toList());

        // 构建父子关系映射
        Map<String, List<V2CultivateCourseChapterVo>> childrenMap = new HashMap<>();
        for (V2CultivateCourseChapterVo chapterVo : chapterVos) {
            String parentId = "0".equals(chapterVo.getParentId()) ? "0" : chapterVo.getParentId();
            childrenMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(chapterVo);
        }

        // 设置子章节
        for (V2CultivateCourseChapterVo chapterVo : chapterVos) {
            List<V2CultivateCourseChapterVo> children = childrenMap.get(chapterVo.getId());
            if (CollUtil.isNotEmpty(children)) {
                chapterVo.setChildChapter(children);
            }
        }

        // 返回顶级章节
        return childrenMap.getOrDefault("0", new ArrayList<>());
    }

    /**
     * 转换章节实体为VO
     */
    private V2CultivateCourseChapterVo convertToChapterVo(FtbCultivateCourseChapter chapter) {
        V2CultivateCourseChapterVo chapterVo = new V2CultivateCourseChapterVo();
        chapterVo.setId(chapter.getId());
        chapterVo.setCourseId(chapter.getCourseId());
        chapterVo.setName(chapter.getName());
        chapterVo.setSortCode(chapter.getSortCode());
        chapterVo.setAnnex(chapter.getAnnex());
        chapterVo.setAnnexName(chapter.getAnnexName());
        chapterVo.setDetailDesc(chapter.getDetailDesc());
        chapterVo.setDuration(chapter.getDuration());
        chapterVo.setWhetherTesting(chapter.getWhetherTesting());
        chapterVo.setForcedStudy(chapter.getForcedStudy());
        chapterVo.setChapterType(chapter.getChapterType());
        chapterVo.setParentId(chapter.getParentId());
        chapterVo.setSource(chapter.getSource());
        chapterVo.setPath(chapter.getPath());
        chapterVo.setVideoActionType(chapter.getVideoActionType());
        chapterVo.setSize(chapter.getSize());
        chapterVo.setLibraryId(chapter.getLibraryId());

        // 查询随堂测试
        if (chapter.getWhetherTesting() != null && chapter.getWhetherTesting() == 0) {
            List<V2CultivateChapterTestAddDTO> tests = getChapterTests(chapter.getId());
            chapterVo.setCultivateChapterTest(tests);
        }

        return chapterVo;
    }

    /**
     * 查询章节随堂测试
     */
    private List<V2CultivateChapterTestAddDTO> getChapterTests(String chapterId) {
        LambdaQueryWrapper<FtbCultivateChapterTest> testQuery = Wrappers.lambdaQuery();
        testQuery.eq(FtbCultivateChapterTest::getCourseChapterId, chapterId);
        testQuery.eq(FtbCultivateChapterTest::getEnableMark, 0);
        List<FtbCultivateChapterTest> tests = ftbCultivateChapterTestService.list(testQuery);

        if (CollUtil.isEmpty(tests)) {
            return new ArrayList<>();
        }

        return tests.stream().map(test -> {
            V2CultivateChapterTestAddDTO testDto = new V2CultivateChapterTestAddDTO();
            testDto.setTopicName(test.getTopicName());
            testDto.setAnswerAnalysis(test.getAnswerAnalysis());
            testDto.setForcedStudy(test.getForcedStudy());

            // 查询测试选项
            List<FtbCultivateChapterTestOption> options = getTestOptions(test.getId());
            List<FtbCultivateChapterTestOptionDTO> optionDtos = options.stream().map(option -> {
                FtbCultivateChapterTestOptionDTO optionDto = new FtbCultivateChapterTestOptionDTO();
                optionDto.setIsRightOption(option.getIsRightOption());
                optionDto.setContent(option.getContent());
                optionDto.setSortCode(option.getSortCode());
                return optionDto;
            }).collect(Collectors.toList());
            testDto.setFetchChapterTestOptions(optionDtos);

            return testDto;
        }).collect(Collectors.toList());
    }

    /**
     * 查询测试选项
     */
    private List<FtbCultivateChapterTestOption> getTestOptions(String testId) {
        LambdaQueryWrapper<FtbCultivateChapterTestOption> optionQuery = Wrappers.lambdaQuery();
        optionQuery.eq(FtbCultivateChapterTestOption::getChapterTestId, testId);
        optionQuery.eq(FtbCultivateChapterTestOption::getEnableMark, 0);
        optionQuery.orderByAsc(FtbCultivateChapterTestOption::getSortCode);
        return ftbCultivateChapterTestOptionService.list(optionQuery);
    }

    /**
     * 查询考试信息
     */
    private AppCultivateCourseExamVo getExamInfo(String examId) {
        // 这里需要调用考试服务查询考试信息
        // 由于没有具体的考试服务方法，暂时返回基础信息
        AppCultivateCourseExamVo examVo = new AppCultivateCourseExamVo();
        examVo.setExamId(examId);
        // 可以通过FtbCultivateExamMapper查询考试名称等详细信息
        String examName = ftbCultivateCourseMapper.queryExamNameByExamId(examId);
        examVo.setExamName(examName);
        return examVo;
    }

    /**
     * 查询鉴定信息
     */
    private AppCultivateCourseIdentityVo getIdentityInfo(String identifyId) {
        // 这里需要调用鉴定服务查询鉴定信息
        // 由于没有具体的鉴定服务方法，暂时返回基础信息
        AppCultivateCourseIdentityVo identityVo = new AppCultivateCourseIdentityVo();
        identityVo.setIdentityId(identifyId);
        CultivateIdentifyTable table = cultivateIdentifyTableMapper.selectById(identifyId);
        if (table != null) {
            identityVo.setIdentityName(table.getName());
        }
        // 鉴定名称可以通过其他方式查询
        return identityVo;
    }

    /**
     * 添加岗位学习OR任务时，课程列表选择
     *
     * @param req
     * @return {@link Page}
     */
    @Override
    public Page<V2CultivateCourseSelectVo> learnSelectCourseList(V2CultivateCourseSelectReq req) {
        Page<V2CultivateCourseSelectVo> page = Page.of(req.getCurrentPage(), req.getPageSize());
        return ftbCultivateCourseMapper.jobLearningCourseList(page, req);

    }


    /**
     * 清空课程学习记录
     *
     * @param courseId 课程ID
     */
    @Override
    public void clearCourseLog(String courseId) {
        UserInfo user = UserProvider.getUser();
        String tenantId = user.getTenantId();
        CompletableFuture.runAsync(() -> {
            userApiV2Util.checkOutTenant(tenantId);
            FtbCultivateCourseSettingGlobal info = ftbCultivateCourseSettingGlobalService.getInfo();
            if (info == null || info.getCourseUpdate().equals(0)) {
                ftbCultivatePositionCourceChapterLearningMapper.update(null,
                        new LambdaUpdateWrapper<FtbCultivatePositionCourceChapterLearning>()
                                .eq(FtbCultivatePositionCourceChapterLearning::getCourceId, courseId)
                                .eq(FtbCultivatePositionCourceChapterLearning::getEnabledMark, 0)
                                .set(FtbCultivatePositionCourceChapterLearning::getLastVideoStudyTime, 0));
                return;
            }
            FtbCultivateCourse ftbCultivateCourse = ftbCultivateCourseMapper.selectById(courseId);
            if (ftbCultivateCourse == null) {
                return;
            }
            LambdaQueryWrapper<FtbCultivatePositionCourceLearning> queryCourseLearnWrapper = Wrappers.lambdaQuery();
            queryCourseLearnWrapper.eq(FtbCultivatePositionCourceLearning::getCourceId, courseId)
                    .ne(FtbCultivatePositionCourceLearning::getState, 0)
                    .eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0);
            List<FtbCultivatePositionCourceLearning> allUserStudyList = ftbCultivatePositionCourceLearningMapper.selectList(queryCourseLearnWrapper);

            ftbCultivatePositionCourceLearningMapper.update(null,
                    new LambdaUpdateWrapper<FtbCultivatePositionCourceLearning>()
                            .eq(FtbCultivatePositionCourceLearning::getCourceId, courseId)
                            .eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0)
                            .set(FtbCultivatePositionCourceLearning::getState, 0));

            ftbCultivatePositionCourceChapterLearningMapper.update(null,
                    new LambdaUpdateWrapper<FtbCultivatePositionCourceChapterLearning>()
                            .eq(FtbCultivatePositionCourceChapterLearning::getCourceId, courseId)
                            .eq(FtbCultivatePositionCourceChapterLearning::getEnabledMark, 0)
                            .set(FtbCultivatePositionCourceChapterLearning::getLastVideoStudyTime, 0)
                            .set(FtbCultivatePositionCourceChapterLearning::getState, 0));
            ftbCultivateChapterTestResultMapper.update(null,
                    new LambdaUpdateWrapper<FtbCultivateChapterTestResult>()
                            .eq(FtbCultivateChapterTestResult::getCourseId, courseId)
                            .set(FtbCultivateChapterTestResult::getEnableMark, 1));
            if (CollUtil.isNotEmpty(allUserStudyList)) {
                List<CultivateCourseMsg> cultivateCourseMsgLists = new ArrayList<>();
                for (FtbCultivatePositionCourceLearning item : allUserStudyList) {
                    CultivateCourseMsg cultivateCourseMsg = new CultivateCourseMsg();
                    cultivateCourseMsg.setDesc("课程：" + ftbCultivateCourse.getName() + "章节发生变更，请根据要求重新学习");
                    cultivateCourseMsg.setCourseId(ftbCultivateCourse.getId());
                    cultivateCourseMsg.setState(0);
                    cultivateCourseMsg.setUserId(item.getUserId());
                    cultivateCourseMsg.setStatus(0);
                    cultivateCourseMsgLists.add(cultivateCourseMsg);
                }
                cultivateCourseMsgService.saveBatch(cultivateCourseMsgLists);
            }
        }, cultivateThreadPool);
    }

    @Override
    public AiHelperCourseStatisticsVo getCourseStatistics(String courseId) {
        if (StringUtils.isEmpty(courseId)) {
            throw new RuntimeException("课程ID不能为空");
        }
        AiHelperCourseStatisticsVo statistics = ftbCultivateCourseMapper.getCourseStatistics(courseId);
        if (statistics == null) {
            statistics = new AiHelperCourseStatisticsVo();
            statistics.setCompletedCount(0);
            statistics.setLearningCount(0);
        }
        return statistics;
    }

    /**
     * 查询指定用户的学习情况
     *
     * @param userId 用户ID
     * @return 用户学习情况（包含已完成的课程、考试、鉴定列表，已去重）
     */
    @Override
    public UserLearningStatusVo getUserLearningStatus(String userId) {
        if (StringUtils.isEmpty(userId)) {
            throw new RuntimeException("用户ID不能为空");
        }

        UserLearningStatusVo result = new UserLearningStatusVo();
        result.setUserId(userId);

        // 1. 查询已完成的课程（使用关联查询，一次性获取课程信息）
        List<UserLearningStatusVo.CourseInfo> completedCourses = ftbCultivatePositionCourceLearningMapper.queryCompletedCoursesWithInfo(userId);
        result.setCompletedCourses(completedCourses);

        // 2. 查询已完成的考试（使用关联查询，一次性获取考试信息，并按完成时间倒序）
        List<UserLearningStatusVo.ExamInfo> completedExams = ftbCultivateExamUserMapper.queryCompletedExamsWithInfo(userId);
        result.setCompletedExams(completedExams);

        // 3. 查询已完成的鉴定（使用关联查询，一次性获取鉴定信息，并按鉴定时间倒序）
        List<UserLearningStatusVo.IdentityInfo> completedIdentities = cultivateIdentifyApplyMapper.queryCompletedIdentitiesWithInfo(userId);
        result.setCompletedIdentities(completedIdentities);

        return result;
    }
}