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.extension.service.impl.ServiceImpl;
import jnpf.cultivate.mapper.CultivatePositionCourseLogMapper;
import jnpf.cultivate.mapper.FtbCultivatePositionLogMapper;
import jnpf.cultivate.v2.service.FtbCultivatePositionLogService;
import jnpf.entity.cultivate.CultivateIdentifyApply;
import jnpf.entity.cultivate.CultivatePositionCourseLogEntity;
import jnpf.model.cultivate.po.exam.FtbCultivateExamUser;
import jnpf.model.cultivate.po.position.FtbCultivatePositionLog;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 岗位学习完成记录表服务实现类
 */
@Service
public class FtbCultivatePositionLogServiceImpl extends ServiceImpl<FtbCultivatePositionLogMapper, FtbCultivatePositionLog> implements FtbCultivatePositionLogService {

    @Autowired
    CultivatePositionCourseLogMapper cultivatePositionCourseLogMapper;

    /**
     * 根据条件保存或更新用户职位学习记录
     * 该方法会根据传入的用户ID、职位学习ID等条件来决定是保存新记录还是更新现有记录
     *
     * @param userId          用户ID，用于标识操作的用户
     * @param positionLearnId 职位学习ID，用于标识具体的职位学习记录
     * @param postId          职位ID，关联到具体的职位信息
     * @param gradeId         年级ID，表示用户所在的年级信息
     * @param courseId        课程id
     */
    @Override
    public void completePositionCourse(String userId, String positionLearnId, String postId, String gradeId, String courseId) {
        LambdaQueryWrapper<CultivatePositionCourseLogEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CultivatePositionCourseLogEntity::getPostLearnId, positionLearnId)
                .eq(StringUtils.isNotEmpty(gradeId), CultivatePositionCourseLogEntity::getGradeId, gradeId)
                .eq(CultivatePositionCourseLogEntity::getUserId, userId)
                .eq(CultivatePositionCourseLogEntity::getCourseId, courseId)
                .eq(CultivatePositionCourseLogEntity::getEnabledMark, 0);
        List<CultivatePositionCourseLogEntity> logList = cultivatePositionCourseLogMapper.selectList(queryWrapper);

