package com.lightinit.hsdataportal.common;

import com.google.gson.Gson;
import com.lightinit.hsdataportal.dictionary.DicGitToken;
import org.springframework.util.StringUtils;

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

/**
 * @Author: sunxiang
 * @Date: 2018/9/28 10:04
 * @Description: 获取平台同步需要的token
 **/
public class TokenUtils {

    public static  String EXPIRYTIME = "" ;

    public static String STORAGE = "" ;

    public static void main(String[] args) {
        getToken();
    }

    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(DicGitToken.URL,heads,"application/x-www-form-urlencoded") ;
        } catch (Exception e) {
            e.printStackTrace();
        }
        Gson gson = new Gson();
        Map<String,Object> str = gson.fromJson(token,Map.class) ;
        if(!StringUtils.isEmpty(str.get("access_token"))){
            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 ;
        }
        return null;
    }

    public static String getEXPIRYTIME() {
        return EXPIRYTIME;
    }

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

    public static String getSTORAGE() {
        return STORAGE;
    }

    public static void setSTORAGE(String STORAGE) {
        TokenUtils.STORAGE = STORAGE;
    }
    /*
    *@Description 管控平台的配置类
    *@Param
    *@Date 2018/9/29
    *@return
    **/
    public static class MsgsServer{
        public static final String USERPATH="v1/user";
    }

    /*
    *@Description 开发平台的配置类
    *@Param
    *@Date 2018/9/29
    *@return
    **/
    public static class DevopsServer{
        public static final String GROUPPATH="api/v1/groups";
        public static final String USERPATH="api/v1/users";
    }
}
