package jnpf.cultivate.v2.mq;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.constants.MessageTopicConstants;
import jnpf.cultivate.mapper.CultivateIdentifyApplyMapper;
import jnpf.cultivate.mapper.FtbCultivateCertificateUserMapper;
import jnpf.cultivate.mapper.FtbCultivateChapterTestResultMapper;
import jnpf.cultivate.mapper.FtbCultivateExamUserMapper;
import jnpf.cultivate.mapper.FtbCultivateLearnTaskAssignmentMapper;
import jnpf.cultivate.mapper.FtbCultivateOfflineTrainMapper;
import jnpf.cultivate.mapper.FtbCultivatePositionCourceChapterLearningMapper;
import jnpf.cultivate.mapper.FtbCultivatePositionCourceLearningMapper;
import jnpf.cultivate.mapper.FtbCultivatePromotionMemberNewMapper;
import jnpf.cultivate.utils.CultivateLearnUtils;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.cultivate.v2.service.FtbCultivatePromotionUserService;
import jnpf.entity.cultivate.CultivateIdentifyApply;
import jnpf.message.enums.PermissionMessageTagEnum;
import jnpf.message.enums.PermissionUserInfoEnum;
import jnpf.message.model.permission.PermissionRelationOrganizeUserListDTO;
import jnpf.message.model.permission.PermissionRelationUserPositionListDTO;
import jnpf.message.model.permission.UserInfoSaveMessageDTO;
import jnpf.model.cultivate.po.certificate.FtbCertificateUserEntity;
import jnpf.model.cultivate.po.course.FtbCultivateChapterTestResult;
import jnpf.model.cultivate.po.exam.FtbCultivateExamUser;
import jnpf.model.cultivate.po.learn.FtbCultivateLearnTaskAssignment;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceChapterLearning;
import jnpf.model.cultivate.po.position.FtbCultivatePositionCourceLearning;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionMemberNew;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionUser;
import jnpf.model.notice.domain.FtbNoticeAnnouncementsReceive;
import jnpf.model.notice.domain.FtbNoticeUserGroupMembers;
import jnpf.notice.service.FtbNoticeAnnouncementsReceiveService;
import jnpf.notice.service.FtbNoticeUserGroupMembersService;
import jnpf.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 培训请求信息
 */
@Component
@RocketMQMessageListener(
        topic = MessageTopicConstants.PERMISSION_TOPIC,
        consumerGroup = MessageTopicConstants.CULTIVATE_CONSUMER_GROUP,
        selectorExpression = "TAG_USER_INFO_SAVE || TAG_ORGANIZE_RELATION_USER || TAG_USER_RELATION_POSITION",
        replyTimeout = 600000,
        nameServer = "${spring.cloud.stream.rocketmq.binder.name-server}"
)
@Slf4j
public class PermissionConsumerMEListener implements RocketMQListener<MessageExt> {
    @Autowired
    private FtbNoticeUserGroupMembersService ftbNoticeUserGroupMembersService;

    @Autowired
    private FtbNoticeAnnouncementsReceiveService ftbNoticeAnnouncementsReceiveService;

    @Autowired
    private FtbCultivatePromotionUserService ftbCultivatePromotionUserService;

    @Autowired
    private FtbCultivateExamUserMapper ftbCultivateExamUserMapper;

    @Autowired
    private CultivateIdentifyApplyMapper cultivateIdentifyApplyMapper;

    @Autowired
    private FtbCultivatePromotionMemberNewMapper ftbCultivatePromotionMemberNewMapper;

    @Autowired
    private FtbCultivateCertificateUserMapper ftbCultivateCertificateUserMapper;

    @Autowired
    private FtbCultivatePositionCourceLearningMapper ftbCultivatePositionCourceLearningMapper;

    @Autowired
    private FtbCultivatePositionCourceChapterLearningMapper ftbCultivatePositionCourceChapterLearningMapper;

    @Autowired
    private FtbCultivateLearnTaskAssignmentMapper ftbCultivateLearnTaskAssignmentMapper;

    @Autowired
    private FtbCultivateChapterTestResultMapper ftbCultivateChapterTestResultMapper;

    @Autowired
    private FtbCultivateOfflineTrainMapper ftbCultivateOfflineTrainMapper;

    @Autowired
    @Lazy
    private CultivateLearnUtils cultivateLearnUtils;

    @Autowired
    @Lazy
    private UserApiV2Util userApiV2Util;

