package com.persagy.labsl.config

import com.baomidou.mybatisplus.annotation.DbType
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor
import com.fasterxml.jackson.databind.ObjectMapper
import org.mybatis.spring.annotation.MapperScan
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.CommandLineRunner
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.transaction.annotation.EnableTransactionManagement

/**
 * MybatisPlus公共配置
 * @author lixing
 * @description 由 Mybatisplus Code Generator 创建
 * @since 2020-09-09 09:13:27
 */
@MapperScan(value = ["com.persagy.**.mapper","com.persagy.**.services.mappers","com.persagy.mybatis"])
@Configuration
@EnableTransactionManagement
open class MybatisPlusConfig : CommandLineRunner {
    @Value("\${persagy.common.sql.limit:500}")
    private val sqlLimit: Long = 0
    @Value("\${persagy.common.sql.db.type:mysql}")
    private val dbType: String? = null

    @Throws(Exception::class)
    override fun run(vararg args: String) { // 注入objectMapper，处理Java对象转JsonString
        JacksonTypeHandler.setObjectMapper(objectMapper())
    }

    /**
     * 注册Mybatis插件
     * 使用示例： IPage<Member> memberPage = new Page<>(1, 2，false) true查询总记录数量
    </Member> */
    @Bean
    open fun objectMapper(): ObjectMapper {
        return ObjectMapper()
    }

    /**
     * 注册Mybatis插件
     * 使用示例： IPage<Member> memberPage = new Page<>(1, 2，false) true查询总记录数量
    </Member> */
    @Bean
    open fun mybatisPlusInterceptor(): MybatisPlusInterceptor {
        val mybatisPlusInterceptor = MybatisPlusInterceptor()
        val paginationInnerInterceptor = PaginationInnerInterceptor()
        // 设置每页查询记录上限，默认500（与mp相同）
        paginationInnerInterceptor.maxLimit = sqlLimit
        paginationInnerInterceptor.dbType = DbType.getDbType(dbType)
        // 添加分页插件
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor)
        return mybatisPlusInterceptor
    }
}