package com.ssj.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
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 org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;

/**
 * @author yrf
 * @description
 * @time 2019/9/16 16:51
 */
@Configuration
@AutoConfigureAfter(SqlSessionFactory.class)
public class MybatisPlusConfig {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${mybatis-plus.mapper-locations}")
    private String mapperLocations;

    @Value("${mybatis-plus.refresh-mapper}")
    private Boolean refreshMapper;

    private static final ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();

    /*
     * 分页插件，自动识别数据库类型
     * 多租户，请参考官网【插件扩展】
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作， true调回到首页，false 继续请求  默认false
        // paginationInterceptor.setOverflow(false);
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
         paginationInterceptor.setLimit(-1);
        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }


    /**
     * mapper.xml 热加载
     * @return
     */
    @Bean
    public MybatisMapperRefresh mybatisMapperRefresh(){
        SqlSessionFactory sqlSessionFactory = SpringContextHolder.getBean("sqlSessionFactory");
        Resource[] resources = new Resource[0];
        try {
            resources = resourceResolver.getResources(mapperLocations);
        } catch (IOException e) {
            logger.error("获取mapper source异常", e);
        }
        return new MybatisMapperRefresh(resources,sqlSessionFactory,10,5,refreshMapper);
    }

}
