package com.yc.ship.module.trade.framework.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Set;

/**
 * @author lishiqiang 906534176@qq.com
 * @version V1.0
 * &#064;Description: 支付工具类
 * @date 2017-11-24
 * @Copyright www.lishiqiang.cn
 */
public class PayUtil {

    private static final Logger LOG = LoggerFactory.getLogger(PayUtil.class);


    /**
     * 验证支付中心签名
     *
     * @param params
     * @return
     */
    public static boolean verifyPaySign(Map<String, Object> params, String key) {
        // 签名
        String sign = (String) params.get("sign");
        // 不参与签名
        params.remove("sign");
        String checkSign = PayDigestUtil.getSign(params, key,"channerId");
        if (!checkSign.equalsIgnoreCase(sign)) {
            return false;
        }
        return true;
    }

    /**
     * 验证VV平台支付中心签名
     *
     * @param params
     * @return
     */
    public static boolean verifyPaySign(Map<String, Object> params, String key, String... noSigns) {
        String sign = (String) params.get("sign"); // 签名
        params.remove("sign");    // 不参与签名
        if (noSigns != null && noSigns.length > 0) {
            for (String noSign : noSigns) {
                params.remove(noSign);
            }
        }
        String checkSign = PayDigestUtil.getSign(params, key);
        if (!checkSign.equalsIgnoreCase(sign)) {
            return false;
        }
        return true;
    }

    public static String genUrlParams(Map<String, Object> paraMap) {
        if (paraMap == null || paraMap.isEmpty()) {
            return "";
        }
        StringBuffer urlParam = new StringBuffer();
        Set<String> keySet = paraMap.keySet();
        int i = 0;
        for (String key : keySet) {
            urlParam.append(key).append("=").append(paraMap.get(key));
            if (++i == keySet.size()) {
                break;
            }
            urlParam.append("&");
        }
        return urlParam.toString();
    }

    /**
     * 发起HTTP/HTTPS请求(method=POST)
     *
     * @param url
     * @return
     */
    public static String call4Post(String url) {
        try {
            URL url1 = new URL(url);
//            LOG.info("call4Post>>>url="+url);
            if ("https".equals(url1.getProtocol())) {
                return HttpClient.callHttpsPost(url);
            } else if ("http".equals(url1.getProtocol())) {
                return HttpClient.callHttpPost(url);
            } else {
                return "";
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return "";
    }

}
