package com.qs.mp.framework.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Mybatis Plus Config
 */
@Configuration
@MapperScan("com.qs.mp.**.mapper")
public class MybatisPlusConfig {


  /**
   * 新多租户插件配置,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存万一出现问题
   */
  @Bean
  public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
    // 添加防止全表更新与删除插件
    BlockAttackInnerInterceptor blockAttackInnerInterceptor=new BlockAttackInnerInterceptor();
    interceptor.addInnerInterceptor(blockAttackInnerInterceptor);

    // 租户ID拦截器废弃
    /*interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
      @Override
      public Expression getTenantId() {
        String custId = null != hostHolder.getUser() ? hostHolder.getUser().getCustId() : "";
        return new StringValue(custId);
      }

      @Override
      public String getTenantIdColumn() {
        return "cust_id";
      }

      // 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
//      !"ygp_store".equalsIgnoreCase(tableName)
//      && !"ygp_shop".equalsIgnoreCase(tableName)
      @Override
      public boolean ignoreTable(String tableName) {
        return !"ygp_customer_staff".equalsIgnoreCase(tableName);
           // && !"ygp_merchant_bill".equalsIgnoreCase(tableName)
           // && !"ygp_merchant_bill_pay_log".equalsIgnoreCase(tableName)
           // && !"ygp_fee_item".equalsIgnoreCase(tableName)
           // && !"ygp_contract".equalsIgnoreCase(tableName)
           // && !"ygp_merchant_staff".equalsIgnoreCase(tableName);
      }
    }));*/
    // 如果用了分页插件注意先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor
    // 用了分页插件必须设置 MybatisConfiguration#useDeprecatedExecutor = false
//    interceptor.addInnerInterceptor(new PaginationInnerInterceptor());

    return interceptor;
  }


  /**
   * 数据权限插件
   *
   * @return DataScopeInterceptor
   */
  public DataPermissionInterceptor dataPermissionInterceptor() {
    return new DataPermissionInterceptor();
  }

}
