// fs-service模块
package com.fs.common.config;

import com.fs.common.enums.DataScopeEnum;

/**
 * 登录上下文管理器
 * 线程安全的上下文管理
 */
public class LoginContextManager {

    private static final ThreadLocal<LoginContextCallback> callbackHolder = new ThreadLocal<>();

    /**
     * 设置上下文回调函数
     */
    public static void setContextCallback(LoginContextCallback callback) {
        callbackHolder.set(callback);
    }

    /**
     * 获取当前用户ID
     */
    public static Long getCurrentUserId() {
        LoginContextCallback callback = callbackHolder.get();
        return callback != null ? callback.getUserId() : null;
    }

    /**
     * 获取companyUserId
     */
    public static Long getCurrentCompanyUserId() {
        LoginContextCallback callback = callbackHolder.get();
        return callback != null ? callback.getCompanyUserId() : null;
    }

    /**
     * 获取用户名
     */
    public static String getCurrentUsername() {
        LoginContextCallback callback = callbackHolder.get();
        return callback != null ? callback.getUsername() : null;
    }

    /**
     * 获取租户ID
     */
    public static Long getCurrentCompanyId() {
        LoginContextCallback callback = callbackHolder.get();
        return callback != null ? callback.getCompanyId() : null;
    }

    /**
     * 获取当前部门ID
     * @return 部门ID
     */
    public static Long getCurrentDeptId(){
        LoginContextCallback callback = callbackHolder.get();
        return callback != null ? callback.getDeptId() : null;
    }

    /**
     * 获取当前用户的数据权限
     * @return DataScopeEnum
     */
    public static DataScopeEnum getDataScope(){
        LoginContextCallback callback = callbackHolder.get();
        return callback != null ? callback.getDataScope() : null;
    }



    /**
     * 清理上下文
     */
    public static void clearContext() {
        callbackHolder.remove();
    }

    /**
     * 检查是否有有效的上下文
     */
    public static boolean hasContext() {
        LoginContextCallback callback = callbackHolder.get();
        return callback != null && callback.getUserId() != null;
    }

    /**
     * 当前用户是否有指定资源的权限
     * @param permission 权限支付
     * @return boolean
     */
    public static boolean hasPermission(String permission) {
        LoginContextCallback callback = callbackHolder.get();
        return callback != null && callback.hasPermission(permission);
    }
}
