package org.dromara.elevator.service.message.impl;

import cn.hutool.http.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.elevator.domain.message.AuthBody;
import org.dromara.elevator.domain.message.AuthToken;
import org.dromara.elevator.service.message.AuthTokenService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 认证接口实现
 *
 * @author ym
 * @version 1.0.0
 * @date 2024-08-27 10:26
 */
@Service
public class AuthTokenServiceImpl implements AuthTokenService {

    @Value("${auth.token.url:https://ele.secp.com.cn/oauth/tooken.do}")
    private String authTokenUrl;
    /**
     * 三方认证token缓存key前缀
     */
    private static final String TOKEN_PREFIX = "third_auth_token:";

    @Override
    public AuthToken getToken(AuthBody authBody) {

        String tokenCacheKey = TOKEN_PREFIX + authBody.getClientId();
        AuthToken authToken= RedisUtils.getCacheObject(tokenCacheKey);
        if (Objects.nonNull(authToken)) {
            return authToken;
        }

        Map<String, Object> params = new HashMap<>();
        params.put("clientId", authBody.getClientId());
        params.put("clientSecret", authBody.getClientSecret());
        String url = StringUtils.isNotBlank(authBody.getRequestUrl()) ? authBody.getRequestUrl() : authTokenUrl;
        String res = HttpUtil.get(url, params);
        authToken = JsonUtils.parseObject(res, AuthToken.class);

        if (Objects.nonNull(authToken)) {
            // 三方token缓存
            RedisUtils.setCacheObject(TOKEN_PREFIX + authBody.getClientId(), authToken,
                Duration.ofSeconds(authToken.getObj().getExpires()));
        }
        return authToken;

    }
}
