package com.liquidnet.service.erp.utils;

import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.MD5Utils;

import java.util.*;

public class BaseUtils {
    /**
     * 获取 erp的sign
     * @param map           请求参数
     * @param appSecret     秘钥
     * @return
     */
    public static String getErpSign(Map<String, String> map, String appSecret) {
        String finalStr = "";
        map = sortMapByKey(map);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            String key01 = leftFillChar(key, "0", 2).concat("-").concat(key);
            String value01 = leftFillChar(value, "0", 4).concat("-").concat(value);
            String data = key01.concat(":").concat(value01).concat(";");
            finalStr = finalStr.concat(data);
        }
        finalStr = finalStr.substring(0, finalStr.length() - 1).concat(appSecret);
        return MD5Utils.md5(finalStr);
    }

    // 根据key 排序 hash
    private static HashMap<String,String> sortMapByKey(Map<String, String> map){
        LinkedHashMap<String,String> finalMap = CollectionUtil.linkMapStringString();
        List<String> ll = new ArrayList<>(map.keySet());
        Collections.sort(ll);
        for (String str:ll){
            finalMap.put(str,map.get(str));
        }
        return finalMap;
    }

    // sign补位算法
    private static String leftFillChar(String str, String charStr, int a) {
        String length = str.length() + "";
        for (int i = length.length(); i < a; i++) {
            length = charStr.concat(length);
        }
        return length;
    }

    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("appkey", "test2-xx");
        map.put("page_no", "0");
        map.put("end_time", "2016-08-01 13:00:00");
        map.put("start_time", "2016-08-01 12:00:00");
        map.put("page_size", "40");
        map.put("sid", "test2");
        map.put("timestamp", "1470042310");
        System.out.println(getErpSign(map,"12345"));
        System.out.println("ad4e6fe037ea6e3ba4768317be9d1309");

    }

}
