package com.lightinit.hsdataplatform.common;

import com.google.gson.Gson;
import com.lightinit.hsdataplatform.dictionary.DicGitToken;
import com.lightinit.hsdataplatform.dictionary.DicPaasApi;
import com.mongodb.util.JSON;

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

/**
 * @author lidy
 */

public  class TokenUntils {

    public static  String EXPIRYTIME = "" ;

    public static String STORAGE = "" ;


    public static  String getToken(){
        Date date = new Date(System.currentTimeMillis());
        long nowTime = date.getTime() ;
        if (!getSTORAGE().equals("")){
            long time = Long.valueOf(getEXPIRYTIME()) ;
            //没过期
            if (nowTime<time){
                return getSTORAGE() ;
            }
        }
            Map<String,String> heads = new HashMap<>() ;
            heads.put("Authorization", DicGitToken.AUTHORIZATION) ;
            heads.put("Content-Type","application/x-www-form-urlencoded") ;
            String token = "" ;
            try {
                token =  HttpUtil.getToken(DicPaasApi.TOKEN,heads,"application/x-www-form-urlencoded") ;
            } catch (Exception e) {
                e.printStackTrace();
            }
            Gson gson = new Gson();
            Map<String,Object> str = gson.fromJson(token,Map.class) ;
            String accessToken = (String) str.get("access_token") ;
            setSTORAGE(accessToken);
            Double getTime = (Double) str.get("expires_in");
            long str1 = getTime.longValue()+nowTime ;
            setEXPIRYTIME(String.valueOf(str1));
            return accessToken ;
    }

    public static  Map<String,String> getHead(){
        Map<String,String> head = new HashMap<>() ;
        head.put("Authorization","Bearer "+getToken()) ;
        return head ;
    }

    public static String getEXPIRYTIME() {
        return EXPIRYTIME;
    }

    public static void setEXPIRYTIME(String EXPIRYTIME) {
        TokenUntils.EXPIRYTIME = EXPIRYTIME;
    }

    public static String getSTORAGE() {
        return STORAGE;
    }

    public static void setSTORAGE(String STORAGE) {
        TokenUntils.STORAGE = STORAGE;
    }
}
