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

import com.fs.common.enums.DataScopeEnum;
import com.fs.common.enums.PlatEnum;

/**
 * 登录上下文管理器
 * 线程安全的上下文管理
 */
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();
        if(callback == null) {
            return 0L;
        }
        if(callback.getCompanyUserId() == null) {
            return 0L;
        }

        return callback.getCompanyId();
    }

    /**
     * 获取当前部门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;
    }

    /**
     * 获取当前执行环境
     * @return PlatEnum
     */
    public static PlatEnum getNowPlatEnum(){
        LoginContextCallback callback = callbackHolder.get();
        return callback != null ? callback.getNowPlatEnum() : null;
    }
}
