package com.fs.aicall.utils;

import com.alibaba.fastjson.JSONObject;
import com.fs.baidu.utils.HttpUtils;
import com.fs.common.core.redis.RedisCacheT;
import com.fs.common.exception.base.BaseException;
import com.fs.common.utils.StringUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@AllArgsConstructor
public class AiobTokenUtils {

    private static final String ACC_TOKEN_KEY = "aiob:baidu:token:";
    private final RedisCacheT<String> redisCache;

    public String getToken(String accessKey, String secretKey) {
        String key = ACC_TOKEN_KEY + accessKey;
        String token = redisCache.getCacheObject(key);
        if(StringUtils.isNotEmpty(token)){
            return token;
        }
        Map<String, Object> request = new HashMap<>();
        request.put("accessKey", accessKey);
        request.put("secretKey", secretKey);
        JSONObject jsonObject = HttpUtils.sendPost("https://aiob-open.baidu.com/api/v2/getToken", request);
        if(jsonObject.getInteger("code") != 200){
            throw new BaseException(jsonObject.getString("msg"));
        }
        JSONObject data = jsonObject.getJSONObject("data");
        token = data.getString("accessToken");
        redisCache.setCacheObject(key, token, data.getLongValue("expiresTime"), TimeUnit.MINUTES);
        return token;
    }

}
