package com.nbclass.shiro;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nbclass.holder.SpringContextHolder;
import com.nbclass.system.model.Permission;
import com.nbclass.system.service.PermissionService;

/**
 *
 * @author Leon
 * @datetime 2019年4月1日 下午2:47:53
 */
@Service
public class ShiroService {

    @Autowired
    private PermissionService permissionService;

    /**
     * 初始化加载权限
     * @return
     */
    public Map<String, String> loadFilterChainDefinitions() {
        // 权限控制map.从数据库获取
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();

        filterChainDefinitionMap.put("/register", "anon");
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/error/**", "anon");
        filterChainDefinitionMap.put("/kickout", "anon");
        /*filterChainDefinitionMap.put("/logout", "logout");*/
        filterChainDefinitionMap.put("/css/**","anon");
        filterChainDefinitionMap.put("/js/**","anon");
        filterChainDefinitionMap.put("/img/**","anon");
        filterChainDefinitionMap.put("/libs/**","anon");
        filterChainDefinitionMap.put("/favicon.ico", "anon");
        filterChainDefinitionMap.put("/verificationCode", "anon");

        filterChainDefinitionMap.put("/test/**", "anon");

        filterChainDefinitionMap.put("/api/**" ,"anon"); 	// 前端接口
        filterChainDefinitionMap.put("/", "anon");			// 网站首页
        // 静态资源按后缀排除
        filterChainDefinitionMap.put("/**/*.css", "anon");
        filterChainDefinitionMap.put("/**/*.js", "anon");
        filterChainDefinitionMap.put("/**/*.jpg", "anon");
        filterChainDefinitionMap.put("/**/*.png", "anon");
        filterChainDefinitionMap.put("/**/*.gif", "anon");
        filterChainDefinitionMap.put("/**/*.webp", "anon");
        filterChainDefinitionMap.put("/**/*.ttf", "anon");
        filterChainDefinitionMap.put("/**/*.woff", "anon");
        filterChainDefinitionMap.put("/**/*.woff2", "anon");
        filterChainDefinitionMap.put("/**/*.mp3", "anon");
        filterChainDefinitionMap.put("/**/*.mp4", "anon");

    //	filterChainDefinitionMap.put("/**/*.html", "authc,wxOAuthFilter");
    //	filterChainDefinitionMap.put("/**/*.jsp", "authc,wxOAuthFilter");
        filterChainDefinitionMap.put("/**/*.html", "wxOAuthFilter");
        filterChainDefinitionMap.put("/mobile/page/**", "wxOAuthFilter");
        // 测试放开权限
        filterChainDefinitionMap.put("/mobile/api/**", "anon");

        //List<Permission> permissionList = permissionService.selectAll(CoreConst.STATUS_VALID); // 迁移此数据库结构不一致，不从数据库查权限配置
        List<Permission> permissionList = new ArrayList<Permission>();
        for(Permission permission : permissionList){
            if (StringUtils.isNotBlank(permission.getUrl())&& StringUtils.isNotBlank(permission.getPerms())) {
                String perm = "perms[" + permission.getPerms()+ "]";
                filterChainDefinitionMap.put(permission.getUrl(),perm+",kickout");
            }
        }

        filterChainDefinitionMap.put("/**", "user,kickout");

        return filterChainDefinitionMap;
    }

    /**
     * 添加/修改/删除 后 重新加载权限
     */
    public void updatePermission() {
        ShiroFilterFactoryBean shiroFilterFactoryBean = SpringContextHolder.getBean(ShiroFilterFactoryBean.class);
        synchronized (shiroFilterFactoryBean) {
            AbstractShiroFilter shiroFilter = null;
            try {
                shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();
            } catch (Exception e) {
                throw new RuntimeException("get ShiroFilter from shiroFilterFactoryBean error!");
            }

            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter
                    .getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver
                    .getFilterChainManager();

            // 清空老的权限控制
            manager.getFilterChains().clear();

            shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
            shiroFilterFactoryBean.setFilterChainDefinitionMap(loadFilterChainDefinitions());
            // 重新构建生成
            Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();
            for (Map.Entry<String, String> entry : chains.entrySet()) {
                String url = entry.getKey();
                String chainDefinition = entry.getValue().trim().replace(" ", "");
                manager.createChain(url, chainDefinition);
            }
        }
    }
}
