package com.qryord.mp.common;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 阿里云Util
 *
 * @author biandan
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "wx.miniapp.appid")
public class WxUtil {
    private static String appId;
    private static String appKey;

    @Value("${wx.miniapp.appid}")
    public void setAppId(String appId) {
        WxUtil.appId = appId;
    }

    @Value("${wx.miniapp.secret}")
    public void setAppKey(String appKey) {
        WxUtil.appKey = appKey;
    }

    /**
     * 获取微信AccessToken
     *
     * @param wxAppId  微信小程序AppId
     * @param wxAppKey 微信小程序AppKey
     * @return accessToken
     */
    public static String getWxAccessToken(String wxAppId, String wxAppKey) throws BusinessException {
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxAppId + "&secret=" + wxAppKey;
        try {
            URL url = new URL(tokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            // 设置通用的请求属性
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setUseCaches(false);
            connection.setDoOutput(true);
            connection.setDoInput(true);

            // 得到请求的输出流对象
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes("");
            out.flush();
            out.close();

            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in;
            if (tokenUrl.contains("nlp"))
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
            else
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder result = new StringBuilder();
            String getLine;
            while ((getLine = in.readLine()) != null) {
                result.append(getLine);
            }
            in.close();

            JSONObject jsonObject = JSON.parseObject(result.toString());
            if (jsonObject.containsKey("access_token")) {
                return jsonObject.getString("access_token");
            } else {
                log.error("token获取失败");
                throw new BusinessException("token获取失败");
            }
        } catch (Exception e) {
            log.error("token获取失败");
            throw new BusinessException(e.getMessage());
        }
    }
}
