package com.aiotagro.common.core.utils;

import cn.dev33.satoken.stp.StpUtil;
import com.aiotagro.common.core.constant.RoleConstants;

import java.util.Collections;
import java.util.List;

/**
 * @author Carson
 * @package_name com.aiotagro.common.core.utils
 * @date 2024/2/7 14:18
 */
public class SecurityUtil {

    /**
     * 获取登录用户ID
     **/
    public static Long getUserId() {
        return StpUtil.getLoginIdAsLong();
    }

    /**
     * 获取登录用户ID
     **/
    public static Integer getCurrentUserId() {
        return StpUtil.getLoginIdAsInt();
    }

    /**
     * 获取用户名称
     **/
    public static String getUserName() {
        Object username = StpUtil.getTokenSession().get("username");
        return username != null ? username.toString() : "";
    }

    /**
     * 获取用户手机号
     **/
    public static String getUserMobile() {
        Object mobile = StpUtil.getTokenSession().get("mobile");
        return mobile != null ? mobile.toString() : "";
    }

    /**
     * 获取当前用户角色ID
     **/
    public static Integer getRoleId() {
        Object roleId = StpUtil.getTokenSession().get("roleId");
        return roleId != null ? Integer.parseInt(roleId.toString()) : null;
    }

    /**
     * 获取当前用户权限列表
     **/
    @SuppressWarnings("unchecked")
    public static List<String> getPermissions() {
        Object permissions = StpUtil.getTokenSession().get("permissions");
        return permissions != null ? (List<String>) permissions : Collections.emptyList();
    }

    /**
     * 判断是否超级管理员
     **/
    public static boolean isSuperAdmin() {
        Integer roleId = getRoleId();
        return roleId != null && roleId.equals(RoleConstants.SUPER_ADMIN_ROLE_ID);
    }

    /**
     * 判断是否拥有某个权限
     **/
    public static boolean hasPermission(String permission) {
        if (isSuperAdmin()) {
            return true;
        }
        List<String> permissions = getPermissions();
        return permissions.contains(RoleConstants.ALL_PERMISSION) || 
               permissions.contains(permission);
    }

}
