package com.njzscloud.common.mp.support;

import com.baomidou.mybatisplus.extension.plugins.handler.MultiDataPermissionHandler;
import com.njzscloud.common.security.support.UserDetail;
import com.njzscloud.common.security.util.SecurityUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Table;

import java.util.List;
import java.util.function.Supplier;

@Slf4j
@AllArgsConstructor
public class CustomDataPermissionHandler implements MultiDataPermissionHandler {

    public static final Supplier<Long> TENANT_ID_SUPPLIER = () -> {
        UserDetail userDetail = SecurityUtil.loginUser();
        Long tenantId = 0L;
        if (userDetail != null) tenantId = userDetail.getTenantId();
        if (tenantId == null) tenantId = 0L;
        return tenantId;
    };
    private final List<String> ignoreTables;

    @Override
    public Expression getSqlSegment(Table table, Expression where, String mappedStatementId) {
        Long tenantId = TENANT_ID_SUPPLIER.get();
        String tableName = table.getName();
        if ((ignoreTables != null && ignoreTables.contains(tableName)) || tenantId == null || tenantId == 0L)
            return null;
        try {
            return CCJSqlParserUtil.parseCondExpression("tenant_id = " + tenantId);
        } catch (JSQLParserException e) {
            log.error("租户 Id 条件设置失败：{}", tenantId, e);
            return null;
        }
    }
}
