package net.wicp.tams.app.duckula.controller.config;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;

import net.wicp.tams.common.mybatis.intercepts.SqlInterceptor;

@Configuration
@MapperScan("net.wicp.tams.app.duckula.controller.dao.*")
public class MybatisPlusConfig {

	@Bean
	public PaginationInterceptor paginationInterceptor() {
		PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
		// 设置请求的页面大于最大页后操作， true调回到首页，false 继续请求 默认false
		// paginationInterceptor.setOverflow(false);
		// 设置最大单页限制数量，默认 500 条，-1 不受限制
		// paginationInterceptor.setLimit(500);
		// 开启 count 的 join 优化,只针对部分 left join
		paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
		return paginationInterceptor;
	}

	@Autowired
	private DataSource datasource;

	/***
	 * 
	 * @return
	 */
	@Bean
	public IdentifierGenerator identifierGenerator() {
		return new DefaultIdentifierGenerator();
	}

	@Bean
	@Primary
	public SqlSessionFactory mybatisSqlSessionFactory() throws Exception {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(datasource);
//		sqlSessionFactoryBean.setTypeAliasesPackage("net.wicp.tams.app.duckula.controller.bean.models");
//		if (StringUtil.isNotNull(Conf.get("common.jdbc.mybatis.mapperLocations"))) {
//			sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
//					.getResources(Conf.get("common.jdbc.mybatis.mapperLocations")));
//		}
		MybatisConfiguration configuration = new MybatisConfiguration();
		configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
		configuration.setJdbcTypeForNull(JdbcType.NULL);
		// 设置主键，不设置会导致 nullpoint
		DbConfig dbConfig = new GlobalConfig.DbConfig();
		dbConfig.setIdType(IdType.AUTO);
		GlobalConfig setDbConfig = new GlobalConfig().setDbConfig(dbConfig);

		configuration.setGlobalConfig(setDbConfig);
		sqlSessionFactoryBean.setConfiguration(configuration);
		sqlSessionFactoryBean.setTypeAliasesPackage("net.wicp.tams.app.duckula.controller.bean.models");
		sqlSessionFactoryBean.setMapperLocations(resolveMapperLocations());
		sqlSessionFactoryBean.setPlugins(new SqlInterceptor());
		sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
		return sqlSessionFactoryBean.getObject();
	}

	public Resource[] resolveMapperLocations() {
		ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
		List<String> mapperLocations = new ArrayList<>();
		mapperLocations.add("classpath:mybatis/primary/sqlmap/*.xml");
//		mapperLocations.add("classpath*:com/pab/cc/ces/mapper/*Mapper*.xml");
//		mapperLocations.add("classpath*:com/pab/cc/ams/mapper/*Mapper*.xml");
		List<Resource> resources = new ArrayList();
		if (mapperLocations != null) {
			for (String mapperLocation : mapperLocations) {
				try {
					Resource[] mappers = resourceResolver.getResources(mapperLocation);
					resources.addAll(Arrays.asList(mappers));
				} catch (IOException e) {
					// ignore
				}
			}
		}
		return resources.toArray(new Resource[resources.size()]);
	}
}