package cn.iocoder.foodnexus.module.customerpermission.core.rule;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.foodnexus.module.customerpermission.core.annotation.CustomerVisible;
import cn.iocoder.foodnexus.module.customerpermission.core.aop.CustomerPermissionContextHolder;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.List;

/**
 * 默认的 DataPermissionRuleFactoryImpl 实现类
 * 支持通过 {@link CustomerPermissionContextHolder} 过滤数据权限
 *
 * @author 芋道源码
 */
@Slf4j
public class CustomerPermissionRuleFactoryImpl implements CustomerPermissionRuleFactory {

    /**
     * 数据权限规则数组
     */
    private final List<CustomerPermissionRule> rules;

    public CustomerPermissionRuleFactoryImpl(List<CustomerPermissionRule> rules) {
        this.rules = rules;
    }

    @Override
    public List<CustomerPermissionRule> getCustomerPermissionRules() {
        return rules;
    }

    @Override // mappedStatementId 参数，暂时没有用。以后，可以基于 mappedStatementId + CustomerPermission 进行缓存
    public List<CustomerPermissionRule> getCustomerPermissionRule(String mappedStatementId) {
        // 1. 无数据权限
        if (CollUtil.isEmpty(rules)) {
            return Collections.emptyList();
        }
        // 2. 未配置，则默认关闭
        CustomerVisible customerVisible = CustomerPermissionContextHolder.get();
        if (customerVisible == null) {
            return Collections.emptyList();
        }
        // 3. 已配置，但禁用
        if (!customerVisible.enable()) {
            return Collections.emptyList();
        }
        // 6. 已配置，全部规则
        return rules;
    }

}
