package com.ama.core.architecture.util

import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.security.MessageDigest

object MD5Util {

    fun md5(input: String): String? {
        return try {
            val messageDigest = MessageDigest.getInstance("MD5")
            val digestBytes = messageDigest.digest(input.toByteArray(Charsets.UTF_8))
            val hexString = StringBuilder()
            for (b in digestBytes) {
                val hex = Integer.toHexString(0xFF and b.toInt())
                if (hex.length == 1) {
                    hexString.append('0')
                }
                hexString.append(hex)
            }
            hexString.toString()
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    /*fun md5ForWithDraw(input: String): String? {
        return try {
            val messageDigest = MessageDigest.getInstance("MD5")
            val digestBytes = messageDigest.digest(input.toByteArray(Charsets.UTF_8))
            val hashValue = digestBytes.hashCode()



            val hexString = StringBuilder()
            for (b in digestBytes) {
                val hex = Integer.toHexString(0xFF and b.toInt())
                if (hex.length == 1) {
                    hexString.append('0')
                }
                hexString.append(hex)
            }
            hexString.toString()
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }*/



    fun md5ForWithDraw(pOriginal: String): String {
        val bytes = pOriginal.toByteArray(StandardCharsets.UTF_8)
        val digest = MessageDigest.getInstance("MD5").digest(bytes)
        return digest.joinToString("") { "%02x".format(it.toInt() and 0xFF) }
    }



    /**
     * MD5加密函数
     * @param original 原始字符串
     * @param charsetName 字符编码名称，默认为"UTF-8"
     * @return 返回32位小写的MD5哈希字符串
     */
    fun md5ForWithDraw2(pOriginal: String): String {
        val bytes = pOriginal.toByteArray(Charset.forName("UTF-8"))
        val digest = MessageDigest.getInstance("MD5").digest(bytes)
        return digest.joinToString("") {"%02".format(it.toInt() and 0xFF) }

        /*// 元宝
        val bytes = input.toByteArray(charset("UTF-8")) // 按指定字符集转换为字节数组[6](@ref)
        val digest = MessageDigest.getInstance("MD5") // 获取MD5实例[6,7,8](@ref)
        val hashBytes = digest.digest(bytes) // 计算MD5哈希值[6,7,8](@ref)

        // 将字节数组转换为十六进制字符串[6,8](@ref)
        val hexString = StringBuilder()
        for (byte in hashBytes) {
            val hex = (byte.toInt() and 0xFF).toString(16) // 确保无符号转换[6](@ref)
            if (hex.length == 1) {
                hexString.append('0') // 单数位前补零[6,8](@ref)
            }
            hexString.append(hex)
        }
        return hexString.toString().lowercase()*/

        /*  // 百度
        val md = MessageDigest.getInstance("MD5")
        val inputBytes = input.toByteArray(StandardCharsets.UTF_8)
        val hashBytes = md.digest(inputBytes)

        return hashBytes.joinToString("") { byte -> "%02x".format(byte) }*/


        /* // 豆包
        // 1. 对应C#: Encoding.GetEncoding(pCharSet).GetBytes("utf-8")
        val charset = Charset.forName("UTF-8")
        val tData = "utf-8".toByteArray(charset)

        // 2. 对应C#: new MD5CryptoServiceProvider().ComputeHash(tData)
        val md5 = MessageDigest.getInstance("MD5")
        val tHash = md5.digest(tData)

        // 3. 对应C#: 循环拼接两位小写十六进制（x2）
        val tResult = StringBuilder(32) // 预初始化容量32，与C#一致
        for (i in tHash.indices) {
            // 对应C#: tHash[i].ToString("x2") —— 格式化为两位十六进制（不足补0）
            tResult.append(String.format("%02x", tHash[i]))
        }

        // 4. 对应C#: ToString().ToLower()（注：%02x本身已是小写，此处保持ToLower()与原代码一致）
        return tResult.toString().lowercase()
        */

    }


    /*
    private static string GetMD5(string pOriginal)
    {
        var tData = Encoding.GetEncoding(pCharSet).GetBytes("utf-8");
        var tHash = new MD5CryptoServiceProvider().ComputeHash(tData);
        var tResult = new StringBuilder(32);
        for (int i = 0; i < tHash.Length; i++)
        {
            tResult.Append(tHash[i].ToString("x2"));
        }
        return tResult.ToString().ToLower();
    }*/

}