package com.lightinit.hsdataplatformresdir.spring;

import com.lightinit.hsdataplatformresdir.entity.PermissionModule;
import com.lightinit.hsdataplatformresdir.service.IShiroPermissionsService;
import org.apache.shiro.config.Ini;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.config.IniFilterChainResolverFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Mr.Yao on 2017/11/8.
 */
public class ShiroPermissionFactory extends ShiroFilterFactoryBean {
    @Autowired
    private IShiroPermissionsService shiroPermissionsService;
    public static String filterChainDefinitions="";
    @Override
    public void setFilterChainDefinitions(String definitions){
        ShiroPermissionFactory.filterChainDefinitions=definitions;
        //数据库动态权限
        List<PermissionModule> permissions= shiroPermissionsService.findAll();
        Map<String,String> otherChains=new HashMap<String, String>();
        for(PermissionModule permission : permissions){
            String roles="";
            if(otherChains.containsKey(permission.getAction())){
                roles=otherChains.get(permission.getAction());
                if(StringUtils.isEmpty(roles)==false){
                    String tmpRoles= roles.replace("sroles[","").replace("]","").replace("\"","");
                    List<String> arrayRoles= Arrays.asList(tmpRoles.split(","));
                    if(arrayRoles.contains(permission.getRolecode())==false) {
                        roles=tmpRoles+"," + permission.getRolecode();
                        otherChains.replace(permission.getAction(),"sroles[\"" + roles + "\"]");
                    }
                }
            }else {
                if(permission.getRolecode().equalsIgnoreCase("admin")==false) {
                    roles = "sroles[\"admin," + permission.getRolecode() + "\"]";
                }else{
                    roles = "sroles[admin]";
                }
                otherChains.put(permission.getAction(),roles);
            }
        }
        otherChains.put("/**", "authc");
        //从配置文件加载权限配置
        Ini ini = new Ini();
        ini.load(definitions);
        Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS);
        if (CollectionUtils.isEmpty(section)) {
            section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        }
        section.putAll(otherChains);
        //加入权限集合
        setFilterChainDefinitionMap(section);
    }
}
