package com.community.huiju.common.sign;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * 大苏签名校验
 */
@Slf4j
public class DaSuSign {

    /**
     * 校验签名是否相等
     * @param val_1
     * @param val_2
     * @return true 相等  false 不相等
     */
    public static boolean isMD5Sign(String val_1, String val_2) {
        return StringUtils.equals(val_1, val_2);
    }

    /**
     *
     * 创建签名
     *
     * @param appid
     * @param appSecret
     * @param datetime 时间戳
     * @param encrypt 加密方式(目前就 MD5)
     * @param communityId 小区id
     * @return
     */
    public static String createSign(String appid, String appSecret, String datetime, String encrypt, String communityId, String phone){
        TreeMap<String ,Object> treeMap = Maps.newTreeMap();
        treeMap.put("appid", appid);
        treeMap.put("datetime", datetime);
        treeMap.put("encrypt", encrypt);
        treeMap.put("communityid", communityId);
        treeMap.put("phone", phone);

        String sign = "";

        StringBuilder sb = new StringBuilder();
        Set<Map.Entry<String, Object>> entries = treeMap.entrySet();
        entries.forEach(e-> {
            sb.append(e.getKey());
            sb.append("=");
            sb.append(e.getValue());
            sb.append("&");
        });

        sign = sb.toString();
        sign = sign.substring(0, sign.lastIndexOf("&"));

        log.info("签名之前参数: {}" , sign);

        try {
            String str = new String(sign.getBytes("UTF-8"), "UTF-8");
            sign = DigestUtils.md5Hex( str + appSecret);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        log.info("签名: {}" , sign);

        return sign;
    }

    public static void main(String[] args) {

        Long timeMillis = System.currentTimeMillis();
        System.out.println(timeMillis);
        String sign = createSign("dssdw2576sd997", "fgexhd855sf4", timeMillis + "", "md5", "101", "15850791953");
    }

}