    @Override
    public void onMessage(MessageExt messageExt) {
        String tag = messageExt.getTags();
        String message = new String(messageExt.getBody(), StandardCharsets.UTF_8);
        if (StringUtil.isEmpty(message)) {
            return;
        }
        log.error("接受组织下人员(批量入职/批量删除/预入职/离职)变更信息{}", message);
        if (PermissionMessageTagEnum.USER_INFO_SAVE.getCode().equals(tag)) {
            try {
                List<UserInfoSaveMessageDTO> messageList =
                        JSON.parseArray(message, UserInfoSaveMessageDTO.class);

                if (CollUtil.isEmpty(messageList)) {
                    return;
                }

                String tenantId = messageList.get(0).getUserInfo().getTenantId();
                userApiV2Util.checkOutTenant(tenantId);

                List<String> deleteUserIds = new ArrayList<>();
                List<String> addUserIds = new ArrayList<>();
                List<String> updateUserIds = new ArrayList<>();

                for (UserInfoSaveMessageDTO userInfoSaveMessageDTO : messageList) {
                    if (userInfoSaveMessageDTO.getOperateType() == PermissionUserInfoEnum.ADD) {
                        addUserIds.add(userInfoSaveMessageDTO.getUserInfo().getId());
                    } else if (userInfoSaveMessageDTO.getOperateType() == PermissionUserInfoEnum.DELETE) {
                        deleteUserIds.add(userInfoSaveMessageDTO.getUserInfo().getId());
                    } else if (userInfoSaveMessageDTO.getOperateType() == PermissionUserInfoEnum.UPDATE) {
                        updateUserIds.add(userInfoSaveMessageDTO.getUserInfo().getId());
                    }
                }

                dealDeleteUser(deleteUserIds, tenantId);
                dealAddUser(addUserIds, tenantId);
                dealUpdateUser(updateUserIds, tenantId);

            } catch (Exception e) {
                log.error("消息解析异常: message={}", message, e);
            }

        } else if (PermissionMessageTagEnum.ORGANIZE_RELATION_USER.getCode().equals(tag)) {
            try {
                List<PermissionRelationOrganizeUserListDTO> messageList =
                        JSON.parseArray(message, PermissionRelationOrganizeUserListDTO.class);

                if (CollUtil.isEmpty(messageList)) {
                    return;
                }
                PermissionRelationOrganizeUserListDTO dto = messageList.get(0);
                String tenantId = dto.getTenantId();
                userApiV2Util.checkOutTenant(tenantId);
                List<String> updateUserIds = new ArrayList<>();
                for (PermissionRelationOrganizeUserListDTO permissionRelationOrganizeUserListDTO : messageList) {
                    updateUserIds.add(permissionRelationOrganizeUserListDTO.getUserId());
                }
                dealOrganizeUpdateUser(updateUserIds, tenantId);
            } catch (Exception e) {
                log.error("组织用户关系消息解析异常: message={}", message, e);
            }

        } else if (PermissionMessageTagEnum.USER_RELATION_POSITION.getCode().equals(tag)) {
            try {
                List<PermissionRelationUserPositionListDTO> messageList =
                        JSON.parseArray(message, PermissionRelationUserPositionListDTO.class);

                if (CollUtil.isEmpty(messageList)) {
                    return;
                }
                PermissionRelationUserPositionListDTO dto = messageList.get(0);
                String tenantId = dto.getTenantId();
                userApiV2Util.checkOutTenant(tenantId);
                List<String> updateUserIds = new ArrayList<>();
                for (PermissionRelationUserPositionListDTO permissionRelationOrganizeUserListDTO : messageList) {
                    updateUserIds.add(permissionRelationOrganizeUserListDTO.getUserId());
                }
                cultivateLearnUtils.dealPositionUpdateUser(updateUserIds, tenantId);
            } catch (Exception e) {
                log.error("组织用户关系消息解析异常: message={}", message, e);
            }

        }else {
            log.error("未知 RocketMQ tag: {}, msgId: {}, body: {}",
                    tag, messageExt.getMsgId(), message);
        }

    }

    private void dealUpdateUser(List<String> updateUserIds, String tenantId) {
        if (CollUtil.isEmpty(updateUserIds)) {
            return;
        }
        cultivateLearnUtils.addNewPersonToTask(updateUserIds, tenantId);
        cultivateLearnUtils.organizeOrPositionChange(updateUserIds, tenantId);
        cultivateLearnUtils.dealPositionUpdateUser(updateUserIds, tenantId);
    }

    private void dealOrganizeUpdateUser(List<String> updateUserIds, String tenantId) {
        if (CollUtil.isEmpty(updateUserIds)) {
            return;
        }
        cultivateLearnUtils.organizeOrPositionChange(updateUserIds, tenantId);
    }

