package com.iformall.mq;

import com.iformall.domain.po.msg.BaseMsg;
import com.iformall.enums.EnumMsgRecordDomain;
import com.iformall.enums.EnumMsgRecordStatus;
import com.iformall.mapper.WxMsgRecordMapper;
import com.iformall.service.UserService;
import com.iformall.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

/**
 * 消息消费入口
 */
@Service
public class AmqpMsgConsumer {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WxMsgRecordMapper wxMsgRecordMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    @Autowired
    private UserService userService;

    public void doMessage(String message) {
        log.info("received amqp message: {}", message);
        BaseMsg baseMsg = null;

        try {
            baseMsg = (BaseMsg)JsonUtil.readValue(message,BaseMsg.class);

            if(EnumMsgRecordDomain.A.getCode().equals(baseMsg.getDomain())) {
                messagingTemplate.convertAndSend("/topic/" + baseMsg.getTenantId() + "A", message);
            }else if(EnumMsgRecordDomain.B.getCode().equals(baseMsg.getDomain())) {
                messagingTemplate.convertAndSend("/topic/" + baseMsg.getTenantId() + "B", message);
            }else if(EnumMsgRecordDomain.C.getCode().equals(baseMsg.getDomain())) {
                messagingTemplate.convertAndSend("/topic/" + baseMsg.getTenantId() + "C",message);
            }else if(EnumMsgRecordDomain.USER.getCode().equals(baseMsg.getDomain())) {
                // 方式1
                messagingTemplate.convertAndSendToUser(baseMsg.getTenantId()+baseMsg.getReceiver(), "/message", message);
                // 方式2
//                String userId = userService.getSessionId(name);
//                amqpTemplate.convertAndSend("", Constance.queue_pre+userId, message);
            }

            baseMsg.setMsgStatus(EnumMsgRecordStatus.CONSUME_SUCC.getCode());
            wxMsgRecordMapper.updateByBaseMsg(baseMsg);
        }catch (Exception e){
            log.error("consum received error: {}", e);
            baseMsg.setStatusMessage(e.getMessage());
            baseMsg.setMsgStatus(EnumMsgRecordStatus.CONSUME_FAIL.getCode());
            wxMsgRecordMapper.updateByBaseMsg(baseMsg);
        }

    }
}
