package com.mortals.flowable.base.framework.config;

import com.mortals.framework.springcloud.config.SpringBootVFS;
import com.mortals.framework.springcloud.config.mybatis.AbstractMybatisConfiguration;
import com.mortals.framework.thirty.mybatis.MortalsPagePlugin;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

@Configuration
//@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisConfiguration extends AbstractMybatisConfiguration {
    private static Log logger = LogFactory.getLog(MybatisConfiguration.class);

    // 配置类型别名
    @Value("${spring.application.name}")
    private String name;
    // 配置类型别名
    @Value("${mybatis.root-path}")
    private String rootPath;

    // 配置类型别名
    @Value("${mybatis.type-aliases-package}")
    private String typeAliasesPackage;

    // 配置mapper的扫描，找到所有的mapper.xml映射文件
    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;

    // 加载全局的配置文件
    @Value("${mybatis.config-location}")
    private String configLocation;


    // 提供SqlSeesion
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("dataSource") DataSource dataSource) {

        try {
            this.logger.info("开始初始化SqlSessionFactory...");
            VFS.addImplClass(SpringBootVFS.class);
            SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
            sessionFactoryBean.setDataSource(dataSource);
            sessionFactoryBean.setTypeAliasesPackage(getTypeAliasesPackage());
            sessionFactoryBean.setMapperLocations(this.resolveMapperLocations());
            String configLocation = this.getMybatisConfig();
            if (StringUtils.isNotEmpty(configLocation)) {
                this.logger.info("MyBatis运用配置文件-->" + configLocation);
                Resource[] configLocations = (new PathMatchingResourcePatternResolver()).getResources(configLocation);
                if (configLocations != null && configLocations.length > 0) {
                    sessionFactoryBean.setConfigLocation(configLocations[0]);
                }
            } else {
                this.logger.info("MyBatis使用默认配置");
                org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
                configuration.setCacheEnabled(false);
                configuration.setLazyLoadingEnabled(false);
                configuration.setMultipleResultSetsEnabled(true);
                configuration.setUseColumnLabel(true);
                configuration.setUseGeneratedKeys(false);
                configuration.setDefaultExecutorType(ExecutorType.REUSE);
                sessionFactoryBean.setConfiguration(configuration);
                MortalsPagePlugin pagePlugin = new MortalsPagePlugin();
                Properties pageProp = new Properties();
                pageProp.put("dialect", "MySql");
                pagePlugin.setProperties(pageProp);
                sessionFactoryBean.setPlugins(new Interceptor[]{pagePlugin});
            }

            Properties properties = new Properties();
            properties.put("prefix", "");
            properties.put("blobType", "BLOB");
            properties.put("boolValue", "TRUE");
            sessionFactoryBean.setConfigurationProperties(properties);

            return sessionFactoryBean.getObject();
        } catch (IOException var7) {
            this.logger.error("mybatis resolver mapper*xml is error", var7);
            return null;
        } catch (Exception var8) {
            this.logger.error("mybatis sqlSessionFactoryBean create error", var8);
            return null;
        }

    }

    @Override
    public String getTypeAliasesRootPackage() {
        return rootPath;
    }

    @Override
    public String getSqlMappers() {
        logger.info("mapperLocations:"+mapperLocations);

        return mapperLocations;
    }

    @Override
    public String getMybatisConfig() {
        return configLocation;
    }

    @Override
    public String getTypeAliasesPackage() {
        logger.info("typeAliasesPackage:"+typeAliasesPackage);
        return typeAliasesPackage;
    }

}