package com.persagy.dmp.rwd.basic.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.persagy.dmp.amqp.handler.RabbitMessageSender;
import com.persagy.dmp.basic.model.DigitalManageMessage;
import com.persagy.dmp.basic.utils.JsonNodeUtils;
import com.persagy.dmp.common.exception.BusinessException;
import com.persagy.dmp.common.model.entity.BaseEntity;
import com.persagy.dmp.basic.constant.DigitalMessageConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 数据孪生消息发送助手
 * @author Charlie Yu
 * @date 2021-06-25
 */
@Component
@Slf4j
public class DigitalMessageHelper {

    @Autowired
    private RabbitMessageSender messageSender;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 发送消息
     * @param operator 操作类型
     * @param oldVO 原数据
     * @param newVO 现数据
     * @param syncFlag 同步消息标识
     */
    public void sendMessage(String operator, BaseEntity oldVO, BaseEntity newVO, boolean syncFlag) {
        // 将扩展属性提取到外部
        ObjectNode oldNode = JsonNodeUtils.toObjectNode(oldVO, "infos", null);
        ObjectNode newNode = JsonNodeUtils.toObjectNode(newVO, "infos", null);
        // 组装消息体
        DigitalManageMessage message = new DigitalManageMessage();
        message.setOperatorType(operator);
        message.setOperatorObj(newVO.getClass().getSimpleName());
        message.setOldObj(oldNode);
        message.setNewObj(newNode);
        // 同步消息
        try {
            if(syncFlag) {
                messageSender.sendAndReceive(DigitalMessageConstant.MESSAGE_EXCHANGE,
                        DigitalMessageConstant.MESSAGE_ROUTING,
                        objectMapper.writeValueAsString(message));
            } else {
                // 异步消息
                    messageSender.send(DigitalMessageConstant.MESSAGE_EXCHANGE,
                            DigitalMessageConstant.MESSAGE_ROUTING,
                            objectMapper.writeValueAsString(message));
            }
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("消息格式有误！");
        }
    }
}
