package cn.com.poc.thirdparty.resource.baidu.service.impl;

import cn.com.poc.common.service.RedisService;
import cn.com.poc.thirdparty.resource.baidu.api.BaiduTokenAPI;
import cn.com.poc.thirdparty.resource.baidu.entity.result.BaiduTokenResult;
import cn.com.poc.thirdparty.resource.baidu.service.BaiduTokenService;
import cn.com.yict.framemax.core.config.Config;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author alex.yao
 * @date 2023/3/6
 **/
@Service
public class BaiduTokenServiceImpl implements BaiduTokenService {

    @Resource
    private BaiduTokenAPI baiduTokenApi;

    @Resource
    private RedisService redisService;

    @Override
    public String getToken() {
        String BAIDU_AI_CUSTOM_TOKEN = "BAIDU_TOKEN";
        String ACCESS_KEY_ID = Config.get("baidu.code.keyId");
        String SECRET_ACCESS_KEY = Config.get("baidu.code.keySecret");
        if (null == redisService.get(BAIDU_AI_CUSTOM_TOKEN)) {
            BaiduTokenResult token = baiduTokenApi.getToken(ACCESS_KEY_ID, SECRET_ACCESS_KEY);
            if (token == null || StringUtils.isNoneBlank(token.getError())) {
                throw new I18nMessageException("exception/failed.to.obtain.baidu.token");
            }
            redisService.set(BAIDU_AI_CUSTOM_TOKEN, token.getAccess_token(), token.getExpires_in());
        }
        return redisService.get(BAIDU_AI_CUSTOM_TOKEN).toString();
    }

    @Override
    public String getToken(String clientId, String clientSecret) {
        String BAIDU_AI_CUSTOM_TOKEN = "BAIDU_TOKEN_" + clientId;
        if (null == redisService.get(BAIDU_AI_CUSTOM_TOKEN)) {
            BaiduTokenResult token = baiduTokenApi.getToken(clientId, clientSecret);
            if (token == null || StringUtils.isNoneBlank(token.getError())) {
                throw new I18nMessageException("exception/failed.to.obtain.baidu.token");
            }
            redisService.set(BAIDU_AI_CUSTOM_TOKEN, token.getAccess_token(), token.getExpires_in());
        }
        return redisService.get(BAIDU_AI_CUSTOM_TOKEN).toString();
    }
}
