package com.icloud.server.wxserver;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
//import com.icloud.server.scala.pay.PayRealmName;
import com.icloud.server.scala.pay.PayRealmNameRepository;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;

@Component
public class AccessTokenAPI {
    @Autowired
    private PayRealmNameRepository payrealmnamerepository;

    // 获取微信公众号：access_token的接口地址（GET） 限2000（次/天）
    public final  String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    public  AccessToken getAccessToken1(String appid, String appsecret) {
        AccessToken accessToken = null;
        return accessToken;
    }

    /**临时String appid, String appsecret
     * 获取access_token
     */
    public  AccessToken getAccessToken(String appid,String appsecret) {
//        String ak = stringredistemplate.opsForValue().get(realmname+"_access_token");
//        String[] keys = ak.split("fangka");
//        String appid = "";
//        String appsecret = "";
//        List<PayRealmName> byUrlAndAndStatus = payrealmnamerepository.findByUrlAndAndStatus(realmname, 0);
//        if(byUrlAndAndStatus!=null){
//            appid = byUrlAndAndStatus.get(0).appid();
//            appsecret = byUrlAndAndStatus.get(0).secret();
//        }


        AccessToken accessToken = null;
        String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
        JSONObject jsonObject = HttpRequestUtil.httpRequest(requestUrl,"");
        if (jsonObject == null) {
            jsonObject = HttpRequestUtil.httpRequest(requestUrl,"");
        }
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new AccessToken();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInteger("expires_in"));

            } catch (JSONException e) {
                accessToken = null;
                // 获取token失败
            }
        }
        return accessToken;
    }

    /** 在redis获取accessToken,如果过期则生成新的
     * @Author : yang
     * @Date : 2022-05-01 2:11 AM
     * @Version : 2.1.2
     */
    public String getredis_accessToken(){

        return "";
    }
    /**生成新的accessToken存到redis中
     * @Author : yang
     * @Date : 2022-05-01 2:12 AM
     * @Version : 2.1.2
     */

    public String setredis_accessToken(){

        return "";
    }

}
