package com.zanxiang.game.module.sdk.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
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.sql.Connection;

/**
 * @author : lingfeng
 * @time : 2022-09-28
 * @description : MybatisPlus分页插件
 */
@Configuration
@EnableTransactionManagement
@MapperScan({"com.zanxiang.game.module.mybatis.mapper"})
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        interceptor.addInnerInterceptor(new DatascopeInterceptor());
        return interceptor;
    }

    @Slf4j
    public static class DatascopeInterceptor implements InnerInterceptor {
        /**
         * {@link Executor#query(MappedStatement, Object, RowBounds, ResultHandler, CacheKey, BoundSql)} 操作前置处理
         * <p>
         * 改改sql啥的
         *
         * @param executor      Executor(可能是代理对象)
         * @param ms            MappedStatement
         * @param parameter     parameter
         * @param rowBounds     rowBounds
         * @param resultHandler resultHandler
         * @param boundSql      boundSql
         */
        @Override
        public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
        }

        /**
         * {@link StatementHandler#prepare(Connection, Integer)} 操作前置处理
         * <p>
         * 改改sql啥的
         *
         * @param sh                 StatementHandler(可能是代理对象)
         * @param connection         Connection
         * @param transactionTimeout transactionTimeout
         */
        @Override
        public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
        }
    }
}
