package jnpf.cultivate.v2.util;

import jnpf.constants.MessageTopicConstants;
import jnpf.cultivate.utils.CultivateIdentifyIMUtils;
import jnpf.entity.cultivate.CultivateIdentifyApply;
import jnpf.entity.cultivate.TeachingRecord;
import jnpf.enums.cultivate.v2.mq.CultivateTypeEnum;
import jnpf.model.cultivate.po.exam.FtbCultivateExamUser;
import jnpf.model.cultivate.v2.course.vo.app.V2ChapterStudyVo;
import jnpf.model.cultivate.v2.enums.PositionBusinessSourceEnum;
import jnpf.model.cultivate.v2.mq.CultivateMqDTO;
import jnpf.util.UserProvider;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 培训模块发送mq工具类
 */
@Component
public class CultivateMqSendUtil {

    @Autowired
    private RocketMQTemplate rocketMqTemplate;

    @Autowired
    private CultivateIdentifyIMUtils cultivateIdentifyIMUtils;

    /**
     * 发送课程完成消息
     *
     * @param req      章节学习参数
     * @param userId   用户 ID
     * @param tenantId 租户 ID
     */
    public void sendCourseCompletionMessage(V2ChapterStudyVo req, String userId, String tenantId) {
        Map<String, Object> params = new HashMap<>();
        params.put(CultivateMqDTO.POST_ID, req.getPostId());
        params.put(CultivateMqDTO.GRADE_ID, req.getGradeId());
        params.put("chapterId", req.getChapterId());
        CultivateMqDTO courseEventDTO = CultivateMqDTO.builder()
                .tenantId(tenantId)
                .userId(userId)
                .businessSource(req.getBusinessSource())
                .businessSourceId(req.getBusinessSourceId())
                .type(CultivateTypeEnum.COURSE)
                .businessId(req.getCourseId())
                .status(1)
                .params(params)
                .build();

        // 构建带 Tag 和 Key 的消息
        Message<CultivateMqDTO> message = MessageBuilder
                .withPayload(courseEventDTO)
                .setHeader("TAGS", tenantId)  // 课程完成 Tag
                .setHeader("KEYS", tenantId + "_" + userId)  // 唯一 Key: userId_courseId
                .build();

        rocketMqTemplate.syncSend(MessageTopicConstants.CULTIVATE_TOPIC, message);
    }

    /**
     * 发送课程完成消息
     *
     * @param apply 章节学习参数
     */
    public void sendIdentityCompletionMessage(CultivateIdentifyApply apply, String identityId) {
        // 判断鉴定结果是否告知被鉴定人（0-告知，1-不告知）
        if (apply.getAppraisalResults() != null && apply.getAppraisalResults().equals(0)) {
            noticeAppMessage(apply);
        }
        //鉴定来源 (0-手动发起，1-课程学习鉴定，2-岗位学习鉴定，3-本人申请，4-任务鉴定)
        if (apply.getSource().equals(0) || apply.getSource().equals(1) || apply.getSource().equals(3)) {
            return;
        }
        
        
        String tenantId = UserProvider.getUser().getTenantId();
        Map<String, Object> params = new HashMap<>();
        params.put("userIdentifyId", apply.getId());
        if (!apply.getStatus().equals(0)) {
            params.put("userIdentifyStatus", apply.getResult());
        }
        PositionBusinessSourceEnum businessSource = null;
        if (apply.getSource().equals(2)) {
            businessSource = PositionBusinessSourceEnum.POST_LEARNING;
        } else if (apply.getSource().equals(4)) {
            businessSource = PositionBusinessSourceEnum.TASK_LEARNING;
        }
        CultivateMqDTO courseEventDTO = CultivateMqDTO.builder()
                .tenantId(tenantId)
                .userId(apply.getBeIdentifyUserId())
                .businessSource(businessSource)
                .businessSourceId(apply.getSourceId())
                .type(CultivateTypeEnum.IDENTITY)
                .businessId(identityId)
                .status(apply.getStatus())
                .params(params)
                .build();

        // 构建带 Tag 和 Key 的消息
        Message<CultivateMqDTO> message = MessageBuilder
                .withPayload(courseEventDTO)
                .setHeader("TAGS", tenantId)  // 鉴定完成 Tag
                .setHeader("KEYS", tenantId + "_" + apply.getBeIdentifyUserId())  // 唯一 Key
                .build();

        rocketMqTemplate.syncSend(MessageTopicConstants.CULTIVATE_TOPIC, message);
    }

    private void noticeAppMessage(CultivateIdentifyApply apply) {
        cultivateIdentifyIMUtils.sendMsg(apply,UserProvider.getUser().getTenantId());
    }

    public void sendCompleteTeachingMessage(TeachingRecord teachingRecord) {
        String tenantId = UserProvider.getUser().getTenantId();
        Map<String, Object> params = new HashMap<>();
        PositionBusinessSourceEnum businessSource = null;

        CultivateMqDTO courseEventDTO = CultivateMqDTO.builder()
                .tenantId(tenantId)
                .userId(teachingRecord.getUserId())
                .businessSource(businessSource)
                .businessSourceId("")
                .type(CultivateTypeEnum.PRACTICE)
                .businessId(teachingRecord.getSkillId())
                .status(1)
                .params(params)
                .build();

        // 构建带 Tag 和 Key 的消息
        Message<CultivateMqDTO> message = MessageBuilder
                .withPayload(courseEventDTO)
                .setHeader("TAGS", tenantId)  // 实训完成 Tag
                .setHeader("KEYS", tenantId + "_" + teachingRecord.getUserId())  // 唯一 Key
                .build();

        rocketMqTemplate.syncSend(MessageTopicConstants.CULTIVATE_TOPIC, message);
    }

    public void sendExamMessage(FtbCultivateExamUser examUser) {
        String tenantId = UserProvider.getUser().getTenantId();
        Map<String, Object> params = new HashMap<>();
        params.put("userExamId", examUser.getId());
        params.put("userExamStatus", examUser.getStatus());
        PositionBusinessSourceEnum businessSource = null;

        CultivateMqDTO courseEventDTO = CultivateMqDTO.builder()
                .tenantId(tenantId)
                .userId(examUser.getUserId())
                .businessSource(businessSource)
                .businessSourceId("")
                .type(CultivateTypeEnum.EXAM)
                .businessId(examUser.getExamId())
                .status(examUser.getStatus())
                .params(params)
                .build();

        // 构建带 Tag 和 Key 的消息
        Message<CultivateMqDTO> message = MessageBuilder
                .withPayload(courseEventDTO)
                .setHeader("TAGS", tenantId)  // 考试完成 Tag
                .setHeader("KEYS", tenantId + "_" + examUser.getUserId())  // 唯一 Key
                .build();

        rocketMqTemplate.syncSend(MessageTopicConstants.CULTIVATE_TOPIC, message);
    }


}