package com.fzm.mall.server.front.order.controller.weixinPay;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class WeiXinPay {
    private static String transaction = "TRANSACTION.SUCCESS";
    private static String description = "充值";
    private static String paySign = "%s\n%s\n%s\n%s\n";
    private static String signType = "RSA";
    private static String charSet = "UTF-8";
    private static String contentType = "application/json";
    private static String algorithm = "SHA256withRSA";

    private static Map<String, X509Certificate> certSet = new HashMap<>();
    private static CloseableHttpClient httpClient;
    private static PrivateKey merchantPrivateKey;
    private static AesUtil aesUtil;


    public WeiXinPay() throws IOException {
        // 加载商户私钥（privateKey：私钥字符串）
        merchantPrivateKey = PemUtil
                .loadPrivateKey(new ByteArrayInputStream(WeiXinProties.getPRIVATE_KEY().getBytes(charSet)));

        // 加载平台证书（mchId：商户号,mchSerialNo：商户证书序列号,apiV3Key：V3密钥）
        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(WeiXinProties.getMERC_ID(), new PrivateKeySigner(WeiXinProties.getSERIAL_NO(), merchantPrivateKey)), WeiXinProties.getAPIV3_KEY().getBytes(charSet));

        // 初始化httpClient
        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(WeiXinProties.getMERC_ID(), WeiXinProties.getSERIAL_NO(), merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier)).build();
        aesUtil = new AesUtil(WeiXinProties.getAPIV3_KEY().getBytes(charSet));
    }

    /**
     * 预支付下单，jsapi
     *
     * @param orderId
     * @param amt
     * @param payerOpenId
     * @return
     * @throws Exception
     */
    private String createOrder(String orderId, String amt, String payerOpenId) throws Exception {
        //请求URL
        HttpPost httpPost = new HttpPost(WeiXinProties.getWEIXINPAY_URL());
        //请求body参数
        JSONObject reqdata = new JSONObject();
        reqdata.put("appid", WeiXinProties.getAPP_ID());
        reqdata.put("mchid", WeiXinProties.getMERC_ID());
        reqdata.put("description", description);
        reqdata.put("out_trade_no", orderId);
        reqdata.put("notify_url", WeiXinProties.getNOTIFY_URL());
        JSONObject amount = new JSONObject();
        //单位为分，传数字不能传字符串，需要对amt进行处理
        amount.put("total", 1000);
        amount.put("currency", "CNY");
        reqdata.put("amount", amount);
        JSONObject payer = new JSONObject();
        payer.put("openid", payerOpenId);
        reqdata.put("payer", payer);
        StringEntity entity = new StringEntity(reqdata.toString());
        entity.setContentType(contentType);
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", contentType);
        return this.httpExecute(httpPost).getString("prepay_id");
    }


    private JSONObject httpExecute(HttpUriRequest uriRequest) throws Exception {
        //完成签名并执行请求
        CloseableHttpResponse response = httpClient.execute(uriRequest);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                return JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
            } else if (statusCode == 204) {
                throw new RuntimeException("微信支付状态204");
            } else {
                try {
                    throw new RuntimeException(JSONObject.parseObject(EntityUtils.toString(response.getEntity())).getString("message"));
                } catch (Exception e) {
                    throw new RuntimeException(StringUtils.join("微信支付状态", statusCode));
                }
            }
        } finally {
            response.close();
        }
    }

    /**
     * 小程序调起支付数据组织签名
     *
     * @param orderId
     * @param amt
     * @param payerOpenId
     * @return
     */
    public JSONObject wxAppSign(String orderId, String amt, String payerOpenId) {
        try {
            JSONObject data = new JSONObject();
            String orderPkg = this.createOrder(orderId, amt, payerOpenId);
            String appId = WeiXinProties.getAPP_ID();
            String timeSmp = String.valueOf(System.currentTimeMillis());
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String pkgInfo = StringUtils.join("prepay_id=", orderPkg);
            data.put("appId", appId);
            data.put("timeStamp", timeSmp);
            data.put("nonceStr", uuid);
            data.put("package", pkgInfo);
            data.put("signType", signType);
            data.put("paySign", this.sign(String.format(paySign, appId, timeSmp, uuid, pkgInfo), merchantPrivateKey));
            return data;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 私钥签名
     *
     * @param plainText
     * @param privateKey
     * @return
     * @throws Exception
     */
    private String sign(String plainText, PrivateKey privateKey) throws Exception {
        Signature privateSignature = Signature.getInstance(algorithm);
        privateSignature.initSign(privateKey);
        privateSignature.update(plainText.getBytes(charSet));
        byte[] signature = privateSignature.sign();
        return Base64.getEncoder().encodeToString(signature);
    }

    /**
     * 验签
     *
     * @param serialNo
     * @param verStr
     * @param signStr
     * @throws Exception
     */
    public void verify(String serialNo, String verStr, String signStr) throws Exception {
        Certificate cerCert = certSet.get(serialNo);
        if (null == cerCert) {
            this.freshCert();
            cerCert = certSet.get(serialNo);
        }
        PublicKey publicKey = cerCert.getPublicKey();
        byte[] signed = Base64.getDecoder().decode(signStr);
        Signature sign = Signature.getInstance(algorithm);
        sign.initVerify(publicKey);
        sign.update(verStr.getBytes(charSet));
        if (!sign.verify(signed)) {
            throw new RuntimeException("签名验证失败");
        }
    }

    /**
     * 获取微信支付平台证书
     *
     * @throws Exception
     */
    private void freshCert() throws Exception {
        HttpGet httpGet = new HttpGet(WeiXinProties.getCERT_URL());
        httpGet.setHeader("Accept", contentType);
        httpGet.setHeader("User-Agent", "https://zh.wikipedia.org/wiki/User_agent");
        JSONObject json = this.httpExecute(httpGet);
        for (Object o : json.getJSONArray("data")) {
            JSONObject certificate = JSONObject.parseObject(o.toString());
            JSONObject encryptCertificate = certificate.getJSONObject("encrypt_certificate");
            String cert = aesUtil.decryptToString(encryptCertificate.getString("associated_data").getBytes(charSet), encryptCertificate.getString("nonce").getBytes(charSet), encryptCertificate.getString("ciphertext"));
            X509Certificate weixinCert = PemUtil.loadCertificate(new ByteArrayInputStream(cert.getBytes(charSet)));
            certSet.put(certificate.getString("serial_no"), weixinCert);
        }
    }


    public JSONObject notify(JSONObject data) throws Exception {
        if (transaction.equals(data.get("event_type"))) {
            JSONObject resource = data.getJSONObject("resource");
            String notifyData = aesUtil.decryptToString(resource.getString("associated_data").getBytes("UTF-8"), resource.getString("nonce").getBytes("UTF-8"), resource.getString("ciphertext"));
            JSONObject notifyJsonData = JSONObject.parseObject(notifyData);
            notifyJsonData.getString("mchid");
            notifyJsonData.getString("appid");
            notifyJsonData.getString("out_trade_no");
            notifyJsonData.getString("trade_state");
            notifyJsonData.getString("success_time");
            notifyJsonData.getJSONObject("payer").getString("openid");
            notifyJsonData.getJSONObject("amount");
            return  notifyJsonData;
        }else{
            return  null;
        }
    }

    public String wxAppSign(String appid, String timestamp, String noncestr, String prepayid) {
        try {
            return sign(String.format(paySign, appid, timestamp, noncestr, prepayid), merchantPrivateKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
