package jnpf.cultivate.event.impl.certificate;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.base.entity.SuperBaseEntity;
import jnpf.cultivate.event.JnpfApplicationEventService;
import jnpf.cultivate.mapper.*;
import jnpf.cultivate.service.FtbCultivateExamUserService;
import jnpf.cultivate.utils.CultivateImUtil;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.entity.cultivate.CultivateIdentifyApply;
import jnpf.model.cultivate.event.dto.certificate.CertificateEventDTO;
import jnpf.model.cultivate.po.FtbCultivatePositionCourseCertificate;
import jnpf.model.cultivate.po.certificate.FtbCertificateEntity;
import jnpf.model.cultivate.po.certificate.FtbCertificateUserEntity;
import jnpf.model.cultivate.po.course.FtbCultivateCertificateResult;
import jnpf.model.cultivate.po.course.FtbCultivateCourse;
import jnpf.model.cultivate.po.exam.FtbCultivateExamUser;
import jnpf.model.cultivate.po.learn.*;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCertificate;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourseExam;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourseIdentity;
import jnpf.model.cultivate.po.position.FtbCultivatePositionIdentifyResult;
import jnpf.model.enums.CourseEnums;
import jnpf.model.enums.SelfrowingEnum;
import jnpf.permission.vo.v2.position.PositionVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.SelfGrowthUtil;
import jnpf.util.UserProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
@RequiredArgsConstructor
@SuppressWarnings("Duplicates")
@Slf4j
public class JnpfApplicationEventCertificateService implements JnpfApplicationEventService {

    private final FtbCultivatePromotionNewMapper ftbCultivatePromotionNewMapper;
    private final FtbCultivateCertificateUserMapper ftbCultivateCertificateUserMapper;
    private final FtbCultivateCertificateMapper ftbCultivateCertificateMapper;
    private final FtbCultivatePositionCertificateMapper ftbCultivatePositionCertificateMapper;
    private final FtbCultivatePositionCourseCertificateMapper ftbCultivatePositionCourseCertificateMapper;
    private final FtbCultivateCourseMapper ftbCultivateCourseMapper;
    private final FtbCultivateLearnTaskCertificateMapper ftbCultivateLearnTaskCertificateMapper;
    private final FtbCultivateLearnTaskMapper learnTaskMapper;
    private final FtbCultivateLearnTaskExamMapper learnTaskExamMapper;
    private final FtbCultivateLearnTaskIdentificationMapper learnTaskIdentificationMapper;
    private final FtbCultivateLearnTaskAssignmentMapper learnTaskAssignmentMapper;
    private final CultivateIdentifyApplyMapper cultivateIdentifyApplyMapper;
    private final FtbCultivateExamUserService ftbCultivateExamUserService;
    private final CultivateImUtil cultivateImUtil;
    private final FtbCultivatePositionCourseIdentityMapper ftbCultivatePositionCourseIdentityMapper;
    private final FtbCultivatePositionIdentifyResultMapper ftbCultivatePositionIdentifyResultMapper;
    private final FtbCultivatePositionCourseExamMapper ftbCultivatePositionCourseExamMapper;
    private final FtbCultivateExamUserMapper ftbCultivateExamUserMapper;

    private final FtbCultivateCertificateResultMapper ftbCultivateCertificateResultMapper;
    @Autowired
    private UserApiV2Util userApiV2Util;


    @Override
    public boolean isSupportedCourseEvent(Object event) {
        return event instanceof CertificateEventDTO;
    }

    @Override
    public void handlerCourseEvent(Object courseEvent) {
        CertificateEventDTO certEventDTO = (CertificateEventDTO) courseEvent;
        //颁发类型  0 课程证书 1 岗位学习证书, 2 任务证书
        log.error("自动颁发证书参数:" + certEventDTO.toString());
        Integer issuanceType = certEventDTO.getIssuanceType();
        // 岗位学习颁发
        if (issuanceType == 1) awardedForOnTheJobLearning(certEventDTO);
        //  课程颁发
        if (issuanceType == 0) courseAwarded(certEventDTO);
        //  任务颁发
        if (issuanceType == 2) taskIssuance(certEventDTO);

    }

