package com.zhongzheng.framework.mybatisplus;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.zhongzheng.common.core.domain.AjaxResult;
import com.zhongzheng.common.exception.CustomException;
import com.zhongzheng.common.utils.ServletUtils;
import lombok.SneakyThrows;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.commons.compress.utils.Lists;


import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.xml.soap.MimeHeaders;

/**
 * 多租户处理插件
 *
 * @author hjl
 * @date 2021/07/30 13:37
 */
@Component
public class CustomTenantLineHandler implements TenantLineHandler {

    /**
     * 租户id字段名
     */
    public static final String TENANT_ID_COLUMN = "tenant_id";

  //  public static  String TENANT_ID = null;

    @Value("${mybatis-plus.tenant.enabled-tenant:true}")
    private boolean enabledTenant;

    /**
     * 忽略添加租户ID的表
     */
    private final static List<String> IGNORE_TABLE_NAMES = new ArrayList<String>(){{
        add("sys_tenant");
        add("top_sys_user");
        add("top_sys_dept");
        add("top_sys_role");
        add("top_sys_user_role");
        add("tables");
        add("columns");
        add("sys_logininfor");
    }};

    /**
     * 获取租户ID值表达式(可从cookie、token、缓存中取)
     *
     * @return
     */
    @SneakyThrows
    @Override
    public Expression getTenantId() {
        String TenantId = ServletUtils.getRequest().getHeader("TenantId");
        if(!StrUtil.isNotBlank(TenantId)||TenantId==null){
            TenantId = ServletUtils.getResponse().getHeader("TenantId");
            if(enabledTenant){
                if(!StrUtil.isNotBlank(TenantId)||TenantId==null){
                    int code = HttpStatus.HTTP_UNAVAILABLE;
                    String msg = "企业非法访问";
                    ServletUtils.renderString( ServletUtils.getResponse(), JSON.toJSONString(AjaxResult.error(code, msg)));
                    ServletUtils.getResponse().getWriter().flush();
                    ServletUtils.getResponse().getWriter().close();
                }
            }
        }
        return new LongValue(TenantId);
    }

    /**
     * 获取租户字段名(数据库的租户ID字段名)
     *
     * @return
     */
    @Override
    public String getTenantIdColumn() {
        return TENANT_ID_COLUMN;
    }

    /**
     * 根据表名判断是否忽略拼接多租户条件
     *
     * @param tableName
     * @return
     */
    @Override
    public boolean ignoreTable(String tableName) {
        return IGNORE_TABLE_NAMES.contains(tableName);
    }


}
