package com.ssj.framework.basic.utils;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * 
 * 类名称：EncryptUtil<br>
 * 类描述：加密工具类<br>
 * @version v1.0
 *
 */
public class EncryptUtil {
    private static final Logger logger = LoggerFactory.getLogger(EncryptUtil.class);
    protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    protected static MessageDigest messagedigest = null;
    static {
        try {
            messagedigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.error("MD5FileUtil messagedigest初始化失败", e);
        }
    }

    /**
     * 获取文件的MD5值
     * @param file
     * @return
     */
    public static String getFileMD5String(File file) {
        String fileMD5 = "未知";
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            FileChannel ch = in.getChannel();
            MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            messagedigest.update(byteBuffer);
            fileMD5 = bufferToHex(messagedigest.digest());
            IOUtils.closeQuietly(in);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(in);
        }
        return fileMD5;
    }

    /**
     * 获取文件的MD5值
     * @param file
     * @return
     */
    public static String getFileMD5String(MultipartFile fileItem) {
        String fileMD5 = "未知";
        try {
            byte[] uploadBytes = fileItem.getBytes();
            byte[] digest = messagedigest.digest(uploadBytes);
            String hashString = new BigInteger(1, digest).toString(32);
            fileMD5 = hashString.toUpperCase();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileMD5;
    }

    /**
     * 通过字符串生成MD5
     * @param s
     * @return
     */
    public static String getMD5String(String s) {
        return getMD5String(s.getBytes());
    }

    /**
     * 获取一个字符串UUID
     * @return
     */
    public static String getUUIDString() {
        String uuid = UUID.randomUUID().toString();
        // 去掉“-”符号
        return uuid.replace("-", "");
    }



    /**
     * 通过byte[]生成MD5
     * @param s
     * @return
     */
    public static String getMD5String(byte[] bytes) {
        messagedigest.update(bytes);
        return bufferToHex(messagedigest.digest());
    }

    /**
     * 通过byte生成MD5
     * @param s
     * @return
     */
    private static String bufferToHex(byte bytes[]) {
        return bufferToHex(bytes, 0, bytes.length);
    }

    private static String bufferToHex(byte bytes[], int m, int n) {
        StringBuffer stringbuffer = new StringBuffer(2 * n);
        int k = m + n;
        for (int l = m; l < k; l++) {
            appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }

    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
        char c0 = hexDigits[(bt & 0xf0) >> 4];
        char c1 = hexDigits[bt & 0xf];
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }

    /**
     * SHA1 加密
     * @param input
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String SHA1(String input) {
        StringBuffer sb = new StringBuffer();
        try {
            MessageDigest mDigest = MessageDigest.getInstance("SHA1");
            byte[] result = mDigest.digest(input.getBytes());
            for (int i = 0; i < result.length; i++) {
                sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}

