package com.yihu.jw.util.wechat;

import com.yihu.jw.util.common.XMLUtil;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.*;


public class WeiXinPayUtils {

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final Random RANDOM = new SecureRandom();

    /**
     * 获取 微信支付,统一下单 前的报文
     * @param param
     * @param appKey
     * @return
     * @throws Exception
     */
    public static String getXmlBeforUnifiedorder(Map<String, String> param,String appKey) throws Exception {
        synchronized (WeiXinPayUtils.class) {
            param.put("nonce_str",generateNonceStr());
            WXPayConstants.SignType  wxSignType = WXPayConstants.SignType.MD5;
            String signType = param.get("sign_type");
            if("HMAC-SHA256".equalsIgnoreCase(signType)){
                wxSignType = WXPayConstants.SignType.HMACSHA256;
            }

            //获取微信签名
            String signature = WeiXinPayUtils.generateSignature(param, appKey, wxSignType);
            param.put("sign",signature);

            //参数转化XML
            String params = XMLUtil.map2xmlForWx(param);
            return params;
        }
    }


    public static Map<String, String> getXmlBeforRefund(Map<String, String> param,String appKey) throws Exception {
        synchronized (WeiXinPayUtils.class) {
            param.put("nonce_str",generateNonceStr());
            WXPayConstants.SignType  wxSignType = WXPayConstants.SignType.MD5;
            String signType = param.get("sign_type");
            if("HMAC-SHA256".equalsIgnoreCase(signType)){
                wxSignType = WXPayConstants.SignType.HMACSHA256;
            }

            //获取微信签名
            String signature = WeiXinPayUtils.generateSignature(param, appKey, wxSignType);
            param.put("sign",signature);
            return param;
        }
    }

    /**
     * 调起支付的接口
     * @param param
     * @param appKey
     * @return
     * @throws Exception
     */
    public static Map<String, String> getMapAfterUnifiedorder(Map<String, String> param,String appKey) throws Exception {
        synchronized (WeiXinPayUtils.class) {
            WXPayConstants.SignType  wxSignType = WXPayConstants.SignType.MD5;
            String signType = param.get("sign_type");
            if("HMAC-SHA256".equalsIgnoreCase(signType)){
                wxSignType = WXPayConstants.SignType.HMACSHA256;
            }

            //获取微信签名
            String signature = WeiXinPayUtils.generateSignature(param, appKey, wxSignType);
            param.put("sign",signature);
            return param;
        }
    }

