package com.seer.teach.common.data.permission.config;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.seer.teach.common.data.permission.aop.DataPermissionAnnotationAdvisor;
import com.seer.teach.common.data.permission.handler.DataPermissionRuleHandler;
import com.seer.teach.common.data.permission.rule.DataPermissionCondition;
import com.seer.teach.common.data.permission.rule.DataPermissionRule;
import com.seer.teach.common.data.permission.rule.DataPermissionRuleFactory;
import com.seer.teach.common.data.permission.rule.DataPermissionRuleFactoryImpl;
import com.seer.teach.common.data.permission.rule.role.RoleDataPermissionRule;
import com.seer.teach.common.data.permission.rule.role.RoleDataPermissionRuleCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

//@Configuration
public class DataPermissionAutoConfiguration {

    @Bean
    public RoleDataPermissionRule roleDataPermissionRule(List<RoleDataPermissionRuleCustomizer>  rules) {
        RoleDataPermissionRule rule = new RoleDataPermissionRule();
        if(CollectionUtil.isNotEmpty(rules)){
            rules.forEach(customizer -> customizer.customize(rule, rule.getCondition()));
        }
        return rule;
    }

    @Bean
    public DataPermissionRuleFactory dataPermissionRuleFactory(List<DataPermissionRule> rules, List<DataPermissionCondition>  conditions) {
        return new DataPermissionRuleFactoryImpl(rules,conditions);
    }

    @Bean
    public DataPermissionRuleHandler dataPermissionRuleHandler(MybatisPlusInterceptor interceptor,
                                                               DataPermissionRuleFactory ruleFactory) {
        DataPermissionRuleHandler handler = new DataPermissionRuleHandler(ruleFactory);
        DataPermissionInterceptor inner = new DataPermissionInterceptor(handler);
        List<InnerInterceptor> inners = new ArrayList<>(interceptor.getInterceptors());
        inners.add(0, inner);
        interceptor.setInterceptors(inners);
        return handler;
    }

    @Bean
    public DataPermissionAnnotationAdvisor dataPermissionAnnotationAdvisor() {
        return new DataPermissionAnnotationAdvisor();
    }
}