package com.example.demo.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class TempToken {
    private static final String slat  = "temp-token-smart-bow";
    private long timestamp;
    private String jsonText;
    private String sign;
    private JSONObject params;

    public TempToken(JSONObject params)
    {
        this.params = params;
        timestamp = System.currentTimeMillis();
        jsonText = params.toJSONString();
        sign = MD5Tool.makeMD5(timestamp + jsonText + slat);
    }

    public TempToken(String token)
    {
        try {
            sign = token.substring(0, 32);
            timestamp = Long.parseLong(token.substring(32, 45));
            jsonText = token.substring(45);
            params = JSON.parseObject(jsonText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return sign + timestamp + jsonText;
    }

    public JSONObject getParams() {
        return params;
    }

    public boolean isValid(long validTimeMillis) {
        String signMade = MD5Tool.makeMD5(timestamp + jsonText + slat);
        return signMade.equals(sign) && System.currentTimeMillis() - timestamp < validTimeMillis;
    }
}