    /**
     * 课程颁发
     *
     * @param certEventDTO
     */
    private void courseAwarded(CertificateEventDTO certEventDTO) {
        String userId = certEventDTO.getUserId();
        String courseId = certEventDTO.getCourseId();
        String postId = certEventDTO.getPostId();
        String reason = "课程学习自动颁发证书";
        PositionVO positionEntity = userApiV2Util.infoPosition(postId, null);
        if (positionEntity ==null) {
            positionEntity = new PositionVO();
        }

        FtbCultivateCourse ftbCultivateCourse = ftbCultivateCourseMapper.selectById(courseId);
        String contentMessage = "您已完成【" + positionEntity.getFullName() + "】岗位中【" + ftbCultivateCourse.getName() + "】课程学习";
        LambdaQueryWrapper<FtbCultivatePositionCourseCertificate> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbCultivatePositionCourseCertificate::getPostRankId, postId);
        queryWrapper.eq(FtbCultivatePositionCourseCertificate::getCourseId, courseId);
        queryWrapper.eq(FtbCultivatePositionCourseCertificate::getEnabledMark, 0);
        // 课程绑定证书
        FtbCultivatePositionCourseCertificate certificate = ftbCultivatePositionCourseCertificateMapper.selectOne(queryWrapper);
        if (certificate == null) {
            return;
        }
        // 证书是否下架及删除
        FtbCertificateEntity ftbCertificateEntity = ftbCultivateCertificateMapper.selectById(certificate.getCertificateId());
        if (ftbCertificateEntity.getStatus() == 0 || CourseEnums.EnabledMarkType.INVALID.getCode().equals(ftbCertificateEntity.getEnabledMark())) {
            return;
        }

