package com.hdkj.lt.core.bizms.mp;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import com.jxdinfo.hussar.support.mp.config.MybatisPlusPluginProperties;
import com.jxdinfo.hussar.support.mp.intercept.QueryInterceptor;
import com.jxdinfo.hussar.support.mp.plugins.HussarPaginationInterceptor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;

@Configuration
public class MybatisPlusConfiguration {

    @Bean
    public MybatisPlusInterceptor tableNameHandleInterceptor(ObjectProvider<QueryInterceptor[]> queryInterceptors, MybatisPlusPluginProperties mybatisPlusProperties) {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        HussarPaginationInterceptor paginationInterceptor = new HussarPaginationInterceptor();
        QueryInterceptor[] queryInterceptorArray = queryInterceptors.getIfAvailable();
        if (ObjectUtils.isNotEmpty(queryInterceptorArray)) {
            AnnotationAwareOrderComparator.sort(queryInterceptorArray);
            paginationInterceptor.setQueryInterceptors(queryInterceptorArray);
        }
        paginationInterceptor.setMaxLimit(mybatisPlusProperties.getPageLimit());
        paginationInterceptor.setOverflow(mybatisPlusProperties.getOverflow());
        paginationInterceptor.setOptimizeJoin(mybatisPlusProperties.getOptimizeJoin());
        ArgDynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new ArgDynamicTableNameInnerInterceptor();
        TableNameHandler tableNameHandler = new ArgTableNameHandler();
        dynamicTableNameInnerInterceptor.setTableNameHandler(tableNameHandler);
        mybatisPlusInterceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        mybatisPlusInterceptor.addInnerInterceptor(paginationInterceptor);

        // 批量插入注入 - 全表删除更新脚本校验，现关闭
        //mybatisPlusInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());

        return mybatisPlusInterceptor;
    }

    @Bean
    public BatchSqlInjector easySqlInjector() {
        return new BatchSqlInjector();
    }
}
