package com.cnooc.expert.common.utils;

import cn.hutool.core.util.RandomUtil;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Map;

@Slf4j
public class SmsUtil {


    /**
     * 生成6位随机验证码
     */
    public static String generateVerificationCode() {
        return RandomUtil.randomNumbers(6);
    }

    /**
     * 构建 Redis 缓存键
     */
    public static String buildCacheKey(String phone) {
        return "sms:code:" + phone;
    }

    /**
     * 构建短信内容
     */
    public static String buildSmsContent(String code) {
        return "福建通信行业融合创新服务平台，您的验证码是：" + code + "（有效期为2分钟），请勿泄露给他人，如非本人操作，请忽略此消息。";
    }
    /**
     * 将请求体转换为 Base64 编码的 JSON 字符串
     */
    public static String encodeRequestBodyToBase64(Map<String, String> requestBody) {
        String jsonString = JsonUtils.toJsonString(requestBody);
        return Base64.getEncoder().encodeToString(jsonString.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 处理响应结果
     */
    public static boolean handleResponse(String response) throws Exception {
        JsonNode jsonNode = JsonUtils.parseObject(response, JsonNode.class);
        if (jsonNode.get("success").asBoolean()) {
            System.out.println("云MAS业务平台短信验证码发送成功");
            log.info("云MAS业务平台短信验证码发送成功");
            return true;
        } else {
            System.out.println("云MAS业务平台短信验证码发送失败");
            log.info("云MAS业务平台短信验证码发送失败");
            return false;
        }
    }

    public static String calculateMac(String ecName, String apld, String secretKey, String mobiles, String content, String sign, String addSerial) {
        try{
            // 根据文档中的规则计算MAC
            StringBuilder sb = new StringBuilder();
            sb.append(ecName).append(apld).append(secretKey).append(mobiles).append(content).append(sign).append(addSerial);
            return DigestUtils.md5Hex(sb.toString());
        } catch (Exception e) {
            throw new RuntimeException("生成MAC签名失败", e);
        }
    }

    public static String generateMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("生成MAC签名失败", e);
        }
    }
}
