package com.springboot.cloud.common.core.util;

import com.google.common.collect.Maps;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * {"companies":[{"default":true,"authority":"1"},{"default":false,"authority":"2"}],"user_name":"admin","scope":["read"],"exp":1610100088,"authorities":["1","2"],"jti":"nt9bTYbUe8IzuEgfAz70nwaMveI","client_id":"test_client"}
 */

/**
 * 用户上下文
 */
public class UserContextHolder {

    private ThreadLocal<Map<String, String>> threadLocal;

    private UserContextHolder() {
        this.threadLocal = new ThreadLocal<>();
    }

    /**
     * 创建实例
     *
     * @return
     */
    public static UserContextHolder getInstance() {
        return SingletonHolder.sInstance;
    }

    /**
     * 静态内部类单例模式
     * 单例初使化
     */
    private static class SingletonHolder {
        private static final UserContextHolder sInstance = new UserContextHolder();
    }

    /**
     * 用户上下文中放入信息
     *
     * @param map
     */
    public void setContext(Map<String, String> map) {
        threadLocal.set(map);
    }

    /**
     * 获取上下文中的信息
     *
     * @return
     */
    public Map<String, String> getContext() {
        return threadLocal.get();
    }

    /**
     * 获取上下文中的用户名
     *
     * @return
     */
    public String getUsername() {
        return Optional.ofNullable(threadLocal.get()).orElse(Maps.newHashMap()).get("user_name");
    }

    /**
     * 获取上下文中用户登录的公司
     *
     * @return
     */
    public String getCurrentCompany() {
        return Optional.ofNullable(threadLocal.get()).orElse(Maps.newHashMap()).get("company");
    }

    /**
     * 清空上下文
     */
    public void clear() {
        threadLocal.remove();
    }

}
