package com.jeequan.jeepay.thirdparty.service.push;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.cache.RedisUtil;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.interfaces.push.IBaiduBceService;
import com.jeequan.jeepay.core.model.DBBaiduBceConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class BaiduBceService implements IBaiduBceService {

    @Override
    public String getBaiduBceToken(DBBaiduBceConfig baiduBceConfig) {

        String cacheKey = CS.BAIDU_TOKEN_CACHE_KEY + "_" + baiduBceConfig.getBaiduBceAppKey();
        String accessToken = RedisUtil.getString(cacheKey);
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }

        String param = "grant_type=client_credentials&client_id="+ baiduBceConfig.getBaiduBceAppKey() + "&client_secret=" + baiduBceConfig.getBaiduBceAppSecret();
        log.info("百度语音请求地址 url = {}", DBBaiduBceConfig.BAIDU_OAUTH_URL + param);
        try {
            String responseStr = HttpUtil.post(DBBaiduBceConfig.BAIDU_OAUTH_URL + param, new HashMap<>(), 60000);
            log.info("百度语音响应 response = {}", responseStr);

            if (StringUtils.isNotBlank(responseStr)) {
                JSONObject obj = JSONObject.parseObject(responseStr);

                accessToken = obj.getString("access_token");

                //保存token
                RedisUtil.setString(cacheKey, accessToken, CS.BAIDU_TOKEN_TIME, TimeUnit.DAYS);
                return accessToken;
            }
        }catch(Exception e){
            log.error("获取token失败", e);
        }
        return null;
    }

    @Override
    public void clearBaiduBceTokenCache(DBBaiduBceConfig baiduBceConfig) {

        String cacheKey = CS.BAIDU_TOKEN_CACHE_KEY + "_" + baiduBceConfig.getBaiduBceAppKey();
        String accessToken = RedisUtil.getString(cacheKey);
        if (StringUtils.isNotBlank(accessToken)) {
            RedisUtil.del(cacheKey);
            log.info("百度token已清除，appKey={}", baiduBceConfig.getBaiduBceAppKey());
        }
    }


}