package com.usoftchina.bi.server.aspect;

import com.usoftchina.bi.core.jdbc.DynamicDataSourceContextHolder;
import com.usoftchina.bi.server.dao.dataSource.DataColumnMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.usoftchina.bi.server.model.bo.ToSql;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description 动态数据源通知
 * @Date 2018-06-23
 */
@Aspect
@Order(-1)//保证在@Transactional之前执行
@Component
public class DynamicDattaSourceAspect {

    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    DataColumnMapper dataColumnMapper;

    private static final Logger logger = LoggerFactory.getLogger(DynamicDattaSourceAspect.class);

    //改变数据源
    @Before("@annotation(com.usoftchina.bi.server.model.pojo.annotation.TargetDataSource)")
    public void changeDataSource(JoinPoint joinPoint) {
        Object[] arr = joinPoint.getArgs();
        String joinStr = null;
        ToSql toSql = new ToSql();
        try {
            joinStr = objectMapper.writeValueAsString(arr[1]);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        try {
            toSql = objectMapper.readValue(joinStr, ToSql.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        int baseId = toSql.getId();

        if (!DynamicDataSourceContextHolder.isContainsDataSource(baseId)) {
            logger.info("数据源 -> {} 不存在,使用默认的数据源 -> {}",baseId, joinPoint.getSignature());
        } else {
            logger.info("使用数据源：{}", baseId);
            DynamicDataSourceContextHolder.setDataSourceType(baseId);
        }
    }

    @After("@annotation(com.usoftchina.bi.server.model.pojo.annotation.TargetDataSource)")
    public void clearDataSource(JoinPoint joinPoint) {
        logger.info("清除数据源!");
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}
