package com.cnd3b.utility.qywechat.base;

import com.alibaba.fastjson.JSONObject;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class GetAccessToken {
    public static String accessToken = "";
    public static long lasttime = 0;

    public static String get() {
        long nowtime = System.currentTimeMillis();
        //间隔时间， 单位（分钟）
        long Interval = (nowtime - lasttime) / (1000 * 60);
        if (Interval >= 30) {
            accessToken = getToken();
            lasttime = nowtime;
        }
        return accessToken;
    }

    private static String getToken() {
        /**
         * 如果企业微信参数未设置，则从数据库中查询获取
         */
       Parameter.initParameter();

        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="
                + Parameter.CorpID + "&corpsecret=" + Parameter.corpsecret;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet
                    .openConnection();

            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, StandardCharsets.UTF_8);

            JSONObject demoJson = JSONObject.parseObject(message);
            accessToken = demoJson.getString("access_token");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }
}
