package com.gxwebsoft.common.core.config;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.system.entity.User;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * MybatisPlus配置
 *
 * @author WebSoft
 * @since 2018-02-22 11:29:28
 */
@Configuration
public class MybatisPlusConfig {
  @Resource
  private RedisUtil redisUtil;

  @Bean
  public MybatisPlusInterceptor mybatisPlusInterceptor(HttpServletRequest request) {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

    // 多租户插件配置
    TenantLineHandler tenantLineHandler = new TenantLineHandler() {

      @Override
      public Expression getTenantId() {
        String tenantId;
        // 从请求头拿ID
        tenantId = request.getHeader("tenantId");
        if(tenantId != null){
          return new LongValue(tenantId);
        }
        // 从域名拿ID
        String Domain = request.getHeader("Domain");
        if (StrUtil.isNotBlank(Domain)) {
          String key = "Domain:" + Domain;
          tenantId = redisUtil.get(key);
          if(tenantId != null){
            System.out.println("授权域名" + Domain + " => " + tenantId);
            return new LongValue(tenantId);
          }
        }
        return getLoginUserTenantId();
      }

      @Override
      public boolean ignoreTable(String tableName) {
        return Arrays.asList(
          "sys_tenant",
          "sys_dictionary",
          "sys_dictionary_data",
          "sys_user_oauth",
          "sys_email_record",
          "sys_plug",
          "sys_version",
          "sys_order",
          "sys_modules",
          "sys_environment",
          "sys_components",
          "sys_website_field",
//          "sys_company",
          "sys_domain",
          "sys_white_domain"
//          "cms_domain"
//          "cms_website",
//          "cms_website_field",
//          "cms_navigation",
//          "cms_design",
//          "cms_design_record",
//          "cms_article",
//          "cms_article_content",
//          "cms_article_category",
//          "cms_article_comment",
//          "cms_article_count",
//          "cms_article_like",
//          "cms_form",
//          "cms_form_record",
//          "cms_link",
//          "oa_app",
//          "oa_app_field",
//          "oa_app_renew",
//          "oa_app_url",
//          "oa_app_user",
//          "shop_goods",
//          "cms_product",
//          "cms_product_url",
//          "cms_product_spec",
//          "cms_product_spec_value",
//          "sys_company_content"
        ).contains(tableName);
      }
    };
    TenantLineInnerInterceptor tenantLineInnerInterceptor = new TenantLineInnerInterceptor(tenantLineHandler);
    interceptor.addInnerInterceptor(tenantLineInnerInterceptor);

    // 分页插件配置
    PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
    interceptor.addInnerInterceptor(paginationInnerInterceptor);

    return interceptor;
  }

  /**
   * 获取当前登录用户的租户id
   *
   * @return Integer
   */
  public Expression getLoginUserTenantId() {
    try {
      Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
      if (authentication != null) {
        Object object = authentication.getPrincipal();
        if (object instanceof User) {
          return new LongValue(((User) object).getTenantId());
        }
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    return new NullValue();
  }

}
