package com.emoon.openplatform.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.UUID;

public class MD5SignGenerateExample {
    // 项目私钥（双方一致，仅用于签名/验签）
    private static final String PRIVATE_KEY = "Einv5Re2D0EBbET7";

    public static void main(String[] args) throws Exception {
        // 1. 生成基础参数
        String requestId = UUID.randomUUID().toString(); // 示例：f81d4fae-7dec-11d0-a765-00a0c91e6bf6
        System.out.println("requestId = " + requestId);
        String timestamp = String.valueOf(System.currentTimeMillis()); // 示例：1740672000000
        System.out.println("timestamp = " + timestamp);
        // 2. 构造payload并转为紧凑JSON字符串
        String payload = "{\"patientBasicInfo\": {\"name\": \"张三\",\"gender\": \"男\",\"age\": 32,\"idCard\": \"510322199310030711\",\"occupation\": \"IT工程师\",\"visitTime\": \"2025年3月1日\",\"clinicNo\": \"08111044272\",\"patientId\": \"2014101101700\",\"visitTimes\": 48},\"chiefComplaint\": \"最近1周，每天晚上睡觉时咳嗽加重，白天基本不咳，严重影响睡眠\",\"presentIllness\": {\"symptomDetails\": {\"coughTime\": \"夜间入睡后1-2小时开始，持续至凌晨，白天偶有轻微咳嗽\",\"coughNature\": \"干咳为主，无痰或少量白色黏痰\",\"accompanyingSymptoms\": \"无发热、胸痛、呼吸困难，但咳嗽时偶有喉咙发痒\",\"inducingFactors\": \"平躺时咳嗽加重，坐起后稍缓解\"},\"lifeHistory\": {\"workEnv\": \"长期在空调房间办公，近期办公室装修\",\"livingHabits\": \"吸烟史5年，每日约10支，近期未戒烟\",\"sleep\": \"因咳嗽每晚惊醒3-4次，睡眠质量差\"},\"pastHistory\": {\"chronicDisease\": \"无慢性呼吸系统疾病史（如哮喘、慢性支气管炎）\",\"allergyHistory\": \"花粉过敏\"},\"physicalExam\": {\"temperature\": \"36.5℃\",\"heartRate\": \"72次/分\",\"respiratoryRate\": \"18次/分\",\"lungAuscultation\": \"双肺呼吸音清，未闻及干湿啰音\",\"throatExam\": \"咽部轻度充血，扁桃体无肿大\"}},\"supplementData\": {\"bloodRoutine\": \"白细胞计数 6.5×10^9/L，中性粒细胞比例60%，淋巴细胞比例 35%，嗜酸性粒细胞比例 3%\",\"chestXrayReport\": \"双肺纹理清晰，未见明显渗出影，心影大小正常，膈面光滑\",\"recentMedicalRecords\": \"近3个月无其他就诊记录\",\"recentMedication\": \"未服用任何止咳、抗过敏药物\"},\"mediaReference\": {\"chestXray\": \"${media.media-chest-xray-001}\",\"bloodRoutineImg\": \"${media.media-blood-routine-001}\"}}";

        // 3. 拼接待签名字符串（核心：RequestId+Timestamp+payload+私钥）
        String signStr = String.format("%s&%s&%s&%s", requestId, timestamp, payload, PRIVATE_KEY);
        System.out.println("待签名字符串：" + signStr);
        // 示例输出：f81d4fae-7dec-11d0-a765-00a0c91e6bf61740672000000{"patientBasicInfo":{"name":"张三","gender":"男","age":32},"chiefComplaint":"夜间干咳1周"}PRIVATE_KEY_001

        // 4. MD5哈希计算（UTF-8编码）
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] md5Bytes = md.digest(signStr.getBytes("UTF-8"));
        // 5. 转为32位小写字符串
        String sign = new BigInteger(1, md5Bytes).toString(16);
        while (sign.length() < 32) {
            sign = "0" + sign; // 补全32位
        }
        sign = sign.toLowerCase();
        System.out.println("最终签名（X-Emoon-Sign）：" + sign);
        // 示例输出：5f4dcc3b5aa765d61d8327deb882cf99（模拟值，实际以计算为准）
    }
}
