package cn.superdesk.uniorder.common.security.superdeskapp.sign;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * 服务之窗1L- SignUtils
 *
 * @Description TODO
 * @author: jiangyong
 * @since: 2020/9/18 14:24
 */
@Slf4j
public class OpenDataApiSignUtils {
//    private static final StringBuffer signStr = new StringBuffer();
//    private static final StringBuffer sha1Str = new StringBuffer();


	/**
	 * 签名
	 *
	 * @param request
	 * @param appSecret
	 * @return
	 */
	public static String getSign(OpenDataApiRequestEntity request, String appSecret) {
		StringBuilder signStr = new StringBuilder();
		try {
			if (!ObjectUtils.allNotNull(request)) {
				throw new Exception("参数值不能为空!");
			}
			Map<String, String>                 map      = OpenDataApiSignUtils.objectToMap(request);
			Set<Map.Entry<String, String>>      entries  = map.entrySet();
			Iterator<Map.Entry<String, String>> iterator = entries.iterator();

			signStr.setLength(0);
			signStr.append(appSecret);
			while (iterator.hasNext()) {
				Map.Entry entry = iterator.next();
				String    k     = String.valueOf(entry.getKey());
				String    v     = String.valueOf(entry.getValue());

				if (entry.getValue() != null) {
					signStr.append(k).append(v);
				}
			}
			signStr.append(appSecret);

			log.info("明文\n{}", signStr.toString().trim());

			return toSHA1Str(signStr.toString().trim());
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	private static String toSHA1Str(String str) {
		try {
			if (str == null) {
				return "";
			}
			final MessageDigest messageDigest = MessageDigest.getInstance("SHA");
			final byte[]        digests       = messageDigest.digest(str.getBytes());

//            sha1Str.setLength(0);
//            for (int i = 0; i < digests.length; i++) {
//                int halfbyte = (digests[i] >>> 4) & 0x0F;
//                for (int j = 0; j <= 1; j++) {
//                    sha1Str.append(
//                            ((0 <= halfbyte) && (halfbyte <= 9))
//                                    ? (char) ('0' + halfbyte)
//                                    : (char) ('a' + (halfbyte - 10)));
//                    halfbyte = digests[i] & 0x0F;
//                }
//            }
//            return sha1Str.toString().toUpperCase();
			char[] chars = Hex.encodeHex(digests);

			log.info("密文\n{}", new String(chars).toUpperCase().toString().trim());

			return new String(chars).toUpperCase();

		} catch (final Throwable throwable) {
			return "";
		}

	}


	public static Map<String, String> objectToMap(Object obj) {
		try {
			TreeMap<String, String> map   = new TreeMap<>();
			Class<?>                clazz = obj.getClass();
			for (Field field : clazz.getDeclaredFields()) {
				field.setAccessible(true);
				String fieldName = field.getName();
				Object value     = field.get(obj);
				if (null != value) {
					map.put(fieldName, (String) value);
				}
			}
			return map;
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
//        String s = "123456app_keyN7NL00524939auth_tokenbiz_contentbiz_content_aesformatjsonlocalecnmethodcust.detailtimestamp2018-05-16 20:12:34v1.0123456";
		String s = "b8c4d9d706c71a08e2230d30f4b713720cb1be0fappKeyfwzcFiCI7Ulg854dOufUformatjsonlocalecntimestamp2020-09-17 12:00:00v1.0b8c4d9d706c71a08e2230d30f4b713720cb1be0f";
		System.out.println(OpenDataApiSignUtils.toSHA1Str(StringUtils.trim(s)));

	}

}
