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;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

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";
    public static final String  GET_USER_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s";
    private static final Map<String, String> tokens = new ConcurrentHashMap<>();
    private static final Map<String, Date> expireTimes = new ConcurrentHashMap<>();

    private static String getAccessToken(String appId, String appSecret) {
        if (expireTimes.containsKey(appId)) {
            Date expireTime = expireTimes.get(appId);
            if (expireTime.getTime() < System.currentTimeMillis()) {
                tokens.remove(appId);
            }
        } else {
            tokens.remove(appId);
        }
        return tokens.computeIfAbsent(appId, (k) -> {
            String url = String.format(ACCESS_TOKEN_URL, appId, appSecret);
            String response = HttpUtil.get(url);
            JSONObject jsonObject = JSONObject.parseObject(response);
            String token = jsonObject.getString("access_token");
            Date expireTime = new Date(System.currentTimeMillis() + jsonObject.getInteger("expires_in") * 1000 / 2);
            expireTimes.put(appId, expireTime);
            return 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 String getUserPhone(String appId, String appSecret, String code) throws Exception {
        String url = String.format(GET_USER_PHONE_URL, getAccessToken(appId, appSecret));
        JSONObject json = new JSONObject();
        json.put("code", code);

        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("获取用户手机号失败，原因为：" + jsonObject.getString("errmsg"));
            }
            return jsonObject.getJSONObject("phone_info").getString("phoneNumber");
        }
    }

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