package com.jiayue.ssi.service.impl;

import com.jiayue.ssi.constant.PermissionContextHolder;
import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.util.RyStringUtils;
import com.jiayue.ssi.util.SecurityContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

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

    /** 管理员角色权限标识 */
    private static final String SUPER_ADMIN = "admin";

    private static final String ROLE_DELIMETER = ",";

    private static final String PERMISSION_DELIMETER = ",";
    @Autowired
    SysPermissionService sysPermissionService;
    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermi(String permission)
    {
        if (RyStringUtils.isEmpty(permission))
        {
            return false;
        }
        SysUser loginUser = SecurityContextUtil.getSysUser();
        if (RyStringUtils.isNull(loginUser)) {
            return false;
        }
        PermissionContextHolder.setContext(permission);
        Set<String> permissions = sysPermissionService.getMenuPermission(loginUser.getId());
        return hasPermissions(permissions, permission);
    }

    /**
     * 验证用户是否不具备某权限，与 hasPermi逻辑相反
     *
     * @param permission 权限字符串
     * @return 用户是否不具备某权限
     */
    public boolean lacksPermi(String permission)
    {
        return hasPermi(permission) != true;
    }

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