package com.ruoyi.api;

import com.ruoyi.common.utils.sign.HmacSha256Utils;
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 javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import java.util.Base64;

public class KadaPaymentJava {

    public static void main(String[] args) {

        String mid = "c70f1719017e290354017d1c101d0cc288d06ceb";
        String secret = "b0CH/+tVEsz+1j2mfBzd9Kgu6UylJxr0056TwTbkKfHWw9UW/6TaQyQHv+teBnGbqWy5ObaLUMvnrs9adpymebEqjI3ipNpJa7YPQbMYm0VGuYUEgeM+fjakhWuYx2XEVzmjdIvvfhNsfr2YHTmDUzwIKPbp/OJvfG9KhSPMzpw=";

        String url = "https://rapi.openkada.xyz/api/mcht/payment/submit";

        try {
            String body = "{\"amount\":\"600.00\",\"callbackUrl\":\"https://web.iqyjsnwv.com/api/pay/kada-callBack\",\"createTime\":1764435870000,\"currency\":\"PHP\",\"fee\":\"10.80\",\"netAmount\":\"589.20\",\"ref\":\"20251130kd941b62ef\",\"status\":\"COMPLETE\",\"txid\":\"2025113001048D4I0R59A7\",\"type\":\"PAYMENT\"}";
            String requestTime = String.valueOf(System.currentTimeMillis());
            requestTime = String.valueOf(System.currentTimeMillis());

            // signature_str = Request-Time + "." + body
            String signatureStr = "1764437188324" + "." + body;

            // HMAC-SHA256
            String signatureHex = HmacSha256Utils.hmacSha256To16Hex(signatureStr,secret);
            System.out.println("sign: " + signatureHex);

            // Authorization = Basic base64(mid:signature)
            String basic = mid + ":" + signatureHex;
            String authHeader = "Basic " + Base64.getEncoder().encodeToString(basic.getBytes());

            // HTTP request
            sendPost(url, body, requestTime, authHeader);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // ===== 构造请求体 JSON =====
    private static String buildRequestBody() {
        // 生成毫秒级时间戳 ref
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String now = sdf.format(new Date());
        int randomSuffix = new Random().nextInt(9000) + 1000;

        Map<String, Object> payer = new HashMap<>();
        payer.put("email", "");
        payer.put("name", "");
        payer.put("phone", "");
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
        String dateTime = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String orderNo = dateTime + "kd" + uuid;
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("amount", 600);
        map.put("pm", "QRPH");
        map.put("ref", orderNo);
        map.put("payer", payer);
        map.put("redirect", "https://undressing.top/recharge");
        map.put("callbackUrl", "https://undressing.top/api/pay/kada-callBack");

        return JSON.toJSONString(map);
    }

    // ===== HMAC-SHA256 计算 hex =====
    private static String hmacSha256ToHex(String secret, String data) throws Exception {
        Mac sha256Hmac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        sha256Hmac.init(secKey);
        byte[] hash = sha256Hmac.doFinal(data.getBytes(StandardCharsets.UTF_8));

        // 转16进制
        StringBuilder sb = new StringBuilder(hash.length * 2);
        for (byte b : hash) sb.append(String.format("%02x", b));
        return sb.toString();
    }

    // ===== 发起 POST 请求 =====
    private static void sendPost(String url, String body, String requestTime, String authHeader) throws Exception {

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);

        post.setHeader("Content-Type", "application/json");
        post.setHeader("Authorization", authHeader);
        post.setHeader("Request-Time", requestTime);

        post.setEntity(new StringEntity(body, "UTF-8"));

        System.out.println("=== Sending Request ===");
        System.out.println("URL: " + url);
        System.out.println("Body: " + body);
        System.out.println("Authorization: " + authHeader);
        System.out.println("Request-Time: " + requestTime);

        CloseableHttpResponse response = client.execute(post);

        try {
            int status = response.getStatusLine().getStatusCode();
            String respString = EntityUtils.toString(response.getEntity(), "UTF-8");

            System.out.println("HTTP Status: " + status);
            System.out.println("Response: " + respString);
        } finally {
            response.close();
        }
    }

}