package org.dromara.web.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * 微信小程序工具类
 * @author Maosw
 */
public class WxXcxUtils {

    private static final String APPID = "wxed96e8fe10ea8992";
    private static final String SECRET = "e9399ee3cc4f6f335cd91b1935c19c36";
    private static final String TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    /**
     * 获取access_token
     */
    public static String getAccessToken(){
        String url = TOKEN_URL + "?grant_type=client_credential&appid=" + APPID + "&secret=" + SECRET;
        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("access_token");
    }

    /**
     * 获取jsapi_ticket
     */
    public static String getJsapiTicket() {
        String accessToken = getAccessToken();
        String url = TICKET_URL + "?access_token=" + accessToken + "&type=jsapi";
        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("ticket");
    }

    /**
     * 生成签名
     * @param url 当前网页的URL
     * @return 签名信息
     */
    public static Map<String, String> generateSignature(String url) {
        if (StringUtils.isEmpty(url)) {
            throw new IllegalArgumentException("URL不能为空");
        }

        // 获取jsapi_ticket
        String jsapiTicket = getJsapiTicket();

        // 生成随机字符串
        String nonceStr = RandomUtil.randomString(16);

        // 生成时间戳
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

        // 准备签名参数
        Map<String, String> params = new TreeMap<>();
        params.put("jsapi_ticket", jsapiTicket);
        params.put("noncestr", nonceStr);
        params.put("timestamp", timestamp);
        params.put("url", url);

        // 拼接字符串
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        String string1 = stringBuilder.substring(0, stringBuilder.length() - 1);

        // 生成签名
        String signature = DigestUtil.sha1Hex(string1);

        // 返回结果
        Map<String, String> result = new HashMap<>();
        result.put("timestamp", timestamp);
        result.put("nonceStr", nonceStr);
        result.put("signature", signature);
        result.put("appId", APPID);

        return result;
    }

    public static JSONObject getUserPhoneNumber(String code){
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken;

        JSONObject json = new JSONObject();
        json.put("code", code);
        String result = HttpRequest.post(url).body(json.toString()).execute().body();
        return JSONObject.parseObject(result);
    }

}
