package com.persagy.dmp.rwd.version.handler;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.persagy.dmp.amqp.handler.AbstractRabbitHandlerTemplate;
import com.persagy.dmp.basic.constant.DigitalMessageConstant;
import com.persagy.dmp.basic.model.DigitalManageMessage;
import com.persagy.dmp.common.exception.BusinessException;
import com.persagy.dmp.digital.entity.ObjectRelation;
import com.persagy.dmp.rwd.version.service.IObjectRelationHistoryService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.DataInput;

/**
 * 历史关系记录消息处理
 * @author:linhuili
 * @date:2021/11/15
 */
@Slf4j
@Component
@RabbitListener
public class ObjectRelationHistoryMessageHandler extends AbstractRabbitHandlerTemplate {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private IObjectRelationHistoryService objectRelationHisService;

    @Override
    protected void handler(String message, Channel channel, Message vo) {
        try {
            log.info("对象关系历史记录-接收对象关系消息：{}", message);
            //接收对象消息
            DigitalManageMessage messageVO = objectMapper.readValue(message, DigitalManageMessage.class);
            ObjectNode objectRelation = messageVO.getNewObj();
            if(objectRelation == null || StrUtil.isEmpty(messageVO.getOperatorType())){
                log.info("对象关系消息格式有误：{}"+ messageVO);
            }
            if(!ObjectRelation.class.getSimpleName().equals(messageVO.getOperatorObj())){
                return;
            }
            ObjectRelation objectRelationVO = objectMapper.readValue(objectRelation.toString(), ObjectRelation.class);
            //新增对象关系，历史记录
            if(DigitalMessageConstant.OPERATE_AFTER_INSERT.equals(messageVO.getOperatorType())){
                objectRelationHisService.insert(objectRelationVO);
            }
            //修改对象关系，历史记录
            if(DigitalMessageConstant.OPERATE_AFTER_INSERT.equals(messageVO.getOperatorType())){
                objectRelationHisService.update(objectRelationVO);
            }
            //删除对象关系，历史记录
            if(DigitalMessageConstant.OPERATE_AFTER_INSERT.equals(messageVO.getOperatorType())){
                objectRelationHisService.delete(objectRelationVO);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException(e.getMessage(), e);
        }

    }
}
