package com.nantian.cloud.dbcapp.unit;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * MD5加密类（封装jdk自带的md5加密方法）
 */
public class MD5Util
{

    public static String encrypt(String source)
    {
        return encodeMd5(source.getBytes());
    }

    private static String encodeMd5(byte[] source)
    {
        try
        {
            return bytesToHexString(MessageDigest.getInstance("MD5").digest(source));
        }
        catch(NoSuchAlgorithmException e)
        {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }


    public static String getDigest(String... str)
    {
        String sRet = null;
        int count = str.length;
        String value = null;
        StringBuffer buffer = new StringBuffer();
        for(int i = 0; i < count; i++)
        {
            value = str[i];
            if(value != null)
            {
                buffer.append(value);
            }
        }
        try
        {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(buffer.toString().getBytes("UTF-8"));
            sRet = bytesToHexString(messageDigest.digest());
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return sRet;
    }

    public static String getEnergyDateDigest(String... str)
    {
        String sRet = null;
        //天数据截取到 天 例如：2022-02-20, 月数据截取到月，如：例如：2022-02
        if("1".equals(str[3])){
            sRet = str[0] + str[1] + str[2].substring(0,10);
        }else if("2".equals(str[3])){
            sRet = str[0] + str[1] + str[2].substring(0,7);
        }else if ("3".equals(str[3])){
            sRet = str[0] + str[1] + str[2].substring(0,5);
        }
        return sRet;
    }

    private static String bytesToHexString(byte[] bArray)
    {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for(int i = 0; i < bArray.length; i++)
        {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if(sTemp.length() < 2)
            {
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }


}
