package com.webchat.service.queue;

import com.webchat.common.enums.ChatMessageTypeEnum;
import com.webchat.common.enums.RedisKeyEnum;
import com.webchat.common.enums.RedisMessageChannelTopicEnum;
import com.webchat.common.util.JsonUtil;
import com.webchat.domain.vo.request.mess.ChatMessageRequestVO;
import com.webchat.repository.dao.IArticleDAO;
import com.webchat.service.ChatMessService;
import com.webchat.service.FriendService;
import com.webchat.service.listener.RedisMessageSender;
import com.webchat.service.queue.dto.ArticleDelayConsumeMessageDTO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Set;

/**
 * @author 77
 * @date 2024/11/13 00:01
 */
@Component
public class ArticlePublishQueue extends AbstractRedisQueue<ArticleDelayConsumeMessageDTO> {

    @Autowired
    private FriendService friendService;
    @Autowired
    private ChatMessService chatMessService;
    @Autowired
    private IArticleDAO articleDAO;
    @Autowired
    private RedisMessageSender redisMessageSender;

    @PostConstruct
    public void initBean() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArticlePublishQueue.super.schedule();
            }
        }).start();
    }

    @Override
    protected ArticleDelayConsumeMessageDTO convert(String s) {
        if (StringUtils.isBlank(s)) {
            return null;
        }
        return JsonUtil.fromJson(s, ArticleDelayConsumeMessageDTO.class);
    }

    @Override
    protected String getQueueName() {
        return RedisKeyEnum.QUEUE_ARTICLE_PUBLISH_MESSAGE.getKey();
    }

    @Override
    protected void receive(ArticleDelayConsumeMessageDTO data) {
        if (data == null) {
            return;
        }
        // 1. 拿公众号
        String publicAccount = data.getPublicAccount();
        // 2. 获取文章信息
        Long articleId = data.getArticleId();
        // 3. 走redis拿公众号下所有订阅用户
        Set<String> subscribeUsers = friendService.listSubscribeFriendIds(publicAccount);
        if (CollectionUtils.isEmpty(subscribeUsers)) {
            return;
        }
        // 4. 处理离线场景推文
        this.doExecWriteData(articleId, publicAccount, subscribeUsers);
        // 5. 发布公众号推文消息到PUSH_ARTICLE Topic，在RedisMessageListener中完成推送（分布式websocket）
        redisMessageSender.sendMessage(RedisMessageChannelTopicEnum.PUSH_ARTICLE.getChannel(), JsonUtil.toJsonString(data));

    }

    public void doExecWriteData(Long articleId, String publicAccount, Set<String> receiverIds) {
        // 更新文章推送状态
        articleDAO.updatePushedStatus(articleId);
        // 推文数据写库
        for (String userId : receiverIds) {
            ChatMessageRequestVO messVo = new ChatMessageRequestVO();
            messVo.setType(ChatMessageTypeEnum.PUBLIC_ACCOUNT_ARTICLE.getType());
            messVo.setMessage(String.valueOf(articleId));
            messVo.setSenderId(publicAccount);
            messVo.setReceiverId(userId);
            chatMessService.sendMess(messVo);
        }
    }

    @Override
    protected void error(ArticleDelayConsumeMessageDTO data, Exception ex) {

    }
}
