package com.example.base.extensions

import java.security.MessageDigest
import java.text.SimpleDateFormat
import java.util.Locale


/**
 * 获取字符串的 MD5
 */

fun String.getMD5LowerCase(): String {
    val hexString = StringBuilder()
    try {
        //1 创建一个提供信息摘要算法的对象，初始化为md5算法对象
        val md = MessageDigest.getInstance("MD5")

        //2 将消息变成byte数组
        val input = this.toByteArray(Charsets.UTF_8)

        //3 计算后获得字节数组,这就是那128位了
        val buff = md.digest(input)

        //4 把数组每一字节（一个字节占八位）换成16进制连成md5字符串
        for (b in buff) {
            hexString.append(String.format("%02X", b))
        }

    } catch (e: Exception) {
        e.printStackTrace()
    }
    return hexString.toString().lowercase(Locale.ROOT)   //转小写
}


fun String.toDoubleByTryCatch(): Double {
    return try {
        this.toDouble()
    } catch (e: Exception) {
        0.00
    }
}

fun String.utcToLocalTime(): Long {
    var time = 0L
    try {
        val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
        time = df.parse(this)?.time ?: 0
    } catch (e: java.lang.Exception) {
    }
    return time
}

fun String.utcToLocalTime2(): Long {
    var time = 0L
    try {
        val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'+0800'", Locale.CHINA)
        time = df.parse(this)?.time ?: 0
    } catch (e: java.lang.Exception) {
    }
    return time
}

fun String.maskPhoneNumber(): String {
    if (length != 11) {
        throw IllegalArgumentException("Invalid phone number length. Expected 11 digits.")
    }
    return substring(0, 3) + "****" + substring(7)
}
