package com.rongwei.safecommon.config;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.core.parser.ISqlParserFilter;
import com.baomidou.mybatisplus.core.parser.SqlParserHelper;
import com.rongwei.rwcommonconfig.config.interceptor.SaasPaginationInterceptor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by duyisong on 17/5/28.
 */
@EnableTransactionManagement
@Configuration
@MapperScan("com.rongwei.*.*.dao")
public class MybatisConfig {

//    @Autowired
//    private RedisService redisService;

//    /**
//     * 自定义查询sql多数据库适配
//     * @return
//     */
//    @Bean
//    public QuerySqlAdaptationInterceptor querySqlAdaptationInterceptor(){
//        QuerySqlAdaptationInterceptor sqlAdaptation = new QuerySqlAdaptationInterceptor();
//        return sqlAdaptation;
//    }

    /*
     * 分页插件，自动识别数据库类型
     * 多租户，请参考官网【插件扩展】
     */
    @Bean
    public SaasPaginationInterceptor paginationInterceptor() {
        SaasPaginationInterceptor paginationInterceptor = new SaasPaginationInterceptor();
        /*
         * 【测试多租户】 SQL 解析处理拦截器<br>
         * 这里固定写成住户 1 实际情况你可以从cookie读取，因此数据看不到 【 麻花藤 】 这条记录（ 注意观察 SQL ）<br>
         */
        List<ISqlParser> sqlParserList = new ArrayList<>();
//        TenantSqlParser tenantSqlParser = new TenantSqlParser();
//        tenantSqlParser.setTenantHandler(new TenantHandler() {
//            @Override
//            public Expression getTenantId() {
//                String tenantId = null;
//                String token = ThreadLocalResource.token.get();
//                SysUserVo currUser = null;
//                if(StringUtils.isNotEmpty(token)){
//                    currUser = redisService.getLoginUser(token);
//                }
//                if(currUser != null && currUser.getTenantDo() != null){
//                    tenantId = currUser.getTenantDo().getId();
//                }
//
//                return new StringValue(tenantId);
//            }
//
//            @Override
//            public String getTenantIdColumn() {
//                return "TENANTID";
//            }
//
//            @Override
//            public boolean doTableFilter(String tableName) {
//                // 这里可以判断是否过滤表,true表示过滤、false不过滤
//                /*
//                if ("user".equals(tableName)) {
//                    return true;
//                }*/
//                return true;
//            }
//        });
//        sqlParserList.add(tenantSqlParser);
        paginationInterceptor.setSqlParserList(sqlParserList);
        paginationInterceptor.setSqlParserFilter(new ISqlParserFilter() {
            @Override
            public boolean doFilter(MetaObject metaObject) {
                MappedStatement ms = SqlParserHelper.getMappedStatement(metaObject);
                // 过滤自定义查询此时无租户信息约束【 麻花藤 】出现
                if ("com.rongwei.rwadmincommon.system.dao.getAll".equals(ms.getId())) {
                    return true;
                }
                return false;
            }
        });
        paginationInterceptor.setLimit(2000);
        return paginationInterceptor;
    }

//    /**
//     * 打印 sql
//     */
//    @Bean
//    public PerformanceInterceptor performanceInterceptor() {
//        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
//        //格式化sql语句
//        Properties properties = new Properties();
//        properties.setProperty("format", "true");
//        performanceInterceptor.setProperties(properties);
//        return performanceInterceptor;
//    }

    /*@Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        log.info("[config] 注册 tkMtBatis");
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.rongwei.rwadmin.system.dao");
        Properties properties = new Properties();
        properties.setProperty("markerInterface", "com.rongwei.rwadmin.common.mapper.BaseDao");
        mapperScannerConfigurer.setProperties(properties);
        return mapperScannerConfigurer;
    }

    @Bean
    public PageHelper pageHelper(DataSource dataSource) {
        log.info("[config] 注册 MyBatis分页插件PageHelper");
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        pageHelper.setProperties(p);
        return pageHelper;
    }*/


    // 配置sqlSessionFactory
    /*@Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource
            ,QuerySqlAdaptationInterceptor sqlAdaptation,PaginationInterceptor paginationInterceptor) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        if(StringUtils.isNotBlank(typeAliasesPackage)){
            bean.setTypeAliasesPackage(typeAliasesPackage);
        }

        // 自定义的sql日志拦截器
        Interceptor sqlLogInterceptor = new SqlLogInterceptor();
        Interceptor[] plugins =  new Interceptor[]{ sqlLogInterceptor};
        bean.setPlugins(plugins);
        try {
            bean.setMapperLocations(resolver.getResources(xmlLocation));
            return bean.getObject();
        } catch (Exception e) {

            throw new RuntimeException(e);
        }
    }*/

}