package com.ycwl.basic.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.FileOutputStream;
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 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));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        JSONObject json = new JSONObject();
        json.put("env_version", envVersion);
        json.put("path", path);
        json.put("width", 1000);
        StringEntity entity = new StringEntity(json.toJSONString(), "utf-8");
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json");

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            if (response.getStatusLine().getStatusCode() != 200) {
                expireTime = new Date();
                throw new Exception("获取小程序码失败");
            }
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                byte[] bytes = EntityUtils.toByteArray(responseEntity);
                try (FileOutputStream fos = new FileOutputStream(filePath)) {
                    fos.write(bytes);
                }
            }
        }
    }

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