package com.cyl.wechat.coupon;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;

@Slf4j
public class CouponUtil {
    /**
     * 微信商户号（注意是商户号，不是子商户号）
     */
    //public static String WECHAT_MCHID;

    /**
     * 微信api密钥V2
     */
    //public static String WECHAT_APIV2KEY;

    public static String getSginForWeixinCoupon(SendCouponParam sendCouponParam, String WECHAT_MCHID, String WECHAT_APIV2KEY) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        params.put("out_request_no0",sendCouponParam.getOut_request_no());
        params.put("send_coupon_merchant",WECHAT_MCHID);
        params.put("stock_id0",sendCouponParam.getStock_id());

        String key = WECHAT_APIV2KEY; //这里是微信V2api密钥
        String string = createSign(params);
        String stringSignTemp = string + "key=" + key;
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        //  utf-8 : 解决中文加密不一致问题,必须指定编码格式
        String sgin = byteArrayToHexString(sha256_HMAC.doFinal(stringSignTemp.getBytes("utf-8"))).toUpperCase();
        log.info("【获取微信签名】得到签名sign:" + sgin);
        // 返回签名
        return sgin;
    }

    public static String createSign(Map<String, String> params){
        List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(params.entrySet());
        // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
        Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return (o1.getKey()).toString().compareTo(o2.getKey());
            }
        });
        // 构造签名键值对的格式
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> item : infoIds) {
            if (item.getKey() != null || item.getKey() != "") {
                String key = item.getKey();
                String val = item.getValue();
                if (!(val == "" || val == null)) {
                    sb.append(key + "=" + val + "&");
                }
            }
        }
        log.info("【获取微信签名】得到拼接串:" + sb.toString());
        return sb.toString();
    }

    private static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b!=null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                hs.append('0');
            }
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }
}