        //查询是否颁发
        LambdaQueryWrapper<FtbCultivateCertificateResult> certificateResultLambdaQueryWrapper = Wrappers.lambdaQuery();
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getUserId, certEventDTO.getUserId());
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getPostRankId, certEventDTO.getPostId());
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getCertificateId, certificate.getCertificateId());
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getCourseId, certificate.getCourseId());
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getType, 2);//来源，1：岗位学习证书，2：课程证书  3： 任务证书
        FtbCultivateCertificateResult ftbCultivateCertificateResult = ftbCultivateCertificateResultMapper.selectOne(certificateResultLambdaQueryWrapper);
        if (null != ftbCultivateCertificateResult) {
            return;
        }
        //查询课程是否有考试
        LambdaQueryWrapper<FtbCultivatePositionCourseExam> courseExamWraper = Wrappers.lambdaQuery();
        courseExamWraper.eq(FtbCultivatePositionCourseExam::getPostRankId, postId);
        courseExamWraper.eq(FtbCultivatePositionCourseExam::getCourseId, courseId);
        courseExamWraper.eq(FtbCultivatePositionCourseExam::getEnabledMark, 0);
        FtbCultivatePositionCourseExam courseExam = ftbCultivatePositionCourseExamMapper.selectOne(courseExamWraper);
        if (null != courseExam) {
            LambdaQueryWrapper<FtbCultivateExamUser> userExamWraper = Wrappers.lambdaQuery();
            userExamWraper.eq(FtbCultivateExamUser::getUserId, userId);
            userExamWraper.eq(FtbCultivateExamUser::getExamId, courseExam.getExamId());
            userExamWraper.eq(FtbCultivateExamUser::getExamSource, 1);
            userExamWraper.eq(FtbCultivateExamUser::getEnabledMark, 1);
            userExamWraper.eq(FtbCultivateExamUser::getRelationPositionId, postId);
            userExamWraper.orderByDesc(FtbCultivateExamUser::getCreatorTime);
            userExamWraper.last("limit 1");
            FtbCultivateExamUser examUser = ftbCultivateExamUserMapper.selectOne(userExamWraper);
            if (null == examUser) {
                log.error("课程关联考试未触发{}", certEventDTO);
                return;
            }
            //（0待考试，1待批阅，2已逾期，3合格，4不合格 5优秀）
            if (examUser.getStatus() == 0 || examUser.getStatus() == 1 || examUser.getStatus() == 2 || examUser.getStatus() == 4) {
                log.error("课程关联考试不合格{}", examUser);
                return;
            }
        }
        //查课程是否有鉴定
        LambdaQueryWrapper<FtbCultivatePositionCourseIdentity> courseIdentifyWraper = Wrappers.lambdaQuery();
        courseIdentifyWraper.eq(FtbCultivatePositionCourseIdentity::getPostRankId, postId);
        courseIdentifyWraper.eq(FtbCultivatePositionCourseIdentity::getCourseId, courseId);
        courseIdentifyWraper.eq(FtbCultivatePositionCourseIdentity::getEnabledMark, 0);
        FtbCultivatePositionCourseIdentity courseIdentity = ftbCultivatePositionCourseIdentityMapper.selectOne(courseIdentifyWraper);
        if (null != courseIdentity) {
            //查询鉴定结果表
            LambdaQueryWrapper<FtbCultivatePositionIdentifyResult> identityResultWraper = Wrappers.lambdaQuery();
            identityResultWraper.eq(FtbCultivatePositionIdentifyResult::getPostRankId, postId);
            identityResultWraper.eq(FtbCultivatePositionIdentifyResult::getUserId, userId);
            identityResultWraper.eq(FtbCultivatePositionIdentifyResult::getType, 2);
            identityResultWraper.eq(FtbCultivatePositionIdentifyResult::getIdentifyId, courseIdentity.getIdentityId());
            identityResultWraper.eq(FtbCultivatePositionIdentifyResult::getEnabledMark, 0);
            identityResultWraper.orderByDesc(FtbCultivatePositionIdentifyResult::getCreatorTime);
            identityResultWraper.last("limit 1");
            FtbCultivatePositionIdentifyResult ftbCultivatePositionIdentifyResult = ftbCultivatePositionIdentifyResultMapper.selectOne(identityResultWraper);
            if (null == ftbCultivatePositionIdentifyResult) {
                log.error("课程的鉴定为触发{}", certEventDTO);
                return;
            }
            //查询鉴定申请表
            CultivateIdentifyApply identifyApply = cultivateIdentifyApplyMapper.selectById(ftbCultivatePositionIdentifyResult.getIdentifyRecordId());
            if (identifyApply == null) {
                log.error("课程鉴定申请表为null{}", certEventDTO);
                return;
            }
            if (identifyApply.getStatus() != 1) {
                log.error("课程鉴定申请表未鉴定{},", certEventDTO, identifyApply);
                return;
            }

            //鉴定结果(0-合格，1-优秀，2-不合格)
            Integer result = identifyApply.getResult();
            // 颁发规则鉴定(0 合格, 1 优秀)
            if (result == 2) {
                log.error("课程关联鉴定不合格{}，{}", certEventDTO, identifyApply);
                return;
            }
        }
        // 课程学习完成
        doCreateCertificate(userId, postId, certificate.getCertificateId(), reason, contentMessage);

        FtbCultivateCertificateResult cultivateCertificateResult = new FtbCultivateCertificateResult();
        cultivateCertificateResult.setUserId(certEventDTO.getUserId());
        cultivateCertificateResult.setCertificateId(certificate.getCertificateId());
        cultivateCertificateResult.setPostRankId(certEventDTO.getPostId());
        cultivateCertificateResult.setCourseId(certEventDTO.getCourseId());
        cultivateCertificateResult.setType(2);//来源，1：岗位学习证书，2：课程证书  3： 任务证书
        ftbCultivateCertificateResultMapper.insert(cultivateCertificateResult);

    }

    /**
     * 任务颁发
     *
     * @param certEventDTO
     */
    private void taskIssuance(CertificateEventDTO certEventDTO) {
        // 任务存在
        // 用户id
        String userId = certEventDTO.getUserId();
        // 任务id
        String taskId = certEventDTO.getTaskId();
        // 来源(必传),0无绑定考试和实操鉴定，1考试，2实操
        Integer source = certEventDTO.getSource();
        LambdaQueryWrapper<FtbCultivateLearnTask> taskQuery = Wrappers.lambdaQuery();
        taskQuery.eq(FtbCultivateLearnTask::getEnableMark, 0);
        taskQuery.eq(SuperBaseEntity.SuperIBaseEntity::getId, taskId);
        FtbCultivateLearnTask learnTask = learnTaskMapper.selectOne(taskQuery);
        if (learnTask == null) return;
        // 查询任务关联证书
        LambdaQueryWrapper<FtbCultivateLearnTaskCertificate> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbCultivateLearnTaskCertificate::getTaskId, taskId);
        FtbCultivateLearnTaskCertificate learnTaskCertificate = ftbCultivateLearnTaskCertificateMapper.selectOne(queryWrapper);
        if (learnTaskCertificate == null) return;
        // 证书是否下架及删除
        FtbCertificateEntity ftbCertificateEntity = ftbCultivateCertificateMapper.selectById(learnTaskCertificate.getCertificateId());
        if (ftbCertificateEntity.getStatus() == 0 || CourseEnums.EnabledMarkType.INVALID.getCode().equals(ftbCertificateEntity.getEnabledMark())) {
            return;
        }

        //查询是否颁发
        LambdaQueryWrapper<FtbCultivateCertificateResult> certificateResultLambdaQueryWrapper = Wrappers.lambdaQuery();
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getUserId, certEventDTO.getUserId());
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getTaskId, certEventDTO.getTaskId());
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getCertificateId, learnTaskCertificate.getCertificateId());
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getType, 3);//来源，1：岗位学习证书，2：课程证书  3： 任务证书
        FtbCultivateCertificateResult ftbCultivateCertificateResult = ftbCultivateCertificateResultMapper.selectOne(certificateResultLambdaQueryWrapper);
        if (null != ftbCultivateCertificateResult) {
            return;
        }
        // 查询任务绑定考试
        LambdaQueryWrapper<FtbCultivateLearnTaskExam> learnTaskExamLambdaQueryWrapper = Wrappers.lambdaQuery();
        learnTaskExamLambdaQueryWrapper.eq(FtbCultivateLearnTaskExam::getTaskId, taskId);
        FtbCultivateLearnTaskExam ftbCultivateLearnTaskExam = learnTaskExamMapper.selectOne(learnTaskExamLambdaQueryWrapper);
        // 查询任务绑定实操鉴定
        LambdaQueryWrapper<FtbCultivateLearnTaskIdentification> learnTaskIdentificationLambdaQueryWrapper = Wrappers.lambdaQuery();
        learnTaskIdentificationLambdaQueryWrapper.eq(FtbCultivateLearnTaskIdentification::getTaskId, taskId);
        FtbCultivateLearnTaskIdentification learnTaskIdentification = learnTaskIdentificationMapper.selectOne(learnTaskIdentificationLambdaQueryWrapper);
        // 绑定鉴定
        String reason = "任务学习自动颁发证书";
        String contentMessage = "您已完成【" + learnTask.getTaskName() + "】";
        // 任务颁发规则配置1.考试 合格或者优秀
        // 颁发规则考试(0 合格, 1 优秀)
        Integer examRule = learnTaskCertificate.getExamRule();
        // 任务颁发规则配置2.鉴定 合格或者优秀
        Integer identificationRule = learnTaskCertificate.getIdentificationRule();
        if (source == 0) {
            // 记录证书颁发
            recordCertificateIssuance(userId, taskId);
            recordTaskComplete(userId, taskId);
            doCreateCertificate(userId, null, learnTaskCertificate.getCertificateId(), reason, contentMessage);
        } else {
            boolean examFlag = false, identificationFlag = false;
            boolean userTaskIsComplete = true;//true记录完成  false 不记录完成
            if (ftbCultivateLearnTaskExam == null) {
                examFlag = true;
            } else {
                // 考试情况
                // 考试id
                // 根据任务id加考试id+用户id查询当前人的考试情况
                String examId = ftbCultivateLearnTaskExam.getExamId();
                //-1 没有考试记录 0:未完成考试 3合格 5优秀
                Integer forTask = ftbCultivateExamUserService.queryExamResultForTask(taskId, userId);
                if (examRule == 0 && (forTask == 3 || forTask == 5)) {
                    examFlag = true;
                } else if (examRule == 1 && forTask == 5) {
                    examFlag = true;
                }
                if (ftbCultivateLearnTaskExam.getIsPassComplete() == 1 && !(forTask == 3 || forTask == 5)) {
                    userTaskIsComplete = false;
                }
                if (ftbCultivateLearnTaskExam.getIsPassComplete() == 0 && !(forTask == 3 || forTask == 5 || forTask == 4)) {
                    userTaskIsComplete = false;
                }
            }
            // 不存在鉴定
            if (learnTaskIdentification == null) {
                identificationFlag = true;
            } else {
                String identificationId = learnTaskIdentification.getIdentificationId();
                // 根据任务id加鉴定id+用户id查询当前人的鉴定情况
                LambdaQueryWrapper<CultivateIdentifyApply> identifyApplyLambdaQueryWrapper = Wrappers.lambdaQuery();
                identifyApplyLambdaQueryWrapper.eq(CultivateIdentifyApply::getSourceId, taskId);
                identifyApplyLambdaQueryWrapper.eq(CultivateIdentifyApply::getBeIdentifyUserId, userId);
                identifyApplyLambdaQueryWrapper.eq(CultivateIdentifyApply::getSource, 4);
                identifyApplyLambdaQueryWrapper.eq(CultivateIdentifyApply::getDeleteMark, 0);
                CultivateIdentifyApply identifyApply = cultivateIdentifyApplyMapper.selectOne(identifyApplyLambdaQueryWrapper);
                if (identifyApply == null) {
                    identificationFlag = false;
                    userTaskIsComplete = false;
                } else {
                    if (identifyApply.getStatus() == 1) {//鉴定状态(0待鉴定，1已鉴定，2逾期未鉴定)
                        //鉴定结果(0-合格，1-优秀，2-不合格)
                        Integer result = identifyApply.getResult();
                        // 颁发规则鉴定(0 合格, 1 优秀)
                        if (identificationRule == 0 && result != null && (result == 0 || result == 1)) {
                            identificationFlag = true;
                        } else if (identificationRule == 1 && result != null && result == 1) {
                            identificationFlag = true;
                        }

                        if (learnTaskIdentification.getIsPassComplete() == 1 && !(result == 0 || result == 1)) {
                            userTaskIsComplete = false;
                        }
                    } else {
                        identificationFlag = false;
                        userTaskIsComplete = false;
                    }
                }

            }
            log.error("examFlag && identificationFlag={},{},certEventDTO=", examFlag, identificationFlag, certEventDTO);
            // 满足条件颁发证书
            if (examFlag && identificationFlag) {
                // 记录证书颁发
                recordCertificateIssuance(userId, taskId);
                doCreateCertificate(userId, null, learnTaskCertificate.getCertificateId(), reason, contentMessage);
                FtbCultivateCertificateResult cultivateCertificateResult = new FtbCultivateCertificateResult();
                cultivateCertificateResult.setUserId(certEventDTO.getUserId());
                cultivateCertificateResult.setCertificateId(learnTaskCertificate.getCertificateId());
                cultivateCertificateResult.setTaskId(certEventDTO.getTaskId());
                cultivateCertificateResult.setType(3);//来源，1：岗位学习证书，2：课程证书  3： 任务证书
                ftbCultivateCertificateResultMapper.insert(cultivateCertificateResult);
            }
            if (userTaskIsComplete) {
                recordTaskComplete(userId, taskId);
            }
        }


    }

    /**
     * 记录证书颁发
     *
     * @param userId
     * @param taskId
     */
    private void recordCertificateIssuance(String userId, String taskId) {
        // 任务记录证书颁发
        LambdaUpdateWrapper<FtbCultivateLearnTaskAssignment> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(FtbCultivateLearnTaskAssignment::getIssuedCertificate, 1);
        updateWrapper.eq(FtbCultivateLearnTaskAssignment::getUserId, userId);
        updateWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, taskId);
        learnTaskAssignmentMapper.update(null, updateWrapper);
    }

    /**
     * 记录任务完成
     *
     * @param userId
     * @param taskId
     */
    private void recordTaskComplete(String userId, String taskId) {
        // 任务记录证书颁发
        LambdaUpdateWrapper<FtbCultivateLearnTaskAssignment> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(FtbCultivateLearnTaskAssignment::getStudyStats, 2);
        updateWrapper.set(FtbCultivateLearnTaskAssignment::getLearningEndTime, new Date());
        updateWrapper.eq(FtbCultivateLearnTaskAssignment::getUserId, userId);
        updateWrapper.eq(FtbCultivateLearnTaskAssignment::getTaskId, taskId);
        learnTaskAssignmentMapper.update(null, updateWrapper);
    }

    /**
     * 证书颁发
     *
     * @param userId        用户id
     * @param postId        岗位id
     * @param certificateId 证书id
     * @param reason        原因
     * @param content       通知前缀
     */
    private void doCreateCertificate(String userId,
                                     String postId,
                                     String certificateId,
                                     String reason,
                                     String content) {
        FtbCertificateEntity ftbCertificateEntity = ftbCultivateCertificateMapper.selectById(certificateId);
        assert ftbCertificateEntity != null;
        LambdaQueryWrapper<FtbCertificateUserEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbCertificateUserEntity::getCertificateId, certificateId);
        queryWrapper.eq(FtbCertificateUserEntity::getUserId, userId);
        queryWrapper.eq(FtbCertificateUserEntity::getEnabledMark, CourseEnums.EnabledMarkType.VALID.getCode());
        queryWrapper.last("limit 1");
        FtbCertificateUserEntity certificateUserEntity = ftbCultivateCertificateUserMapper.selectOne(queryWrapper);
        //说明证书存在但是是 1已失效，2已吊销 就删除重新颁发
        if (certificateUserEntity != null && (certificateUserEntity.getStatus() == 1 || certificateUserEntity.getStatus() == 2)) {
            certificateUserEntity.setEnabledMark(0);
            ftbCultivateCertificateUserMapper.updateById(certificateUserEntity);
            certificateUserEntity = null;
        }
        // 移除永久颁发跳过,进行原因覆盖
        UserBoundVO userPrimaryBoundOne = userApiV2Util.getUserPrimaryBoundOne(userId, null);
        FtbCertificateUserEntity ftbCertificateUserEntity = new FtbCertificateUserEntity();
        ftbCertificateUserEntity.setUserId(userId);
        if (StringUtils.isNotEmpty(postId)) ftbCertificateUserEntity.setPositionId(postId);
        ftbCertificateUserEntity.setUserName(userPrimaryBoundOne.getUserName());
        // 组织id，取花名册取默认组织id

        if (userPrimaryBoundOne != null) {
            ftbCertificateUserEntity.setOrganizeId(userPrimaryBoundOne.getOrganizeId());
        }
        ftbCertificateUserEntity.setReason(reason);
        ftbCertificateUserEntity.setStatus(0);
        // 前端要求屏蔽证书地址
        //ftbCertificateUserEntity.setImageUrl(ftbCertificateEntity.getTemplate());
        // 证书编号
        ftbCertificateUserEntity.setNumber(SelfGrowthUtil.provideACustomIDBasedOnTheModule(SelfrowingEnum.CERTIFICATE_ENCODING_PREFIX, 4));
        ftbCertificateUserEntity.setCertificateId(certificateId);
        ftbCertificateUserEntity.setCertificateName(ftbCertificateEntity.getName());
        ftbCertificateUserEntity.setCompanyName(ftbCertificateEntity.getCompanyName());
        ftbCertificateUserEntity.setStatus(CourseEnums.CertUserStatus.USING.getCode());
        ftbCertificateUserEntity.setEffectTime(LocalDateTime.now());
        ftbCertificateUserEntity.setEnabledMark(CourseEnums.EnabledMarkType.VALID.getCode());
        Integer entityExpireTime = ftbCertificateEntity.getExpireTime();
        //计算过期日期
        if (certificateUserEntity != null) {
            //说明是原来是永久无需更改时间
            if (certificateUserEntity.getExpireTime() == null) {

            } else {
                //说明原来是有时间的
                if (!CourseEnums.CertExpireType.NEVER.getCode().equals(ftbCertificateEntity.getExpireType())) {
                    //设置失效时间 ExpireTime=0时 null表示永久
                    Date expireTime = certificateUserEntity.getExpireTime();
                    if (CourseEnums.CertExpireType.DAY.getCode().equals(ftbCertificateEntity.getExpireType())) {
                        //添加天数
                        expireTime = DateUtil.offsetDay(expireTime, ftbCertificateEntity.getExpireTime());
                    } else if (CourseEnums.CertExpireType.MONTH.getCode().equals(ftbCertificateEntity.getExpireType())) {
                        expireTime = DateUtil.offsetMonth(expireTime, ftbCertificateEntity.getExpireTime());
                    }
                    ftbCertificateUserEntity.setExpireTime(expireTime);
                } else {
                    //说明原来不是永久 但是现在是永久 不用设置日期

                }
            }

            ftbCertificateUserEntity.setId(certificateUserEntity.getId());
            ftbCultivateCertificateUserMapper.updateById(ftbCertificateUserEntity);
        } else {
            //如果没有 就直接颁发证书
            if (!CourseEnums.CertExpireType.NEVER.getCode().equals(ftbCertificateEntity.getExpireType())) {
                //设置失效时间 ExpireTime=0时 null表示永久
                LocalDateTime expireTime = LocalDateTime.now();
                if (CourseEnums.CertExpireType.DAY.getCode().equals(ftbCertificateEntity.getExpireType())) {
                    expireTime = expireTime.plusDays(entityExpireTime.longValue());
                } else if (CourseEnums.CertExpireType.MONTH.getCode().equals(ftbCertificateEntity.getExpireType())) {
                    expireTime = expireTime.plusMonths(entityExpireTime.longValue());
                }
                Date date = Date.from(expireTime.atZone(ZoneId.systemDefault()).toInstant());
                ftbCertificateUserEntity.setExpireTime(date);
            }
            ftbCultivateCertificateUserMapper.insert(ftbCertificateUserEntity);
        }

        String contentMessage = content + "，恭喜获得" + ftbCertificateEntity.getName() + "证书。您可前往“我的证书”模块查看更多证书！";
        cultivateImUtil.sendMessage(List.of(userId), UserProvider.getUser().getTenantId(), contentMessage);
    }

    /**
     * 岗位学习颁发
     *
     * @param certEventDTO
     */
    private void awardedForOnTheJobLearning(CertificateEventDTO certEventDTO) {
        LambdaQueryWrapper<FtbCultivatePositionCertificate> positionCertificateQueryWrapper = Wrappers.lambdaQuery();
        positionCertificateQueryWrapper.select(FtbCultivatePositionCertificate::getCertificateId);
        positionCertificateQueryWrapper.eq(FtbCultivatePositionCertificate::getPostRankId, certEventDTO.getPostId());
        positionCertificateQueryWrapper.eq(FtbCultivatePositionCertificate::getEnableMark, 0);
        positionCertificateQueryWrapper.last("limit 1");
        FtbCultivatePositionCertificate certificateCertificate = ftbCultivatePositionCertificateMapper.selectOne(positionCertificateQueryWrapper);
        // 该岗位未绑定证书
        if (certificateCertificate == null) {
            return;
        }
        // 证书是否下架及删除
        FtbCertificateEntity ftbCertificateEntity = ftbCultivateCertificateMapper.selectById(certificateCertificate.getCertificateId());
        if (ftbCertificateEntity.getStatus() == 0 || CourseEnums.EnabledMarkType.INVALID.getCode().equals(ftbCertificateEntity.getEnabledMark())) {
            return;
        }
        //查询是否颁发
        LambdaQueryWrapper<FtbCultivateCertificateResult> certificateResultLambdaQueryWrapper = Wrappers.lambdaQuery();
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getUserId, certEventDTO.getUserId());
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getPostRankId, certEventDTO.getPostId());
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getCertificateId, certificateCertificate.getCertificateId());
        certificateResultLambdaQueryWrapper.eq(FtbCultivateCertificateResult::getType, 1);//来源，1：岗位学习证书，2：课程证书  3： 任务证书
        FtbCultivateCertificateResult ftbCultivateCertificateResult = ftbCultivateCertificateResultMapper.selectOne(certificateResultLambdaQueryWrapper);
        if (null != ftbCultivateCertificateResult) {
            return;
        }

        // 重复颁发+失效时间
        String userId = certEventDTO.getUserId();
        String reason = "岗位学习自动颁发证书";
        // 来源0无绑定考试和实操鉴定，1考试，2实操
        String postId = certEventDTO.getPostId();
