package com.fzm.mall.server.front.util;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.security.MessageDigest;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class Sha256Util {

	public static String sha256String(String data) {
		MessageDigest newDigest = DigestUtils.getSha256Digest();
		newDigest.update(data.getBytes());
		byte[] digest = newDigest.digest();
		String hexString = Hex.encodeHexString(digest);
		return hexString;
	}
	
	public static byte[] sha256(byte[] data) {
		MessageDigest newDigest = DigestUtils.getSha256Digest();
		newDigest.update(data);
		byte[] digest = newDigest.digest();
		return digest;
	}

	public static String generateCheckHash(String token, String timeStamp, String... datas) {
		StringBuilder sb = new StringBuilder();
		sb.append(token);
		for (String string : datas) {
			sb.append(string);
		}
		sb.append(timeStamp);

		return sha256String(sb.toString());
	}

	public static String generateCheckHashGet(String token, String currentTime, Map<String, Object> parameter) {
		StringBuilder sb = new StringBuilder();
		sb.append(token);
		if (parameter != null && parameter.size() != 0) {
			Set<Entry<String, Object>> entrySet = parameter.entrySet();
			for (Entry<String, Object> entry : entrySet) {
				String key = entry.getKey();
				Object value = entry.getValue();
				sb.append(key);
				sb.append("=");
				sb.append(value.toString());
			}
		}
		sb.append(currentTime);
		return sha256String(sb.toString());
	}

	public static String generateCheckHashGetArray(String token, String currentTime, Map<String, String[]> parameter) {
		StringBuilder sb = new StringBuilder();
		sb.append(token);
		if (parameter != null && parameter.size() != 0) {
			Set<Entry<String, String[]>> entrySet = parameter.entrySet();
			for (Entry<String, String[]> entry : entrySet) {
				String key = entry.getKey();
				String[] value = entry.getValue();
				sb.append(key);
				sb.append("=");
				for (String string : value) {
					sb.append(string + ",");
				}
				sb.deleteCharAt(sb.length() - 1);
			}
		}
		sb.append(currentTime);
		return sha256String(sb.toString());
	}

	public static String generateCheckHashGet(String token, String requestUrl, String serverTime) {
		StringBuilder sb = new StringBuilder();
		sb.append(token);
		sb.append(requestUrl);
		sb.append(serverTime);
		return sha256String(sb.toString());
	}

	public static String generateCheckHashPost(String token, String requestUrl, String body, String serverTime) {
		StringBuilder sb = new StringBuilder();
		sb.append(token);
		sb.append(requestUrl);
		sb.append(body);
		sb.append(serverTime);
		return sha256String(sb.toString());
	}

}
