package com.huimv.employment;

import java.security.MessageDigest;
import java.util.*;

public class ApiSignUtil {

    /**
     * 构建请求签名
     *
     * @param params    请求参数 Map（query 参数，key=参数名，value=参数值）
     * @param timestamp 时间戳（毫秒）
     * @param secret    平台分配的 appPublicKey
     * @return 32位小写MD5签名字符串
     */
    public static String buildSign(Map<String, String> params, long timestamp, String secret) {
        // 1. 参数字典序排列（TreeMap 自动排序）
        TreeMap<String, String> sorted = new TreeMap<>(params);

        // 2. 拼接签名原串：k1=v1&k2=v2...&timestamp=xxx&key=secret
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : sorted.entrySet()) {
            if (entry.getValue() != null && !entry.getValue().isEmpty()) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        sb.append("timestamp=").append(timestamp);
        sb.append("&key=").append(secret);

        // 3. MD5 → 32位小写十六进制
        return md5(sb.toString());
    }

    private static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(input.getBytes("UTF-8"));
            byte[] digest = md.digest();
            StringBuilder sb = new StringBuilder(digest.length * 2);
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("MD5 error", e);
        }
    }

    // ────────── 使用示例 ──────────

    public static void main(String[] args) {
        String appKey = "AK_eaf449b6fb9f21";
        String secret = "70c1b93ae1df463809ed3b41156e4791";

        // 示例1：任务大厅列表
        Map<String, String> hallParams = new LinkedHashMap<>();
        hallParams.put("current", "1");
        hallParams.put("size", "108");
//        hallParams.put("occupationCode", "OCC001");

        long ts = System.currentTimeMillis();
        String sign = buildSign(hallParams, ts, secret);

        System.out.println("X-App-Key   : " + appKey);
        System.out.println("X-Timestamp : " + ts);
        System.out.println("X-Sign      : " + sign);

        // 示例2：任务详情（无Query参数）
        Map<String, String> emptyParams = new LinkedHashMap<>();
        long ts2 = System.currentTimeMillis();
        String sign2 = buildSign(emptyParams, ts2, secret);

        System.out.println("\n[任务详情] X-Timestamp: " + ts2);
        System.out.println("[任务详情] X-Sign     : " + sign2);
    }
}