package com.emoon.tongue.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.emoon.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 测试用：生成可直接跳转的舌诊 H5 拍摄页 URL
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class testController {

    private static final String BASE_URL = "https://tongue.hanmc.online";
    private static final String SHOOT_PATH = "/tongue-diagnosis/h5/v1/shoot";

    @GetMapping("/tongue-shoot-url")
    public R<String> getTongueShootUrl() {
        try {
            long ts = System.currentTimeMillis();
            String patientId = "GH" + String.valueOf(ts).substring(0, Math.min(11, String.valueOf(ts).length()));

            // 1. 构建基础参数
            Map<String, String> params = new HashMap<>();
            params.put("project_id", "HOSP001");
            params.put("patient_id", patientId);
            params.put("version", "v1.0");
            params.put("timestamp", String.valueOf(ts));

            // 2. 构建 biz_params 的 JSON 并放入 params
            Map<String, String> biz = new HashMap<>();
            biz.put("patient_name", "测试患者");
            biz.put("patient_age", "35");
            biz.put("patient_gender", "1");
            biz.put("mari_code", "1");
            biz.put("patient_home_addr", "甘肃省兰州市");
            biz.put("patient_height", "170");
            biz.put("patient_weight", "65");
            params.put("biz_params", JSONUtil.toJsonStr(biz));

            // 3. 按参数名 ASCII 升序排序
            Map<String, String> sorted = new TreeMap<>(params);

            // 4. 拼接签名源字符串
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> e : sorted.entrySet()) {
                if (sb.length() > 0) sb.append("&");
                sb.append(e.getKey()).append("=").append(e.getValue());
            }
            String signSource = sb.toString();

            // 5. MD5 得到 sign，拼到 params
            String sign = SecureUtil.md5(signSource).toUpperCase();
            params.put("sign", sign);

            // 6. 拼最终 URL（query 需 URLEncode）
            StringBuilder urlSb = new StringBuilder(BASE_URL).append(SHOOT_PATH).append("?");
            boolean first = true;
            for (Map.Entry<String, String> e : params.entrySet()) {
                if (!first) urlSb.append("&");
                urlSb.append(URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8));
                urlSb.append("=").append(URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8));
                first = false;
            }
            String url = urlSb.toString();
            log.info("生成舌诊拍摄页 URL: {}", url);
            return R.ok(url);
        } catch (Exception e) {
            log.error("生成舌诊拍摄页 URL 失败", e);
            return R.fail("生成 URL 失败: " + e.getMessage());
        }
    }
}
