package jnpf.cultivate.v2.util;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.cultivate.mapper.FtbCultivatePositionCourceLearningMapper;
import jnpf.cultivate.service.FtbCultivateLearnTaskAssignmentService;
import jnpf.cultivate.service.FtbCultivateLearnTaskCourseService;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.cultivate.v2.service.V2CultivatePostStudyService;
import jnpf.cultivate.v2.service.V2CultivateTaskStudyService;
import jnpf.enums.cultivate.v2.mq.CultivateTypeEnum;
import jnpf.model.cultivate.po.learn.FtbCultivateLearnTaskAssignment;
import jnpf.model.cultivate.po.learn.FtbCultivateLearnTaskCourse;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceLearning;
import jnpf.model.cultivate.v2.course.vo.app.V2CourseAppDto;
import jnpf.model.cultivate.v2.mq.CultivateMqDTO;
import jnpf.util.UserProvider;
import jnpf.util.context.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

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

/**
 * 培养模块批量查询工具类
 * 提供通用的批量查询方法，适用于任务和岗位学习等多个场景
 */
@Component
public class CultivateCourseStudyUtil {

    @Autowired
    @Lazy
    private FtbCultivatePositionCourceLearningMapper ftbCultivatePositionCourceLearningMapper;

    @Autowired
    @Lazy
    private FtbCultivateLearnTaskAssignmentService ftbCultivateLearnTaskAssignmentService;

    @Autowired
    @Lazy
    private FtbCultivateLearnTaskCourseService ftbCultivateLearnTaskCourseService;

    @Autowired
    @Lazy
    private V2CultivatePostStudyService v2CultivatePostStudyService;

    @Autowired
    @Lazy
    private V2CultivateTaskStudyService v2CultivateTaskStudyService;

    @Resource
    private ThreadPoolExecutor cultivateThreadPool;

    @Autowired
    private UserApiV2Util userApiV2Util;


