package com.ycwl.basic.utils;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;

public class WxMpUtil {
    private static final String GET_WXA_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacode?access_token=%s";
    private static final String GET_URL_LICK_URL = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=%s";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    private static String ACCESS_TOKEN = "";
    private static Date expireTime = new Date();

    private static String getAccessToken(String appId, String appSecret) {
        if (ACCESS_TOKEN != null && !ACCESS_TOKEN.isEmpty()) {
            if (expireTime.getTime() > System.currentTimeMillis()) {
                return ACCESS_TOKEN;
            }
        }
        String url = String.format(ACCESS_TOKEN_URL, appId, appSecret);
        String response = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(response);
        ACCESS_TOKEN = jsonObject.getString("access_token");
        expireTime = new Date(System.currentTimeMillis() + jsonObject.getInteger("expires_in") * 1000 / 2);
        return ACCESS_TOKEN;
    }

    public static void generateWXAQRCode(String appId, String appSecret, String envVersion, String path, String filePath) throws Exception {
        String url = String.format(GET_WXA_CODE_URL, getAccessToken(appId, appSecret));
        JSONObject json = new JSONObject();
        json.put("env_version", envVersion);
        json.put("path", path);
        json.put("width", 1000);

        try (HttpResponse response = HttpUtil.createPost(url).body(json.toJSONString()).header("Content-Type", "application/json").execute()) {
            if (response.getStatus() != 200) {
                throw new Exception("获取小程序二维码失败，原因为：" + response.body());
            }
            InputStream inputStream = response.bodyStream();
            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                int len;
                byte[] buffer = new byte[1024];
                while ((len = inputStream.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
            }
        }
    }

    public static String generateUrlLink(String appId, String appSecret, String path, String query) throws Exception {
        String url = String.format(GET_URL_LICK_URL, getAccessToken(appId, appSecret));
        JSONObject json = new JSONObject();
        json.put("path", path);
        json.put("query", query);
        
        try (HttpResponse response = HttpUtil.createPost(url).body(json.toJSONString()).header("Content-Type", "application/json").execute()) {
            String responseStr = response.body();

            JSONObject jsonObject = JSONObject.parseObject(responseStr);
            if (jsonObject.getInteger("errcode") != 0) {
                throw new Exception("获取url_link失败，原因为：" + jsonObject.getString("errmsg"));
            }
            return jsonObject.getString("url_link");
        }
    }

    public static void main(String[] args) throws Exception {
        generateWXAQRCode("wxe7ff26af70bfc37c", "5252fbbc68513bc77b7cc0052b9f9695", "trial", "pages/home/index?scenicId=3972138108618674176", "ljh_t.jpg");
    }
}