package com.fs.company.util;

import com.alibaba.fastjson.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author：peicj
 * @Description: 机型检测接口调用工具类
 * @Date：2025/12/17 11:23
 */
public class DetectionPhoneModelVerifyUtil {

    //appid
    public static final long VERIFY_APPID = 100712;
    //secretkey
    public static final String SECRET_KEY = "faGf4dQNG3Tg";
    //机型校验地址
    public static final String VERIFY_URL = "http://zhijian.h12321.com:8086/mobile/model/check";
    //苹果链接
    public static String IOS_URL = "https://apps.apple.com/cn/app/%E8%8A%B3%E5%8D%8E%E6%9C%AA%E6%9D%A5/id6738688148";
    //安卓链接  芳华未来App应用商店下载链接 华为/小米/oppo/vivo/荣耀 https://m.malink.cn/s/2UZjMz
    public static String ANDROID_URL = "https://m.malink.cn/s/2UZjMz";


    /**
     * 获取请求体
     * @param phone 手机号
     * @return 请求体
     */
    public static String getRequestBody(String phone) {
            String timestamp = System.currentTimeMillis() + "";
            Map<String,Object> map = new HashMap<>();
            map.put("appId", VERIFY_APPID);
            map.put("timestamp", timestamp);
            map.put("sign", getSign(VERIFY_APPID, SECRET_KEY, timestamp));
            map.put("phones", phone);
        return JSONObject.toJSONString(map);
    }

    /**
     * 生成MD5签名字符串
     * @param input 输入字符串
     * @return 32位小写MD5字符串
     */
    public static String generateMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(input.getBytes());
            return bytesToHex(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

    /**
     * 字节数组转十六进制字符串
     * @param bytes 字节数组
     * @return 十六进制字符串(小写)
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 获取签名
     * @param appid appid
     * @param secretkey secretkey
     * @param timestamp 时间戳
     * @Description 签名md5小写32位加密字符串,Md5(appId+secretkey+timestamp)
     * @return String 签名
     */
    private static String getSign(long appid,String secretkey,String timestamp){
        return generateMD5(appid + secretkey + timestamp);
    }

}