    /**
     * 初始化课程学习记录
     *
     * @param userId   用户id
     * @param courseId 课程id
     */
    public void initCourseStudyRecord(String userId, String courseId, String tenantId) {
        CompletableFuture.runAsync(ThreadContext.wrap(() -> {
            userApiV2Util.checkOutTenant(tenantId);
            LambdaQueryWrapper<FtbCultivatePositionCourceLearning> courseLearningWrapper = Wrappers.lambdaQuery();
            courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getCourceId, courseId);
            courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getUserId, userId);
            courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0);
            List<FtbCultivatePositionCourceLearning> courseLearningList = ftbCultivatePositionCourceLearningMapper.selectList(courseLearningWrapper);
            if (CollUtil.isNotEmpty(courseLearningList)) {
                return;
            }
            // 创建新的课程学习记录
            FtbCultivatePositionCourceLearning courseLearning = new FtbCultivatePositionCourceLearning();
            courseLearning.setCourceId(courseId);
            courseLearning.setUserId(userId);
            courseLearning.setLearnTime(0);
            courseLearning.setState(0);
            courseLearning.setEnabledMark(0);
            ftbCultivatePositionCourceLearningMapper.insert(courseLearning);
        }), cultivateThreadPool);

    }

    /**
     * 批量初始化课程学习记录
     *
     * @param userIds   用户id
     * @param courseIds 课程id
     */
    public void batchInitCourseStudyRecord(List<String> userIds, List<String> courseIds, String tenantId) {


        CompletableFuture.runAsync(ThreadContext.wrap(() -> {
            userApiV2Util.checkOutTenant(tenantId);
            for (String userId : userIds) {
                LambdaQueryWrapper<FtbCultivatePositionCourceLearning> courseLearningWrapper = Wrappers.lambdaQuery();
                courseLearningWrapper.select(FtbCultivatePositionCourceLearning::getCourceId);
                courseLearningWrapper.in(FtbCultivatePositionCourceLearning::getCourceId, courseIds);
                courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getUserId, userId);
                courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0);
                List<FtbCultivatePositionCourceLearning> courseLearningList = ftbCultivatePositionCourceLearningMapper.selectList(courseLearningWrapper);
                List<String> existCourseIds = new ArrayList<>();
                if (CollUtil.isNotEmpty(courseLearningList)) {
                    existCourseIds = courseLearningList.stream().map(FtbCultivatePositionCourceLearning::getCourceId).collect(Collectors.toList());
                }
                for (String courseId : courseIds) {
                    if (existCourseIds.contains(courseId)) {
                        continue;
                    }
                    // 创建新的课程学习记录
                    FtbCultivatePositionCourceLearning courseLearning = new FtbCultivatePositionCourceLearning();
                    courseLearning.setCourceId(courseId);
                    courseLearning.setUserId(userId);
                    courseLearning.setLearnTime(0);
                    courseLearning.setState(0);
                    courseLearning.setEnabledMark(0);
                    ftbCultivatePositionCourceLearningMapper.insert(courseLearning);
                }
            }

        }), cultivateThreadPool);
    }

    /**
     * 真实初始化课程学习记录
     *
     * @param userIds   用户id
     * @param courseIds 课程id
     */
    public void realInitCourseStudyRecord(List<String> userIds, List<String> courseIds) {
        for (String userId : userIds) {
            LambdaQueryWrapper<FtbCultivatePositionCourceLearning> courseLearningWrapper = Wrappers.lambdaQuery();
            courseLearningWrapper.in(FtbCultivatePositionCourceLearning::getCourceId, courseIds);
            courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getUserId, userId);
            courseLearningWrapper.eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0);
            List<FtbCultivatePositionCourceLearning> courseLearningList = ftbCultivatePositionCourceLearningMapper.selectList(courseLearningWrapper);
            List<String> existCourseIds = new ArrayList<>();
            if (CollUtil.isNotEmpty(courseLearningList)) {
                existCourseIds = courseLearningList.stream().map(FtbCultivatePositionCourceLearning::getCourceId).collect(Collectors.toList());
            }
            for (String courseId : courseIds) {
                if (existCourseIds.contains(courseId)) {
                    continue;
                }
                // 创建新的课程学习记录
                FtbCultivatePositionCourceLearning courseLearning = new FtbCultivatePositionCourceLearning();
                courseLearning.setCourceId(courseId);
                courseLearning.setUserId(userId);
                courseLearning.setLearnTime(0);
                courseLearning.setState(0);
                courseLearning.setEnabledMark(0);
                ftbCultivatePositionCourceLearningMapper.insert(courseLearning);
            }
        }
    }

    /**
     * 添加任务课程学习记录
     *
     * @param taskIds 任务id
     */
    public void addTaskCourseStudyRecord(List<String> taskIds, String tenantId) {

        CompletableFuture.runAsync(ThreadContext.wrap(() -> {
            userApiV2Util.checkOutTenant(tenantId);
            for (String taskId : taskIds) {

                LambdaQueryWrapper<FtbCultivateLearnTaskAssignment> assignmentWrapper = Wrappers.lambdaQuery();
                assignmentWrapper.select(
                        FtbCultivateLearnTaskAssignment::getId,
                        FtbCultivateLearnTaskAssignment::getTaskId,
                        FtbCultivateLearnTaskAssignment::getUserId
                );
                assignmentWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, taskId);
                assignmentWrapper.eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0);
                List<FtbCultivateLearnTaskAssignment> taskAssignment = ftbCultivateLearnTaskAssignmentService.list(assignmentWrapper);
                if (CollUtil.isEmpty(taskAssignment)) {
                    continue;
                }

                List<String> userIds = taskAssignment.stream().map(FtbCultivateLearnTaskAssignment::getUserId).collect(Collectors.toList());
                LambdaQueryWrapper<FtbCultivateLearnTaskCourse> courseWrapper = Wrappers.lambdaQuery();
                courseWrapper.select(
                        FtbCultivateLearnTaskCourse::getId,
                        FtbCultivateLearnTaskCourse::getTaskId,
                        FtbCultivateLearnTaskCourse::getCourseId
                );
                courseWrapper.eq(FtbCultivateLearnTaskCourse::getTaskId, taskId);
                courseWrapper.eq(FtbCultivateLearnTaskCourse::getEnableMark, 0);
                List<FtbCultivateLearnTaskCourse> courseList = ftbCultivateLearnTaskCourseService.list(courseWrapper);
                if (CollUtil.isEmpty(courseList)) {
                    continue;
                }
                List<String> courseIds = courseList.stream().map(FtbCultivateLearnTaskCourse::getCourseId).collect(Collectors.toList());
                realInitCourseStudyRecord(userIds, courseIds);
            }
        }), cultivateThreadPool);
    }

    /**
     * 检查岗位学习
     *
     * @param userId   用户id
     * @param tenantId 租户id
     */
    public void checkCultivateLearning(String userId, String tenantId) {
        CompletableFuture.runAsync(ThreadContext.wrap(() -> {
            userApiV2Util.checkOutTenant(tenantId);
            v2CultivatePostStudyService.dealPositionReCheckStudy(CultivateMqDTO.builder().userId(userId).tenantId(tenantId).build());
        }), cultivateThreadPool);
    }


    /**
     * 检查课程完成
     *
     * @param dto   课程信息
     * @param state 学习状态 1已学习，0未学习,2学习中
     */
    public void checkCourseComplete(V2CourseAppDto dto, Integer state) {
        String tenantId = UserProvider.getUser().getTenantId();
        String userId = dto.getUserId();
        String courseId = dto.getCourseId();
        if (state == null || state == 0 || state == 2) {
            return;
        }

        CompletableFuture.runAsync(ThreadContext.wrap(() -> {
            userApiV2Util.checkOutTenant(tenantId);
            //备注一下就是 岗位学习 、 学习任务 、通用课程 都不能选择限时的 考试是吧
            CultivateMqDTO message = CultivateMqDTO.builder().userId(userId)
                    .tenantId(tenantId).businessId(courseId)
                    .businessSource(dto.getBusinessSource())
                    .businessSourceId(dto.getBusinessSourceId())
                    .type(CultivateTypeEnum.COURSE).build();
            switch (dto.getBusinessSource()) {
                case POST_LEARNING:
                    v2CultivatePostStudyService.dealPositionCourseStudy(message);
                    break;
                case TASK_LEARNING:
                    v2CultivateTaskStudyService.dealTaskCourseStudy(message);
                    break;
                case GENERAL_COURSE:
                case OFFLINE_CLASS:
                    v2CultivatePostStudyService.dealCommonCourseStudy(message);
                    break;
                default:
            }
        }), cultivateThreadPool);
    }
}