package com.ywt.alipaympapi.web.interceptors;

/**
 * 保存当前请求与业务相关的信息上下文
 * 由拦截器层提供信息初始化
 */
public class WebAppContext {
    private static WebAppContext _webAppContext = null;
    private static Object _lockObj = new Object();
    private ThreadLocal<Long> _requestStartTime = new ThreadLocal<>();
    private ThreadLocal<String> _requestID = new ThreadLocal<>();
    private ThreadLocal<String> _ip = new ThreadLocal<>();
    private ThreadLocal<Integer> _userId = new ThreadLocal<>();
    private ThreadLocal<String> _alipayUid = new ThreadLocal<>();
    private ThreadLocal<Integer> _terminal = new ThreadLocal<>();

    private WebAppContext() {
    }

    public long getRequestStartTime() {
        return _requestStartTime.get() == null ? 0L : _requestStartTime.get();
    }

    protected void setRequestStartTime(long time) {
        _requestStartTime.set(time);
    }

    public String getRequestID() {
        return _requestID.get() == null ? "" : _requestID.get();
    }

    protected void setRequestID(String id) {
        _requestID.set(id);
    }

    public String getIP() {
        return _ip.get() == null ? "" : _ip.get();
    }

    protected void setIP(String ip) {
        _ip.set(ip);
    }

    public Integer getUserId() {
        return _userId.get() == null ? 0 : _userId.get();
    }

    protected void setUserId(Integer userId) {
        _userId.set(userId);
    }


    public Integer getTerminal() {
        return _terminal.get() == null ? 0 : _terminal.get();
    }

    protected void setTerminal(Integer terminal) {
        this._terminal.set(terminal);
    }

    protected void setAlipayUid(String alipayUid) {
        this._alipayUid.set(alipayUid);
    }

    public String getAlipayUid() {
        return this._alipayUid.get();
    }

    protected void init() {
        _requestStartTime.set(0L);
        _requestID.set("");
        _ip.set("");
        _userId.set(0);
        _alipayUid.set("");
        _terminal.set(0);
    }

    public static WebAppContext current() {
        if (_webAppContext == null) {
            synchronized (_lockObj) {
                if (_webAppContext == null) {
                    _webAppContext = new WebAppContext();
                }
            }
        }
        return _webAppContext;
    }
}
