package com.persagy.dmp.rwd.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.constant.CommonConstant;
import com.persagy.dmp.common.context.AppContext;
import com.persagy.dmp.digital.entity.ObjectRelation;
import com.persagy.dmp.mybatis.helper.DynamicDataSourceHelper;
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;

/**
 * 物理世界关系消息处理
 * @author:linhuili
 * @date:2021/11/23
 */
@Slf4j
@Component
@RabbitListener(queues = DigitalMessageConstant.MESSAGE_DIGITAL_RELATION_QUEUE)
public class DigitalRelationMessageHandler extends AbstractRabbitHandlerTemplate {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private IObjectRelationHistoryService objectRelationHisService;

   /**
     * 物理世界关系数据：消息监听处理
     * @param message 消息体字符串
     * @param channel 通道对象
     * @param vo     消息对象
     */
    @Override
    protected void handler(String message, Channel channel, Message vo) {
        try {
            //接收对象消息
            DigitalManageMessage messageVO = objectMapper.readValue(message, DigitalManageMessage.class);
            ObjectNode objectRelation = messageVO.getNewObj();
            if(objectRelation == null || StrUtil.isEmpty(messageVO.getOperatorType()) || StrUtil.isEmpty(messageVO.getOperatorObj())){
                log.info("对象关系数据消息格式有误：{}"+ messageVO);
                return;
            }
            if(!ObjectRelation.class.getSimpleName().equals(messageVO.getOperatorObj())){
                return;
            }
            log.info("处理对象关系消息：{}", message);
            //处理物理世界关系数据
            handlerDigitalRelationMessage(messageVO,objectRelation);
        }catch (Exception e){
          log.info("物理世界关系消息处理失败：{} "+e.getMessage());
        }
    }

    /**
     * 处理物理世界关系数据
     * @param messageVO
     * @param objectRelation
     * @throws Exception
     */
    private void handlerDigitalRelationMessage(DigitalManageMessage messageVO, ObjectNode objectRelation) throws Exception{
        ObjectRelation objectRelationVO = objectMapper.readValue(objectRelation.toString(), ObjectRelation.class);
        //获取基本参数
        String groupCode = objectRelationVO.getGroupCode();
        String projectId = objectRelationVO.getProjectId();
        //初始化数据源
        initContextInfo(groupCode,projectId,null,null);
        if(DigitalMessageConstant.OPERATE_AFTER_INSERT.equals(messageVO.getOperatorType())){
            //记录新增关系
            objectRelationHisService.insert(objectRelationVO);
        }
        if(DigitalMessageConstant.OPERATE_AFTER_UPDATE.equals(messageVO.getOperatorType())){
            //记录关系修改
            objectRelationHisService.update(objectRelationVO);
        }
        if(DigitalMessageConstant.OPERATE_AFTER_DELETE.equals(messageVO.getOperatorType())){
            //记录关系删除
            objectRelationHisService.update(objectRelationVO);
        }
    }

     /**
     * 初始化上下文，切换数据源
     * @param groupCode
     * @param projectId
     * @param appId
     * @param userId
     */
    private void initContextInfo(String groupCode,String projectId,String appId,String userId) {
        AppContext.getContext().setGroupCode(groupCode);
        AppContext.getContext().setProjectId(projectId);
        // 无用户时，默认为默认系统用户
        if(StrUtil.isBlank(userId)) {
            userId = CommonConstant.DEFAULT_ID;
        }
        AppContext.getContext().setAccountId(userId);
        DynamicDataSourceHelper.loadDataSource();
    }

}

