package org.jeecg.modules.utils;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import org.apache.commons.codec.digest.DigestUtils;
import org.json.JSONObject;
import org.json.JSONException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class WeChatJSSDK {


    /**
     * 微信公众号-appid - 天都服务
     */

    private static final String APP_ID =  "wx2cc6f138b02196e3";

    /**
     * 微信公众号-appSecret- 天都服务
     */

    private static final String APP_SECRET = "a5320a3c5ed0f90dfb9e0ead79d32945";

    private static String accessToken = null; // 用于缓存access_token
    private static String jsapiTicket = null; // 用于缓存jsapi_ticket

    // 获取access_token
    private static String getAccessToken() throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
        String response = null; // 假设sendGet方法会返回响应字符串
        try {
            response = sendGet(url, "UTF-8"); // 调用你的sendGet方法获取响应
            if (response != null && !response.isEmpty()) {
                org.json.JSONObject jsonObject = new JSONObject(response); // 解析JSON字符串
                accessToken = jsonObject.getString("access_token"); // 提取access_token
                // 这里可以添加逻辑来缓存accessToken
            }
        } catch (JSONException e) {
            e.printStackTrace(); // 打印JSON解析异常
        } catch (Exception e) {
            e.printStackTrace(); // 打印其他异常
        }

        return accessToken;
    }

    // 获取jsapi_ticket
    private static String getJsApiTicket() throws Exception {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
        jsapiTicket = sendGet(url, "UTF-8");
        System.out.println("jsapiTicket=========="+jsapiTicket);
        return jsapiTicket;
    }

    // 发送GET请求并获取响应
    private static String sendGet(String url, String encoding) throws Exception {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        connection.disconnect();
        return content.toString();
    }

    // 生成签名
    public static Map<String, Object> getSignPackage(String url) throws Exception {
        String jsapiTicket = getJsApiTicket();
        org.json.JSONObject jsonObject = new JSONObject(jsapiTicket); // 解析JSON字符串
        jsapiTicket = jsonObject.getString("ticket"); // 提取access_token


        String nonceStr = createNonceStr();
        long timestamp = System.currentTimeMillis() / 1000;

        String string1 = "jsapi_ticket=" + jsapiTicket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" + url; // 确保URL是编码过的

        String signature = sha1(string1);

        Map<String, Object> ret = new TreeMap<>();
        ret.put("appId", APP_ID);
        ret.put("timestamp", timestamp);
        ret.put("nonceStr", nonceStr);
        ret.put("signature", signature);
        ret.put("jsapi_ticket", jsapiTicket);
        ret.put("url",url);

        return ret;
    }

    // 生成随机字符串
    private static String createNonceStr() {
        return String.valueOf((long) (Math.random() * 100000000));
    }

    // SHA1加密
    private static String sha1(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] messageDigest = md.digest(input.getBytes("UTF-8"));
        StringBuilder hexString = new StringBuilder();
        for (byte b : messageDigest) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }



}

