package com.artfess.integrate.util;

import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.ContextThread;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 消息Util工具类,在线程变量中添加消息,消息使用list存放
 *
 * @author pangquan
 * @company 阿特菲斯信息技术有限公司
 * @email pangq@jee-soft.cn
 * @date 2020年11月03日
 */
@Service
public class ThreadMessageUtil implements ContextThread {

    private static ThreadLocal<Map<String, String>> localMapMsg = new ThreadLocal<Map<String, String>>();

    /**
     * 添加线程消息
     *
     * @param key
     * @param msg
     */
    public static void addMapMsg(String key, String msg) {
        Map<String, String> map = localMapMsg.get();
        if (BeanUtils.isEmpty(map)) {
            map = new HashMap<String, String>();
        }
        map.put(key, msg);
        localMapMsg.set(map);
    }

    public static String getMapMsg(String key) {
        Map<String, String> map = localMapMsg.get();
        if (BeanUtils.isEmpty(map)) {
            return null;
        }
        if (map.containsKey(key)) {
            return map.get(key);
        }
        return null;
    }

    public static Map<String, String> getMapMsg(boolean clean) {
        Map<String, String> map = localMapMsg.get();
        if (clean) {
            localMapMsg.remove();
        }
        return map;
    }

    public static String getMapMsg(String key, boolean clean) {
        Map<String, String> map = localMapMsg.get();
        if (BeanUtils.isEmpty(map)) {
            return null;
        }
        if (map.containsKey(key)) {
            String msg = map.get(key);
            if (clean) {
                map.remove(key);
            }
            return msg;
        }
        return null;
    }

    public static void cleanMapMsg() {
        localMapMsg.remove();
    }

    @Override
    public void cleanAll() {
        cleanMapMsg();
    }
}
