package com.artfess.report.bigScreen.manager.impl;

import com.artfess.base.dao.CommonDao;
import com.artfess.base.enums.ResponseErrorEnums;
import com.artfess.base.exception.BaseException;
import com.artfess.base.interceptor.MasterSlaveAutoRoutingPlugin;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.util.AppUtil;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.StringUtil;
import com.artfess.report.bigScreen.dao.BladeVisualConfigDao;
import com.artfess.report.bigScreen.manager.BladeVisualConfigManager;
import com.artfess.report.bigScreen.model.BladeVisualConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 可视化配置表 服务实现类
 *
 * @company 阿特菲斯
 * @author 向贞好
 * @since 2021-07-12
 */
@Service
public class BladeVisualConfigManagerImpl extends BaseManagerImpl<BladeVisualConfigDao, BladeVisualConfig> implements BladeVisualConfigManager {

    @Resource
    CommonDao commonDao;

    @Override
    public List<Map<String, Object>> query(String sql) {
        Assert.notNull(sql, "sql can not be empty.");
        Map<String, Object> map = new HashMap<>();
        map.put("sql", sql);
        // 当前处于切换到外部数据源状态时,使用新事务
        if (MasterSlaveAutoRoutingPlugin.getInExternalDatasource()) {
            PlatformTransactionManager transactionManager = (PlatformTransactionManager) AppUtil.getBean(TransactionManager.class);
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            // 事物隔离级别，开启新事务，这样会比较安全些。
            TransactionStatus status = transactionManager.getTransaction(def);
            // 获得事务状态
            try { // 逻辑代码，可以写上你的逻辑处理代码
                List<Map<String, Object>> result = commonDao.query(map);
                transactionManager.commit(status);
                return result;
            } catch (Exception e) {
                transactionManager.rollback(status);
                throw new BaseException(ResponseErrorEnums.DATABASE_ERROR, e);
            }
        } else {
            return commonDao.query(map);
        }
    }

}
