package com.ruoyi.api.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.ruoyi.api.constant.yz.CacheConstant;
import com.ruoyi.api.constant.yz.HttpConstant;
import com.ruoyi.api.downstream.YzResult;
import com.ruoyi.api.constant.yz.ApiConstant;
import com.ruoyi.api.exception.BusinessException;
import com.ruoyi.api.result.ResponseEnum;
import com.ruoyi.api.service.ITokenService;
import com.ruoyi.api.utils.RedisUtil;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.http.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class TokenServiceImpl implements ITokenService {
    @Value("${downstream.url}")
    private String url;

    @Value("${downstream.appKey}")
    private String appKey;

    @Value("${downstream.appSecret}")
    private String appSecret;

    @Autowired
    private RedisUtil redisUtil;

    private ObjectMapper objectWrapper = new ObjectMapper();

    @Override
    public String getToken() throws JsonProcessingException {
        String cacheKey = CacheConstant.DOWNSTREAM_CACHE_KEY;
        String token;
        if (!redisUtil.exists(cacheKey)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("app_key", appKey);
            jsonObject.put("app_secret", appSecret);

            String data = jsonObject.toString();
            String s = HttpUtils.sendPost(url + ApiConstant.GET_TOKEN, data);
            YzResult yzResult = objectWrapper.readValue(s, YzResult.class);

            // 检验是否为空
            if (ObjectUtils.isEmpty(yzResult)) {
                throw new BusinessException(ResponseEnum.TOKEN_NULL_ERROR);
            }
            // 检验是否成功
            if (yzResult.getCode() != HttpConstant.SUCCESS) {
                throw new BusinessException(yzResult.getMsg(), yzResult.getCode());
            }
            Map<String, Object> map = yzResult.getData();
            token = (String) map.get("token");
            Long expiresAt = (Long) map.get("expiresAt");
            redisUtil.set(cacheKey, token, expiresAt, TimeUnit.MICROSECONDS);
        } else {
            token = redisUtil.get(cacheKey);
        }

        return token;
    }
}
