package com.sifang.modules.sys.init;

import com.alibaba.druid.wall.WallFilter;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.sifang.modules.sys.common.global.Global;

import java.sql.Connection;

//@Configuration
public class ActiveRecordPluginConfig {

   // @Bean
    public ActiveRecordPlugin initActiveRecordPlugin() {

        String dbNames = Global.getConfig("db.config.name");
        if(StrKit.isBlank(dbNames)){
            throw new RuntimeException(" Init ActiveRecordPlugin Error! [dbNameConfig empty] ");
        }

        ActiveRecordPlugin retArp = null;
        String[] dbNameArr = dbNames.split(",");
        boolean hasMain = false;
        for(String dbName : dbNameArr){
            String userName = Global.getConfig("jdbc.username." + dbName);
            String password = Global.getConfig("jdbc.password." + dbName);
            String driverClassUrl = Global.getConfig("jdbc.url." + dbName);
            DruidPlugin druidPlugin = new DruidPlugin(driverClassUrl, userName, password);
            // 加强数据库安全
            WallFilter wallFilter = new WallFilter();
            wallFilter.setDbType("mysql");
            druidPlugin.addFilter(wallFilter);
            // 添加 StatFilter 才会有统计数据
            // druidPlugin.addFilter(new StatFilter());
            // 必须手动调用start
            druidPlugin.start();

            ActiveRecordPlugin arp = new ActiveRecordPlugin(dbName, druidPlugin);
            arp.setTransactionLevel(Connection.TRANSACTION_READ_COMMITTED);
            arp.setShowSql(true);
            // 必须手动调用start
            /*if(!hasMain) {
            	arp.start();
            	hasMain = true;
            }*/
            arp.start();
            if(retArp == null){
                retArp = arp;
            }
        }
        return retArp;
    }

}