        if (CollUtil.isNotEmpty(logList)) {
            LambdaUpdateWrapper<CultivatePositionCourseLogEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(CultivatePositionCourseLogEntity::getPostLearnId, positionLearnId)
                    .eq(StringUtils.isNotEmpty(gradeId), CultivatePositionCourseLogEntity::getGradeId, gradeId)
                    .eq(CultivatePositionCourseLogEntity::getUserId, userId)
                    .eq(CultivatePositionCourseLogEntity::getEnabledMark, 0)
                    .eq(CultivatePositionCourseLogEntity::getCourseId, courseId)
                    .set(CultivatePositionCourseLogEntity::getState, 2)
                    .set(CultivatePositionCourseLogEntity::getTenantId, "1")//todo 打一个标记 后面删除

            ;
            cultivatePositionCourseLogMapper.update(null, updateWrapper);
        } else {
            // 如果不存在，则新增
            CultivatePositionCourseLogEntity newLog = new CultivatePositionCourseLogEntity();
            newLog.setPostLearnId(positionLearnId);
            newLog.setPostId(postId);
            newLog.setGradeId(gradeId);
            newLog.setCourseId(courseId);
            newLog.setUserId(userId);
            newLog.setState(2);
            newLog.setEnabledMark(0);
            newLog.setTenantId("2");//todo 打一个标记 后面删除
            cultivatePositionCourseLogMapper.insert(newLog);
        }
    }

    /**
     * 查询用户已完成的职位学习记录
     *
     * @param userId 用户ID
     * @return 职位学习记录列表
     */
    @Override
    public List<FtbCultivatePositionLog> queryMyCompletePosition(String userId) {
        LambdaQueryWrapper<FtbCultivatePositionLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(FtbCultivatePositionLog::getState, 2)
                .eq(FtbCultivatePositionLog::getUserId, userId)
                .eq(FtbCultivatePositionLog::getEnabledMark, 0);
        return this.list(queryWrapper);

    }

    @Override
    public List<FtbCultivatePositionLog> batchQueryCompletePosition(List<String> currUserIds) {
        LambdaQueryWrapper<FtbCultivatePositionLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(FtbCultivatePositionLog::getState, 2)
                .in(FtbCultivatePositionLog::getUserId, currUserIds)
                .eq(FtbCultivatePositionLog::getEnabledMark, 0);
        return this.list(queryWrapper);
    }

    /**
     * 根据条件保存或更新用户职位学习记录
     * 该方法会根据传入的用户ID、职位学习ID等条件来决定是保存新记录还是更新现有记录
     *
     * @param userId          用户ID，用于标识操作的用户
     * @param positionLearnId 职位学习ID，用于标识具体的职位学习记录
     * @param postId          职位ID，关联到具体的职位信息
     * @param gradeId         年级ID，表示用户所在的年级信息
     * @param tenantId        租户ID
     */
    @Override
    public void completePosition(String userId, String positionLearnId, String postId, String gradeId, String tenantId) {
        LambdaQueryWrapper<FtbCultivatePositionLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FtbCultivatePositionLog::getPostLearnId, positionLearnId)
                .eq(FtbCultivatePositionLog::getPostId, postId)
                .eq(StringUtils.isNotEmpty(gradeId), FtbCultivatePositionLog::getGradeId, gradeId)
                .eq(FtbCultivatePositionLog::getUserId, userId)
                .eq(FtbCultivatePositionLog::getEnabledMark, 0);
        List<FtbCultivatePositionLog> logList = this.list(queryWrapper);

        if (CollUtil.isNotEmpty(logList)) {
            LambdaUpdateWrapper<FtbCultivatePositionLog> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(FtbCultivatePositionLog::getPostLearnId, positionLearnId)
                    .eq(FtbCultivatePositionLog::getPostId, postId)
                    .eq(StringUtils.isNotEmpty(gradeId), FtbCultivatePositionLog::getGradeId, gradeId)
                    .eq(FtbCultivatePositionLog::getUserId, userId)
                    .eq(FtbCultivatePositionLog::getEnabledMark, 0)
                    .set(FtbCultivatePositionLog::getState, 2)
            ;
            this.update(updateWrapper);
        } else {
            // 如果不存在，则新增
            FtbCultivatePositionLog newLog = new FtbCultivatePositionLog();
            newLog.setPostLearnId(positionLearnId);
            newLog.setPostId(postId);
            newLog.setGradeId(gradeId);
            newLog.setUserId(userId);
            newLog.setState(2);
            newLog.setEnabledMark(0);
            this.save(newLog);
        }
    }

    /**
     * 查询用户是否完成职位学习
     *
     * @param userId          用户ID
     * @param positionLearnId 职位学习ID
     * @param postId          职位ID
     * @param gradeId         年级ID
     * @param tenantId        租户ID
     * @return true 表示用户已完成职位学习，false 表示用户未完成职位学习
     */
    @Override
    public boolean selectIsCompletePosition(String userId, String positionLearnId, String postId, String gradeId, String tenantId) {
        LambdaQueryWrapper<FtbCultivatePositionLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FtbCultivatePositionLog::getPostLearnId, positionLearnId)
                .eq(FtbCultivatePositionLog::getPostId, postId)
                .eq(StringUtils.isNotEmpty(gradeId), FtbCultivatePositionLog::getGradeId, gradeId)
                .eq(FtbCultivatePositionLog::getUserId, userId)
                .eq(FtbCultivatePositionLog::getState, 2)
                .eq(FtbCultivatePositionLog::getEnabledMark, 0);
        List<FtbCultivatePositionLog> logList = this.list(queryWrapper);
        if (CollUtil.isEmpty(logList)) {
            return false;
        }
        return true;
    }

    @Override
    public CultivatePositionCourseLogEntity queryIsTriggerExam(String positionLearnId, String userId, String courseId, String gradeId) {
        LambdaQueryWrapper<CultivatePositionCourseLogEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CultivatePositionCourseLogEntity::getPostLearnId, positionLearnId)
                .eq(CultivatePositionCourseLogEntity::getUserId, userId)
                .eq(CultivatePositionCourseLogEntity::getCourseId, courseId)
                .eq(StringUtils.isNotEmpty(gradeId), CultivatePositionCourseLogEntity::getGradeId, gradeId)
                .eq(CultivatePositionCourseLogEntity::getEnabledMark, 0).orderByAsc(CultivatePositionCourseLogEntity::getCreatorTime);
        return cultivatePositionCourseLogMapper.selectOne(queryWrapper);

    }

    @Override
    public void recordUserExamId(String positionLearnId, String userId, String courseId, String gradeId, FtbCultivateExamUser ftbCultivateExamUser) {
        LambdaQueryWrapper<CultivatePositionCourseLogEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CultivatePositionCourseLogEntity::getPostLearnId, positionLearnId)
                .eq(CultivatePositionCourseLogEntity::getUserId, userId)
                .eq(CultivatePositionCourseLogEntity::getCourseId, courseId)
                .eq(StringUtils.isNotEmpty(gradeId), CultivatePositionCourseLogEntity::getGradeId, gradeId)
                .eq(CultivatePositionCourseLogEntity::getEnabledMark, 0);
        List<CultivatePositionCourseLogEntity> logList = cultivatePositionCourseLogMapper.selectList(queryWrapper);

        if (CollUtil.isNotEmpty(logList)) {
            LambdaUpdateWrapper<CultivatePositionCourseLogEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(CultivatePositionCourseLogEntity::getPostLearnId, positionLearnId)
                    .eq(CultivatePositionCourseLogEntity::getUserId, userId)
                    .eq(CultivatePositionCourseLogEntity::getEnabledMark, 0)
                    .eq(CultivatePositionCourseLogEntity::getCourseId, courseId)
                    .eq(StringUtils.isNotEmpty(gradeId), CultivatePositionCourseLogEntity::getGradeId, gradeId)
                    .set(ftbCultivateExamUser != null, CultivatePositionCourseLogEntity::getHasExam, 2)
                    .set(CultivatePositionCourseLogEntity::getExamId, ftbCultivateExamUser.getExamId())
                    .set(CultivatePositionCourseLogEntity::getUserExamId, ftbCultivateExamUser.getId())
                    .set(CultivatePositionCourseLogEntity::getUserExamStatus, ftbCultivateExamUser.getStatus())
            ;
            cultivatePositionCourseLogMapper.update(null, updateWrapper);
        } else {
            // 如果不存在，则新增
            CultivatePositionCourseLogEntity newLog = new CultivatePositionCourseLogEntity();
            newLog.setPostLearnId(positionLearnId);
            newLog.setCourseId(courseId);
            newLog.setUserId(userId);
            if (ftbCultivateExamUser != null) {
                newLog.setHasExam(2);
            }
            newLog.setExamId(ftbCultivateExamUser.getExamId());
            newLog.setUserExamId(ftbCultivateExamUser.getId());
            newLog.setUserExamStatus(ftbCultivateExamUser.getStatus());
            newLog.setGradeId(gradeId);
            cultivatePositionCourseLogMapper.insert(newLog);
        }
    }

    @Override
    public void recodePositionCourseExam(String userId, String examId, String userExamId, Integer status) {

        cultivatePositionCourseLogMapper.update(null, new LambdaUpdateWrapper<CultivatePositionCourseLogEntity>()
                .eq(CultivatePositionCourseLogEntity::getUserExamId, userExamId)
                .eq(CultivatePositionCourseLogEntity::getEnabledMark, 0)
                .eq(CultivatePositionCourseLogEntity::getUserId, userId)
                .eq(CultivatePositionCourseLogEntity::getExamId, examId)
                .set(CultivatePositionCourseLogEntity::getUserExamStatus, status));
    }

    @Override
    public void recordUserIdentificationId(String positionLearnId, String userId, String courseId, String gradeId, CultivateIdentifyApply apply) {
        LambdaQueryWrapper<CultivatePositionCourseLogEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CultivatePositionCourseLogEntity::getPostLearnId, positionLearnId)
                .eq(CultivatePositionCourseLogEntity::getUserId, userId)
                .eq(CultivatePositionCourseLogEntity::getCourseId, courseId)
                .eq(StringUtils.isNotEmpty(gradeId), CultivatePositionCourseLogEntity::getGradeId, gradeId)
                .eq(CultivatePositionCourseLogEntity::getEnabledMark, 0);
        List<CultivatePositionCourseLogEntity> logList = cultivatePositionCourseLogMapper.selectList(queryWrapper);

        if (CollUtil.isNotEmpty(logList)) {
            LambdaUpdateWrapper<CultivatePositionCourseLogEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(CultivatePositionCourseLogEntity::getPostLearnId, positionLearnId)
                    .eq(CultivatePositionCourseLogEntity::getUserId, userId)
                    .eq(CultivatePositionCourseLogEntity::getEnabledMark, 0)
                    .eq(CultivatePositionCourseLogEntity::getCourseId, courseId)
                    .eq(StringUtils.isNotEmpty(gradeId), CultivatePositionCourseLogEntity::getGradeId, gradeId)
                    .set(CultivatePositionCourseLogEntity::getIdentifyId, apply.getOriginalTableId())
                    .set(CultivatePositionCourseLogEntity::getUserIdentifyId, apply.getId())
            ;
            if (apply.getStatus().equals(0)) {
                updateWrapper.set(CultivatePositionCourseLogEntity::getUserIdentifyStatus, -1);
            } else {
                updateWrapper.set(CultivatePositionCourseLogEntity::getUserIdentifyStatus, apply.getResult());
            }
            cultivatePositionCourseLogMapper.update(null, updateWrapper);
        } else {
            // 如果不存在，则新增
            CultivatePositionCourseLogEntity newLog = new CultivatePositionCourseLogEntity();
            newLog.setPostLearnId(positionLearnId);
            newLog.setCourseId(courseId);
            newLog.setUserId(userId);
            newLog.setIdentifyId(apply.getOriginalTableId());
            newLog.setUserIdentifyId(apply.getId());
            newLog.setGradeId(gradeId);
            if (apply.getStatus().equals(0)) {
                newLog.setUserIdentifyStatus(-1);
            } else {
                newLog.setUserIdentifyStatus(apply.getResult());
            }
            cultivatePositionCourseLogMapper.insert(newLog);
        }
    }

    @Override
    public void recodePositionCourseIdentify(String userId, String identityId, String userIdentifyId, Integer status, Integer userIdentifyStatus) {
        cultivatePositionCourseLogMapper.update(null,
                new LambdaUpdateWrapper<CultivatePositionCourseLogEntity>()
                        .eq(CultivatePositionCourseLogEntity::getUserIdentifyId, userIdentifyId)
                        .eq(CultivatePositionCourseLogEntity::getUserId, userId)
                        .eq(CultivatePositionCourseLogEntity::getEnabledMark, 0)
                        .set(CultivatePositionCourseLogEntity::getUserIdentifyStatus,
                                status == 0 ? -1 : userIdentifyStatus)
        );
    }

    /**
     * 根据用户ID和学习地图ID查询岗位学习课程记录
     *
     * @param userId      用户ID
     * @param postLearnId 学习地图ID（岗位学习ID）
     * @return 岗位学习课程记录列表
     */
    @Override
    public List<CultivatePositionCourseLogEntity> queryByUserIdAndPostLearnId(String userId, String postLearnId) {
        return cultivatePositionCourseLogMapper.queryByUserIdAndPostLearnId(userId, postLearnId);
    }
}