package com.fs.core;

import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.fs.app.utils.JwtUtils;
import com.fs.common.core.domain.entity.SysRole;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义权限实现，ss取自SpringSecurity首字母
 */
@Service("ss")
public class PermissionService
{
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    RedisCache redisCache;
    /** 所有权限标识 */
    private static final String ALL_PERMISSION = "*:*:*";



    /**
     * 验证用户是否具备某权限
     * 
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermi(String permission)
    {

        String headValue = ServletUtils.getRequest().getHeader("APPToken");
        Claims claims=jwtUtils.getClaimByToken(headValue);
        String userId = claims.getSubject().toString();
        //获取用户所有的权限
        String permss=redisCache.getCacheObject("perms:"+userId);
        if(StringUtils.isNotEmpty(permss)){
            List<String> perms= (List<String>) JSONUtils.parse(permss);
            if (StringUtils.isEmpty(permission))
            {
                return false;
            }
            if (StringUtils.isNull(userId) || CollectionUtils.isEmpty(perms))
            {
                return false;
            }
            return hasPermissions(perms, permission);
        }
        else{
            return false;
        }


    }



    /**
     * 判断是否包含权限
     * 
     * @param permissions 权限列表
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(List<String> permissions, String permission)
    {
        return permissions.contains(ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission));
    }


}