    /**
     *
     * 微信支付,统一下单
     *
     * param 对应的key值参见文档 https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1 (sign,nonce_str两个参数,此接口会自动生成)
     *
     * @param param
     * @param appKey
     * @return  返回的map为微信返回报文转换成的map,
     *            此外map中 有个属性 wxPayResult.该属性放着微信返回的原始报文数据
     * @throws Exception
     */
    public static Map<String,Object> unifiedorder(Map<String, String> param,String appKey) throws Exception {
        synchronized (WeiXinPayUtils.class) {
            String xml = getXmlBeforUnifiedorder(param, appKey);
            String result = HttpUtil.sendPost("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
            Map<String,Object> wxrs =  XMLUtil.xmltoMap(result);
            wxrs.put("wxPayResult",wxrs);
            return wxrs;
        }
    }

    /**
     *
     * 微信支付,统一下单
     *
     * param 对应的key值参见文档 https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1 (sign,nonce_str两个参数,此接口会自动生成)
     *
     * @param param
     * @return  返回的map为微信返回报文转换成的map,
     *            此外map中 有个属性 wxPayResult.该属性放着微信返回的原始报文数据
     * @throws Exception
     */
    public static Map<String,Object> unifiedorder(String param) throws Exception {
        synchronized (WeiXinPayUtils.class) {
            String result = HttpUtil.sendPost("https://api.mch.weixin.qq.com/pay/unifiedorder", param);
            Map<String,Object> wxrs =  XMLUtil.xmltoMap(result);
            wxrs.put("wxPayResult",wxrs);
            return wxrs;
        }
    }

    public static Map<String,Object> unifiedorder(String param,boolean withResult) throws Exception {
        synchronized (WeiXinPayUtils.class) {
            String result = HttpUtil.sendPost("https://api.mch.weixin.qq.com/pay/unifiedorder", param);
            Map<String,Object> wxrs =  XMLUtil.xmltoMap(result);
            if(withResult){
                wxrs.put("wxPayResult",wxrs);
            }
            return wxrs;
        }
    }



    /**
     *
     * 微信支付，查询订单
     *
     * param 对应的key值参见文档 https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_2&index=4 (sign,nonce_str两个参数,此接口会自动生成)
     *
     * @param param
     * @param appKey
     * @return  返回的map为微信返回报文转换成的map,
     *            此外map中 有个属性 wxPayResult.该属性放着微信返回的原始报文数据
     * @throws Exception
     */
    public static Map<String,Object> orderquery(Map<String, String> param,String appKey) throws Exception {
        synchronized (WeiXinPayUtils.class) {
            String xml = getXmlBeforUnifiedorder(param, appKey);
            String result = HttpUtil.sendPost("https://api.mch.weixin.qq.com/pay/orderquery", xml);
            Map<String,Object> wxrs =  XMLUtil.xmltoMap(result);
            wxrs.put("wxPayResult",wxrs);
            return wxrs;
        }
    }


    public static Map<String,Object> orderquery(String param,boolean withResult) throws Exception {
        synchronized (WeiXinPayUtils.class) {
            String result = HttpUtil.sendPost("https://api.mch.weixin.qq.com/pay/orderquery", param);
            Map<String,Object> wxrs =  XMLUtil.xmltoMap(result);
            if(withResult){
                wxrs.put("wxPayResult",wxrs);
            }
            return wxrs;
        }
    }


    /**
     *
     * 微信支付，申请退款
     *
     * param 对应的key值参见文档 https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_4&index=6 (sign,nonce_str两个参数,此接口会自动生成)
     *
     * @param param
     * @param appKey
     * @return  返回的map为微信返回报文转换成的map,
     *            此外map中 有个属性 wxPayResult.该属性放着微信返回的原始报文数据
     * @throws Exception
     */
    public static Map<String,Object> refund(Map<String, String> param,String appKey) throws Exception {
        synchronized (WeiXinPayUtils.class) {
            String xml = getXmlBeforUnifiedorder(param, appKey);
            String result = HttpUtil.sendPost("https://api.mch.weixin.qq.com/secapi/pay/refund", xml);
            Map<String,Object> wxrs =  XMLUtil.xmltoMap(result);
            wxrs.put("wxPayResult",wxrs);
            return wxrs;
        }
    }

    public static Map<String,Object> refund(String param,boolean withResult) throws Exception {
        synchronized (WeiXinPayUtils.class) {
            String result = HttpUtil.sendPost("https://api.mch.weixin.qq.com/secapi/pay/refund", param);
            Map<String,Object> wxrs =  XMLUtil.xmltoMap(result);
            if(withResult){
                wxrs.put("wxPayResult",wxrs);
            }
            return wxrs;
        }
    }


    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    private static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }



    /**
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     *
     * @param data 待签名数据
     * @param key API密钥
     * @param signType 签名方式
     * @return 签名
     */
    private static String generateSignature(final Map<String, String> data, String key, WXPayConstants.SignType signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(WXPayConstants.FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        sb.append("key=").append(key);
        if (WXPayConstants.SignType.MD5.equals(signType)) {
            return MD5(sb.toString()).toUpperCase();
        }
        else if (WXPayConstants.SignType.HMACSHA256.equals(signType)) {
            return HMACSHA256(sb.toString(), key);
        }
        else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }

    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    private static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 生成 HMACSHA256
     * @param data 待处理数据
     * @param key 密钥
     * @return 加密结果
     * @throws Exception
     */
    private static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }




    public static void main(String[] args) throws Exception {
        HashMap<String, String> map = new HashMap<>();
       /* map.put("appid","wx0a06b75a40b28f2a");
        map.put("mch_id","1516700601");
        map.put("body","腾讯充值中心-QQ会员充值");
        map.put("out_trade_no","20181127112445");
        map.put("total_fee","1");
        map.put("spbill_create_ip","192.168.6.109");
        map.put("notify_url","http://www.baidu.com");
        map.put("trade_type","JSAPI");
        map.put("openid", "oDGGt0QrJvH-YbDCHFgjd3Exc0Sw");*/
        map.put("refund_desc","居民取消");
        map.put("out_trade_no","HLWYY11590725608773494100");
        map.put("out_refund_no","HLWYY11590732364418");
        map.put("appid","wxa67b466e6ab64bba");
        map.put("refund_fee","1.0");
        map.put("total_fee","1.0");
        map.put("mch_id","1588010801");
        map.put("sign","E0177065CD96FC04061BEFDB8507A909");
        map.put("nonce_str","U3AVJwvwRhaiWqLFETMbZWPWoVb4CgHF");
        map.put("refund_fee_type","CNY");
        map.put("sign_type","MD5");
/*
        Map<String, Object> pay = unifiedorder(map, "yF4e9Rr1sVdqCF6c7cqqMPSNsCjYGyf9");
*/
        Map<String, Object> pay = refund(map, "a27cbed6078fa7195e51902d9ab18497");
        System.out.println("123123"+pay);

        System.out.println("--------------"+pay);
    }

}
