package com.ycwl.basic.constant;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Data
public class BaseContextHandler {

    public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

    public BaseContextHandler() {
    }

    public static void set(String key, Object value) {
        Map<String, Object> map;
        if ((map = threadLocal.get()) == null) {
            map = new HashMap<>();
            threadLocal.set(map);
        }

        map.put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map;
        if ((map = threadLocal.get()) == null) {
            map = new HashMap<>();
            threadLocal.set(map);
        }

        return (map).get(key);
    }

    public static void setToken(String token) {
        set("currentUserToken", token);
    }

    public static String getToken() {
        if (get("currentUserToken") == null) {
            return "";
        }
        if (StringUtils.isEmpty(get("currentUserToken").toString())) {
            return "";
        }
        return get("currentUserToken").toString();
    }

    public static String getAccount() {
        return returnObjectValue(get("currentAccount"));
    }

    public static void setAccount(String userName) {
        set("currentAccount", userName);
    }

    public static String getPhone() {
        return returnObjectValue(get("currentPhone"));
    }

    public static void setPhone(String phone) {
        set("currentPhone", phone);
    }

    public static String getName() {
        return returnObjectValue(get("currentName"));
    }

    public static void setName(String name) {
        set("currentName", name);
    }

    public static String getUserId() {
        return returnObjectValue(get("currentUserId"));
    }

    public static void setUserId(String userId) {
        set("currentUserId", userId);
    }


    public static String getRoleId() {
        return get("currentRoleId").toString();
    }

    public static void setRoleId(String roleId) {
        set("currentRoleId", roleId);
    }

    public static LocalDateTime getUserExpireTime() {
        return (LocalDateTime) get("currentUserExpireTime");
    }

    public static void setUserExpireTime(LocalDateTime localDateTime) {
        set("currentUserExpireTime", localDateTime);
    }


    /**
     * 返回value
     *
     * @param value
     * @return
     */
    private static String returnObjectValue(Object value) {
        return value == null ? null : value.toString();
    }

    /**
     * 移除threadLocal
     */
    public static void remove() {
        threadLocal.remove();
    }

}
