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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.persagy.dmp.digital.entity.ObjectDigital;
import com.persagy.dmp.rwd.digital.config.DigitalRabbitConfig;
import com.persagy.dmp.rwd.digital.service.IObjectDigitalService;
import com.persagy.dmp.amqp.handler.AbstractRabbitHandlerTemplate;
import com.persagy.dmp.common.constant.CommonConstant;
import com.persagy.dmp.common.context.AppContext;
import com.persagy.dmp.common.exception.BusinessException;
import com.persagy.dmp.mybatis.helper.DynamicDataSourceHelper;
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.IOException;

/**
 * 项目消息消费
 * @author Charlie Yu
 * @date 2021-06-25
 */
@Slf4j
@Component
@RabbitListener(queues = DigitalRabbitConfig.PROJECT_QUEUE)
public class ProjectMessageHandler extends AbstractRabbitHandlerTemplate {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private IObjectDigitalService digitalService;

    /**
     * 消费
     * @param message 消息体字符串
     * @param channel 通道对象
     * @param vo     消息对象
     */
    @Override
    protected void handler(String message, Channel channel, Message vo) {
        try {
            ProjectMessageVO msgVO = objectMapper.readValue(message, ProjectMessageVO.class);
            initContextInfo(msgVO);
            ObjectDigital project = msgVO.toObjectDigital();
            // 幂等处理 - 检查是否已经存在
            ObjectDigital dbVO = digitalService.load(project.getId());
            if(dbVO == null) {
                digitalService.insert(CollUtil.newArrayList(project));
            } else {
                digitalService.update(CollUtil.newArrayList(project));
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new BusinessException(e.getMessage(), e);
        }
    }

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