package com.eitc.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;










public class CommonUtils {


    /**
     * 文件流MD5加密
     * @param fis
     * @return
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    public static String calculateMD5(InputStream fis) throws IOException, NoSuchAlgorithmException {

        MessageDigest md = MessageDigest.getInstance("MD5");
        try {
            DigestInputStream dis = new DigestInputStream(fis, md);
            while (dis.read() != -1) {
            }
            byte[] digest = md.digest();
            return bytesToHex(digest);
        } catch (Exception ex) {

        }
        return null;
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }


    // Unicode 转中文，解决请求头传中文问题

    /**
     * Unicode 转中文
     * @param unicode
     * @return
     */
    public static String unicodeToChinese(String unicode) {
        StringBuilder sb = new StringBuilder();
        int i = -1;
        int pos = 0;

        while ((i = unicode.indexOf("\\u", pos)) != -1) {
            sb.append(unicode.substring(pos, i));
            if (i + 5 < unicode.length()) {
                pos = i + 6;
                sb.append((char) Integer.parseInt(unicode.substring(i + 2, i + 6), 16));
            }
        }
        if (pos < unicode.length()) {
            sb.append(unicode.substring(pos));
        }

        return sb.toString();
    }

    /**
     * 字符转unicode
     * @param input
     * @return
     */
    public static String toUnicode(String input) {
        StringBuilder sb = new StringBuilder();
        char[] chars = input.toCharArray();
        for (char c : chars) {
            sb.append("\\u").append(Integer.toHexString((int) c));
        }
        return sb.toString();
    }
}
