package com.yonge.toolset.thirdparty.union;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * 银联商务主扫
 */
public class UnionPay {

    private UnionPayFeignService unionPayFeignService;

    static String aliPayUrl = "http://58.247.0.18:29015/v1/netpay/trade/h5-pay";//支付宝
    static String qmfPayUrl = "http://58.247.0.18:29015/v1/netpay/qmf/h5-pay";//银联无卡
    static String H5AppId = "10037e6f6a4e6da4016a670fd4530012";
    static String h5AppKey = "f7a74b6c02ae4e1e94aaba311c04acf2";
    static String h5Mid = "898310148160568";
    static String h5Tid = "88880001";

    static String wpPayUrl = "http://58.247.0.18:29015/v1/netpay/webpay/pay";//微信
    static String wpAppId = "10037e6f6a4e6da4016a62a47e51000c";
    static String wpAppKey = "b4b70d123a724972bc21f445b0b9f75c";
    static String wpMid = "898460107420248";
    static String wpTid = "00000001";

    static String queryUrl = "http://58.247.0.18:29015/v1/netpay/query"; //订单查询地址

    static String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    static String nonce = UUID.randomUUID().toString().replace("-", "");

    public UnionPay(UnionPayFeignService unionPayFeignService) {
        this.unionPayFeignService = unionPayFeignService;
    }

    private static byte[] hmacSHA256(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException {
        String algorithm = "HmacSHA256";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(data);
    }

    private static String getOpenBodySig(String appId, String appKey, String timestamp, String nonce, String content, String method) throws Exception {
        String signatureStr = appId + timestamp + nonce + DigestUtils.sha256Hex(content);
        byte[] localSignature = hmacSHA256(signatureStr.getBytes(), appKey.getBytes());
        if (method.toUpperCase().equals("POST")) {
            return ("OPEN-BODY-SIG AppId=" + "\"" + appId + "\"" + ", Timestamp=" + "\"" + timestamp + "\"" + ", Nonce=" + "\"" + nonce + "\"" + ", Signature=" + "\"" + Base64.encodeBase64String(localSignature) + "\"");
        } else {
            return ("authorization=OPEN-FORM-PARAM" + "&appId=" + appId + "&timestamp=" + timestamp + "&nonce=" + nonce + "&content=" + URLEncoder.encode(content, "UTF-8") + "&signature=" + URLEncoder.encode(Base64.encodeBase64String(localSignature), "UTF-8"));
        }

    }


    /**
     * 获取支付链接的Map
     *
     * @param amount
     * @param orderNo
     * @param notifyUrl
     * @param returnUrl
     * @param orderSubject
     * @return
     * @throws Exception
     */
    public static Map<String, String> getPayMap(BigDecimal amount, String orderNo, String notifyUrl, String returnUrl, String orderSubject) throws Exception {
        Map<String, String> PayMap = new HashMap<>();
        JSONObject json = new JSONObject();
        //H5支付链接生成
        json.put("totalAmount", amount.multiply(new BigDecimal("100")).intValue());
        json.put("instMid", "H5DEFAULT");
        json.put("mid", h5Mid);
        json.put("tid", h5Tid);
        json.put("orderDesc", orderSubject);
        json.put("merOrderId", "1017" + orderNo);
        json.put("requestTimestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        json.put("expireTime", DateFormatUtils.format(new Date().getTime() + 300000, "yyyy-MM-dd HH:mm:ss"));
        json.put("notifyUrl", notifyUrl);
        json.put("returnUrl", returnUrl);
        String param = getOpenBodySig(H5AppId, h5AppKey, timestamp, nonce, json.toString(), "GET");
        PayMap.put("aliPay", aliPayUrl + "?" + param);
        PayMap.put("qmfPay", qmfPayUrl + "?" + param);

        //微信公众号支付链接生成
        json.put("instMid", "YUEDANDEFAULT");
        json.put("mid", wpMid);
        json.put("tid", wpTid);

        param = getOpenBodySig(wpAppId, wpAppKey, timestamp, nonce, json.toString(), "GET");
        PayMap.put("weChatPay", wpPayUrl + "?" + param);
        return PayMap;
    }

    /**
     * 订单查询
     *
     * @param orderNo 自己系统订单号
     * @return 1017201910111756231647562047 测试订单号
     */
    public Map<String, Object> query(String orderNo) throws Exception {
        JSONObject json = new JSONObject();
        json.put("instMid", "H5DEFAULT");
        json.put("mid", h5Mid);
        json.put("tid", h5Tid);
        json.put("merOrderId", "1017" + orderNo);
        json.put("requestTimestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));

        String authorization = getOpenBodySig(wpAppId, wpAppKey, timestamp, nonce, json.toString(), "POST");
        HashMap<String, String> header = new HashMap<>();
        header.put("Authorization", authorization);
        header.put("Content-Type", "application/json; charset=utf-8");
        Map query = unionPayFeignService.query(json.getInnerMap(), header);
        return query;
    }


    public static void main(String[] args) throws Exception {
        String orderNo = "1017" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + RandomStringUtils.randomNumeric(7);

        System.out.println(orderNo);

        Map<String, String> payMap = getPayMap(new BigDecimal("0.01"), orderNo, "http://pay.dayaedu.com/pay/notify", "http://dev.daya.com", "大雅测试订单");
        System.out.println("weChat= " + payMap.get("weChatPay"));
        System.out.println("H5= " + payMap.get("aliPay"));
        System.out.println("qmfPay= " + payMap.get("qmfPay"));
    }
}

