package com.bs.framework.config;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.bs.common.config.TenantConfigProperties;
import com.bs.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

/**
 * @author: gfk
 * @create: 2023/3/3
 * @Description:
 * @FileName: MyTenantLineHandlerImpl
 * @History:
 * @自定义内容：
 */

/**
 * 租户处理器
 *
 * @author luohq
 * @date 2022-08-07 12:31
 */
@Slf4j
public class MyTenantLineHandlerImpl implements TenantLineHandler {
    /**
     * 租户ID请求头名称
     */
    public static final String TENANT_ID_HEADER = "X-TENANT-ID";
    /**
     * 默认租户ID
     */
    public static final Long DEFAULT_TENANT_ID = 1L;

    private final TenantConfigProperties tenantConfigProperties;

    public MyTenantLineHandlerImpl(TenantConfigProperties tenantConfigProperties) {
        this.tenantConfigProperties = tenantConfigProperties;
    }
    @Override
    public Expression getTenantId() {
        Long tenantId = SecurityUtils.getTenantId();
/*        String tenantId = Optional.ofNullable(null)
                .map(String::valueOf)
                //.orElseThrow(() -> new RuntimeException("解析请求头中的X-TENANT-ID失败！"));
                .orElseGet(() -> {
                    log.info("解析请求头中的X-TENANT-ID失败 - 使用默认租户ID: {}", DEFAULT_TENANT_ID);
                    return "1";
                });*/
        //return new LongValue(tenantId);
        if(tenantId==null){
            return new LongValue(0);
        }
        return new LongValue(tenantId);

    }

    @Override
    public String getTenantIdColumn() {
        //默认tenant_id
        return "tenant_id";
    }

    @Override
    public boolean ignoreTable(String tableName) {
        //是否忽略此table的租户处理逻辑
        if(SecurityUtils.getTenantId()==null){
            return true;
        }
        // 1.是否跳过租户对该表对操作
        if (tenantConfigProperties.getTenantSkip()) {
            return true;
        }
        if(tenantConfigProperties.getOpenTenant()){
            return tenantConfigProperties.getNoIgnoreTables().contains(tableName);
        }
        return true;

    }
}
