package com.ssm.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.StringUtils;
import com.ssm.util.RedisClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Data
public class BeiSenUtils {
//    private String accessToken;
//    private Long expiresIn;
//    private String refreshToken;

    @Value("${beisen.app.key}")
    private String key;
    @Value("${beisen.app.secret}")
    private String secret;

    @Autowired
    private RedisClient redisClient;

    public String getToken(){
        String token = (String) redisClient.get(Constant.beiSenToken);
        if(StringUtils.isNotBlank(token)){
            return token;
        }
        //使用刷新的key重新去获取token
        String refreshToken = (String) redisClient.get(Constant.beiSenRefreshToken);
        if(StringUtils.isNotBlank(refreshToken)){
            JSONObject jsonObject = JSON.parseObject("{\"grant_type\":\"refresh_token\""+
                    ",\"refresh_token\": " +"\""+ refreshToken +"\""+
                    " }");
            JSONObject jsonobject = new JSONObject();
            jsonobject.put("param",JSON.toJSON(jsonObject)) ;
            String response = HttpClientUtil.doPost("https://openapi.italent.cn/token", jsonobject);
            if (StringUtils.isNotBlank(response) && !response.equals("null")) {
                try {
                    BeiSenResponse parse = JSON.parseObject(response, BeiSenResponse.class);
                    //写入redis中
                    redisClient.set(Constant.beiSenToken, parse.getAccess_token(), 7200L, TimeUnit.SECONDS);
                    redisClient.set(Constant.beiSenRefreshToken, parse.getRefresh_token());
                    return parse.getAccess_token();
                } catch (Exception e) {

                }
            }

        }
        JSONObject jsonObject = JSON.parseObject("{\"grant_type\":\"client_credentials\",\"app_key\":" +"\""+ key +"\""+
                ",\"app_secret\": " +"\""+ secret +"\""+
                " }");
        JSONObject jsonobject = new JSONObject();
        jsonobject.put("param",JSON.toJSON(jsonObject)) ;
        String response = HttpClientUtil.doPost("https://openapi.italent.cn/token",
                jsonobject);
        BeiSenResponse parse = JSON.parseObject(response,BeiSenResponse.class);
        //写入redis中
        redisClient.set(Constant.beiSenToken,parse.getAccess_token(),7200L, TimeUnit.SECONDS);
        redisClient.set(Constant.beiSenRefreshToken,parse.getRefresh_token());
        return parse.getAccess_token();
    }


}
