package cn.quantgroup.xyqb.event;

import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.webchat.WechatEventMsg;
import cn.quantgroup.xyqb.repository.IUserRepository;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 微信绑定关系变动。通知某系统
 */
@Slf4j
@Component
public class NotifyWechatBindEventListener implements ApplicationListener<WechatBindEvent> {

    @Resource
    private RabbitTemplate wechatRabbitTemplate;
    @Resource
    private IUserRepository userRepository;

    @Override
    public void onApplicationEvent(WechatBindEvent event) {
        WechatEventMsg wechatEventMsg = event.getWechatEventMsg();
        if (wechatEventMsg.getUserId() == null) {
            log.info("微信绑定数据，没有用户 ID 信息,openId:{}", wechatEventMsg.getOpenId());
            return;
        }
        User user = userRepository.findById(wechatEventMsg.getUserId());
        if (user == null) {
            log.info("微信绑定数据，没有用户信息,openId:{},userId:{}", wechatEventMsg.getOpenId(), wechatEventMsg.getUserId());
            return;
        }
        String uuid = user.getUuid();

        Map<String, Object> msg = Maps.newHashMapWithExpectedSize(3);
        msg.put("uuid", uuid);
        msg.put("openId", wechatEventMsg.getOpenId());
        msg.put("timestamp", event.getTimestamp());
        wechatRabbitTemplate.convertAndSend(msg);
    }
}
