package com.greenorange.promotion.service.wechat.impl;



import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import com.greenorange.promotion.config.WxAccessToken;
import com.greenorange.promotion.service.wechat.WechatGetQrcodeService;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class WechatGetQrcodeServiceImpl implements WechatGetQrcodeService {


    private final static String ACCESS_TOKEN_KEY = "accessToken";

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @Schema(description = "小程序 appId")
    @Value("${wx.mini.appId}")
    private String appId;

    @Schema(description = "小程序 appSecret")
    @Value("${wx.mini.appSecret}")
    private String appSecret;


    /**
     * 获取接口调用凭据
     */
    @Override
    public WxAccessToken getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        String response = null;
        try {
            response = HttpUtil.get(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Gson gson = new Gson();
        WxAccessToken wxAccessToken = gson.fromJson(response, WxAccessToken.class);
        String access_token = wxAccessToken.getAccess_token();
        redisTemplate.opsForValue().set(ACCESS_TOKEN_KEY, access_token, 7200, TimeUnit.SECONDS);
        return wxAccessToken;
    }
}
