package cn.com.poc.thirdparty.resource.demand.member.service.impl;

import cn.com.poc.common.service.RedisService;
import cn.com.poc.thirdparty.resource.demand.member.api.DemandAuthApi;
import cn.com.poc.thirdparty.resource.demand.member.entity.DemandAuthResponse;
import cn.com.poc.thirdparty.resource.demand.member.entity.DemandAuthResult;
import cn.com.poc.thirdparty.resource.demand.member.service.DemandAuthService;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import cn.com.yict.framemax.frame.service.FmxParamConfigService;
import cn.hutool.core.lang.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author alex.yao
 * @date 2023/5/17
 **/
@Service
public class DemandAuthServiceImpl implements DemandAuthService {

    final private String TOKEN_KEY = "demand_access_token";

    final private String DEMAND_PROJECT_KEY_PARAM_CODE = "dg.tools.project.key";

    final private String DEMAND_PROJECT_SECRET_PARAM_CODE = "dg.tools.project.secret";

    final private Logger logger = LoggerFactory.getLogger(DemandAuthService.class);

    @Resource
    private DemandAuthApi demandAuthApi;

    @Resource
    private RedisService redisService;

    @Resource
    private FmxParamConfigService fmxConfigService;

    @Override
    public String getToken() {
        if (null == redisService.get(TOKEN_KEY)) {
            String projectKey = fmxConfigService.getParam(DEMAND_PROJECT_KEY_PARAM_CODE);
            String projectSecret = fmxConfigService.getParam(DEMAND_PROJECT_SECRET_PARAM_CODE);
            Assert.notBlank(projectKey);
            Assert.notBlank(projectSecret);
            DemandAuthResponse response = new DemandAuthResponse();
            response.setProjectKey(projectKey);
            response.setProjectSecret(projectSecret);
            DemandAuthResult demandAuthResult = demandAuthApi.getToken(response);
            if (demandAuthResult == null || demandAuthResult.getToken() == null) {
                throw new I18nMessageException("exception/failed.to.obtain.token");
            }
            //计算过期时长
            long now = System.currentTimeMillis() / 1000L;
            long exp = demandAuthResult.getExpires() - now;
            String token = "Bearer " + demandAuthResult.getToken();
            logger.info("demand token：{}", token);
            redisService.set(TOKEN_KEY, token, exp);
            return token;
        }
        return redisService.get(TOKEN_KEY).toString();
    }
}
