package com.fs.app.mq;

import com.alibaba.fastjson.JSON;
import com.fs.common.utils.StringUtils;
import com.fs.course.mq.CourseRepeatByProjectMqConstants;
import com.fs.course.param.FsUserCourseVideoAddKfUParam;
import com.fs.course.service.ICourseRepeatByProjectService;
import com.fs.course.vo.CourseRepeatByProjectMqMessage;
import com.fs.his.domain.FsUser;
import com.fs.his.mapper.FsUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@AllArgsConstructor
@RocketMQMessageListener(
        topic = CourseRepeatByProjectMqConstants.TOPIC,
        consumerGroup = CourseRepeatByProjectMqConstants.CONSUMER_GROUP)
public class RocketMQConsumerCourseRepeatByProjectService implements RocketMQListener<String> {

    private final ICourseRepeatByProjectService courseRepeatByProjectService;
    private final FsUserMapper fsUserMapper;

    @Override
    public void onMessage(String message) {
        if (StringUtils.isEmpty(message)) {
            return;
        }
        try {
            CourseRepeatByProjectMqMessage mqMessage = JSON.parseObject(message, CourseRepeatByProjectMqMessage.class);
            if (mqMessage == null || mqMessage.getParam() == null) {
                return;
            }
            FsUserCourseVideoAddKfUParam param = mqMessage.getParam();
            if (param.getUserId() == null) {
                return;
            }
            FsUser fsUser = fsUserMapper.selectFsUserByUserId(param.getUserId());
            if (fsUser == null) {
                log.warn("看课重粉 MQ 消费：用户不存在 userId={}", param.getUserId());
                return;
            }
            courseRepeatByProjectService.checkAndMarkRepeatByProject(param, fsUser);
        } catch (Exception e) {
            log.error("看课重粉 MQ 消费失败 message={}", message, e);
            throw e;
        }
    }
}