    private void dealAddUser(List<String> addUserIds, String tenantId) {
        if (CollUtil.isEmpty(addUserIds)) {
            return;
        }
        recoverCultivateData(addUserIds, tenantId);
        cultivateLearnUtils.addPromotionUser(addUserIds, tenantId);
        cultivateLearnUtils.addNewPersonToTask(addUserIds, tenantId);
        cultivateLearnUtils.organizeOrPositionChange(addUserIds, tenantId);
        cultivateLearnUtils.dealPositionUpdateUser(addUserIds, tenantId);
    }


    /**
     * 恢复数据
     *
     * @param userIdList 用户集合
     * @param tenantId   租户id
     */
    private void recoverCultivateData(List<String> userIdList, String tenantId) {

        //标记恢复考试记录
        ftbCultivateExamUserMapper.update(null, new LambdaUpdateWrapper<FtbCultivateExamUser>()
                .in(FtbCultivateExamUser::getUserId, userIdList)
                .eq(FtbCultivateExamUser::getLeaveOut, 1)
                .set(FtbCultivateExamUser::getLeaveOut, 0)
                .set(FtbCultivateExamUser::getEnabledMark, 1));

        //标记恢复鉴定记录
        cultivateIdentifyApplyMapper.update(null, new LambdaUpdateWrapper<CultivateIdentifyApply>()
                .in(CultivateIdentifyApply::getBeIdentifyUserId, userIdList)
                .eq(CultivateIdentifyApply::getLeaveOut, 1)
                .set(CultivateIdentifyApply::getLeaveOut, 0)
                .set(CultivateIdentifyApply::getDeleteMark, 0));


        //标记恢复证书
        ftbCultivateCertificateUserMapper.update(null, new LambdaUpdateWrapper<FtbCertificateUserEntity>()
                .in(FtbCertificateUserEntity::getUserId, userIdList)
                .eq(FtbCertificateUserEntity::getLeaveOut, 1)
                .set(FtbCertificateUserEntity::getLeaveOut, 0)
                .set(FtbCertificateUserEntity::getEnabledMark, 1));

        //标记恢复课程学习记录 和章节学习
        ftbCultivatePositionCourceLearningMapper.update(null, new LambdaUpdateWrapper<FtbCultivatePositionCourceLearning>()
                .in(FtbCultivatePositionCourceLearning::getUserId, userIdList)
                .eq(FtbCultivatePositionCourceLearning::getLeaveOut, 1)
                .set(FtbCultivatePositionCourceLearning::getLeaveOut, 0)
                .set(FtbCultivatePositionCourceLearning::getEnabledMark, 0));

        ftbCultivatePositionCourceChapterLearningMapper.update(null, new LambdaUpdateWrapper<FtbCultivatePositionCourceChapterLearning>()
                .in(FtbCultivatePositionCourceChapterLearning::getUserId, userIdList)
                .eq(FtbCultivatePositionCourceChapterLearning::getLeaveOut, 1)
                .set(FtbCultivatePositionCourceChapterLearning::getLeaveOut, 0)
                .set(FtbCultivatePositionCourceChapterLearning::getEnabledMark, 0));

        //处理顺堂测试
        ftbCultivateChapterTestResultMapper.update(null, new LambdaUpdateWrapper<FtbCultivateChapterTestResult>()
                .in(FtbCultivateChapterTestResult::getUserId, userIdList)
                .eq(FtbCultivateChapterTestResult::getLeaveOut, 1)
                .set(FtbCultivateChapterTestResult::getLeaveOut, 0)
                .set(FtbCultivateChapterTestResult::getEnableMark, 0));
    }


