package com.zjty.tynotes.sms.service.impl;

import com.zjty.tynotes.sms.service.MessageTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Service;

/**
 * @author zjm
 */
@Slf4j
@Service
public class MessageTemplateServiceImpl implements MessageTemplateService {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private SimpUserRegistry userRegistry;
    @Override
    public void beingPushed(String receive,String destination,String payload) {

        this.sendToUser(receive, destination, payload);
    }

    @Override
    public void noticePushed(String receive, String payload) {
        this.sendToUser(receive, "/topic/notice", payload);
    }

    /**
     * 给指定用户发送消息，并处理接收者不在线的情况
     *
     * @param receiver 消息接收者
     * @param destination 目的地
     * @param payload 消息正文
     */
    private void sendToUser( String receiver, String destination, String payload){
        SimpUser simpUser = userRegistry.getUser(receiver);
        if(simpUser != null && StringUtils.isNoneBlank(simpUser.getName())){
            messagingTemplate.convertAndSendToUser(receiver, destination, payload);
            log.info("给{}推送成功", simpUser.getName());

        }else {
            log.info("用户{}没上线",receiver);
        }

    }

}