//        PositionEntity positionEntity = personnelOrgUtils.queryPosition(postId);
        PositionVO positionEntity = userApiV2Util.infoPosition(postId, null);
        if(positionEntity==null){
            positionEntity = new PositionVO();
        }
        String content = "您已完成【" + positionEntity.getFullName() + "】学习";
        if (certEventDTO.getSource() == 0) {
            doCreateCertificate(userId, postId, certificateCertificate.getCertificateId(), reason, content);
            recodePositionResult(certEventDTO, certificateCertificate);
        } else if (certEventDTO.getSource() == 1) {
            // 根据人去查询是否有鉴定
            List<String> applyIds = ftbCultivatePromotionNewMapper.checkWhetherThereIsAPracticalAppraisalWithNew(certEventDTO.getPostId(), userId);
            // 未绑定实操鉴定直接颁发，后添加的去app界面查询时触发
            if (CollUtil.isEmpty(applyIds)) {
                doCreateCertificate(userId, postId, certificateCertificate.getCertificateId(), reason, content);
                recodePositionResult(certEventDTO, certificateCertificate);
                return;
            }
            // 实操鉴定是否合格
            Integer qualified = ftbCultivatePromotionNewMapper.queryTheNumberOfPracticalAppraisalStudies(List.of(certEventDTO.getPostId())
                    , userId, applyIds, 1);
            if (qualified > 0) {
                doCreateCertificate(userId, postId, certificateCertificate.getCertificateId(), reason, content);
                recodePositionResult(certEventDTO, certificateCertificate);
            }
        } else if (certEventDTO.getSource() == 2) {
            // 未绑定考试直接颁发，后添加的去app界面查询时触发
            String examId = ftbCultivatePositionCertificateMapper.queryJobPracticalExamByPostId(certEventDTO.getPostId());
            if (StrUtil.isBlank(examId)) {
                doCreateCertificate(userId, postId, certificateCertificate.getCertificateId(), reason, content);
                recodePositionResult(certEventDTO, certificateCertificate);
                return;
            }
            // 考试是否合格
            Integer qualified = ftbCultivateExamUserService.queryExamIsCompleteForUserIdAndPostion(userId,
                    certEventDTO.getPostId(), 1);
            if (qualified == 1) {
                doCreateCertificate(userId, postId, certificateCertificate.getCertificateId(), reason, content);
                recodePositionResult(certEventDTO, certificateCertificate);
            }
        }
    }

    /**
     * 记录证书颁发结果幂等性考虑
     *
     * @param certEventDTO
     * @param certificateCertificate
     */
    private void recodePositionResult(CertificateEventDTO certEventDTO, FtbCultivatePositionCertificate certificateCertificate) {
        FtbCultivateCertificateResult cultivateCertificateResult = new FtbCultivateCertificateResult();
        cultivateCertificateResult.setUserId(certEventDTO.getUserId());
        cultivateCertificateResult.setCertificateId(certificateCertificate.getCertificateId());
        cultivateCertificateResult.setPostRankId(certEventDTO.getPostId());
        cultivateCertificateResult.setType(1);//来源，1：岗位学习证书，2：课程证书  3： 任务证书
        ftbCultivateCertificateResultMapper.insert(cultivateCertificateResult);
    }

    /**
     * 将两个 Date 对象相加
     *
     * @param date1 第一个日期
     * @param date2 第二个日期
     * @return 相加后的新日期
     */
    public Date addDates(Date date1, Date date2) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date1); // 设置为 date1 的时间
        // 将 date2 的时间差加到 calendar 上
        long timeInMillis = date2.getTime();
        calendar.add(Calendar.MILLISECOND, (int) (timeInMillis / 1000));

        return calendar.getTime();
    }
}