    /**
     * 删除人员
     *
     * @param userIdList 用户集合
     * @param tenantId   租户id
     */
    public void dealDeleteUser(List<String> userIdList, String tenantId) {
        if (CollUtil.isEmpty(userIdList)) {
            return;
        }
        //删除分组中的人
        ftbNoticeUserGroupMembersService.remove(new LambdaQueryWrapper<FtbNoticeUserGroupMembers>()
                .in(FtbNoticeUserGroupMembers::getUserId, userIdList));
        //删除未发送的公告接收人
        ftbNoticeAnnouncementsReceiveService.remove(new LambdaQueryWrapper<FtbNoticeAnnouncementsReceive>()
                .in(FtbNoticeAnnouncementsReceive::getUserId, userIdList)
                .eq(FtbNoticeAnnouncementsReceive::getReadStatus, 1));

        //已读的调整为标记删除
        ftbNoticeAnnouncementsReceiveService.update(new LambdaUpdateWrapper<FtbNoticeAnnouncementsReceive>()
                .set(FtbNoticeAnnouncementsReceive::getEnabledMark, 0)
                .in(FtbNoticeAnnouncementsReceive::getUserId, userIdList)
                .eq(FtbNoticeAnnouncementsReceive::getReadStatus, 2)
                .eq(FtbNoticeAnnouncementsReceive::getEnabledMark, 1))
        ;

        //标记删除考试记录
        ftbCultivateExamUserMapper.update(null, new LambdaUpdateWrapper<FtbCultivateExamUser>()
                .in(FtbCultivateExamUser::getUserId, userIdList)
                .eq(FtbCultivateExamUser::getEnabledMark, 1)
                .set(FtbCultivateExamUser::getLeaveOut, 1)
                .set(FtbCultivateExamUser::getEnabledMark, 0));

        //标记删除鉴定记录
        cultivateIdentifyApplyMapper.update(null, new LambdaUpdateWrapper<CultivateIdentifyApply>()
                .in(CultivateIdentifyApply::getBeIdentifyUserId, userIdList)
                .eq(CultivateIdentifyApply::getDeleteMark, 0)
                .set(CultivateIdentifyApply::getLeaveOut, 1)
                .set(CultivateIdentifyApply::getDeleteMark, 1));


        //标记删除学习地图
        ftbCultivatePromotionMemberNewMapper.update(null, new LambdaUpdateWrapper<FtbCultivatePromotionMemberNew>()
                .in(FtbCultivatePromotionMemberNew::getUserId, userIdList)
                .set(FtbCultivatePromotionMemberNew::getDeleteMark, 1));

        //标记删除证书
        ftbCultivateCertificateUserMapper.update(null, new LambdaUpdateWrapper<FtbCertificateUserEntity>()
                .in(FtbCertificateUserEntity::getUserId, userIdList)
                .eq(FtbCertificateUserEntity::getEnabledMark, 1)
                .set(FtbCertificateUserEntity::getLeaveOut, 1)
                .set(FtbCertificateUserEntity::getEnabledMark, 0));

        //标记删除课程学习记录 和章节学习
        ftbCultivatePositionCourceLearningMapper.update(null, new LambdaUpdateWrapper<FtbCultivatePositionCourceLearning>()
                .in(FtbCultivatePositionCourceLearning::getUserId, userIdList)
                .eq(FtbCultivatePositionCourceLearning::getEnabledMark, 0)
                .set(FtbCultivatePositionCourceLearning::getLeaveOut, 1)
                .set(FtbCultivatePositionCourceLearning::getEnabledMark, 1));

        ftbCultivatePositionCourceChapterLearningMapper.update(null, new LambdaUpdateWrapper<FtbCultivatePositionCourceChapterLearning>()
                .in(FtbCultivatePositionCourceChapterLearning::getUserId, userIdList)
                .eq(FtbCultivatePositionCourceChapterLearning::getEnabledMark, 0)
                .set(FtbCultivatePositionCourceChapterLearning::getLeaveOut, 1)
                .set(FtbCultivatePositionCourceChapterLearning::getEnabledMark, 1));

        //标记删除任务学习记录
        ftbCultivateLearnTaskAssignmentMapper.update(null, new LambdaUpdateWrapper<FtbCultivateLearnTaskAssignment>()
                .in(FtbCultivateLearnTaskAssignment::getUserId, userIdList)
                .eq(FtbCultivateLearnTaskAssignment::getEnableMark, 0)
                .set(FtbCultivateLearnTaskAssignment::getLeaveOut, 1)
                .set(FtbCultivateLearnTaskAssignment::getEnableMark, 1));
        //处理顺堂测试
        ftbCultivateChapterTestResultMapper.update(null, new LambdaUpdateWrapper<FtbCultivateChapterTestResult>()
                .in(FtbCultivateChapterTestResult::getUserId, userIdList)
                .eq(FtbCultivateChapterTestResult::getEnableMark, 0)
                .set(FtbCultivateChapterTestResult::getLeaveOut, 1)
                .set(FtbCultivateChapterTestResult::getEnableMark, 1));

        //删除线下签到用户
        ftbCultivateOfflineTrainMapper.deleteLeaveUser(userIdList);

        //删除通道的成员
        LambdaUpdateWrapper<FtbCultivatePromotionUser> promotionUserLambdaUpdateWrapper = Wrappers.lambdaUpdate();
        promotionUserLambdaUpdateWrapper.in(FtbCultivatePromotionUser::getUserId, userIdList);
        ftbCultivatePromotionUserService.remove(promotionUserLambdaUpdateWrapper);

    }
}
