package cn.wisenergy.service.util;

import cn.wisenergy.common.utils.R;
import cn.wisenergy.model.dto.PayPageDto;
import cn.wisenergy.service.httpClient.WechatPayHttpClientBuilder;
import cn.wisenergy.service.httpClient.auth.AutoUpdateCertificatesVerifier;
import cn.wisenergy.service.httpClient.auth.PrivateKeySigner;
import cn.wisenergy.service.httpClient.auth.WechatPay2Credentials;
import cn.wisenergy.service.httpClient.auth.WechatPay2Validator;
import cn.wisenergy.service.httpClient.util.PemUtil;
import cn.wisenergy.service.wxpay.WxCommon;
import com.alibaba.fastjson.JSONObject;
import okhttp3.HttpUrl;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.After;
import org.junit.Before;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.UUID;

public class WxPayUtil {


    /**
     * 商户号
     */
    private static String mchId = WxCommon.MCHID;
    // 商户证书序列号
    private static String mchSerialNo = WxCommon.SERIAL_NO;
    // api密钥
    private static String apiV3Key = WxCommon.SECRET_KEY;

    // 你的商户私钥
    private static String privateKey = "-----BEGIN PRIVATE KEY-----\n" +WxCommon.SECRET_KEY
            + "-----END PRIVATE KEY-----\n";

    private static CloseableHttpClient httpClient;
    private static AutoUpdateCertificatesVerifier verifier;


    static  {
        PrivateKey merchantPrivateKey = null;
        try {
            merchantPrivateKey = PemUtil.loadPrivateKey(
                    new ByteArrayInputStream(privateKey.getBytes("utf-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //使用自动更新的签名验证器,不需要传入证书
        try {
            verifier = new AutoUpdateCertificatesVerifier(
                    new WechatPay2Credentials(mchId, new PrivateKeySigner(mchSerialNo, merchantPrivateKey)),
                    apiV3Key.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(mchId, mchSerialNo, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier))
                .build();
    }

    @After
    public void after() throws IOException {
        httpClient.close();
    }

    public static void main(String[] args) throws IOException, NoSuchAlgorithmException, SignatureException, InvalidKeySpecException, InvalidKeyException {
        HttpPost httpPost = new HttpPost(WxCommon.WX_PAY_URL);

        long timestamp = System.currentTimeMillis() / 1000;
        String nonceStr = UUID.randomUUID().toString().replace("-", "");
        String method = "POST";
        String tradeNo = "21" + System.currentTimeMillis();
        HttpUrl httpurl = HttpUrl.parse(WxCommon.WX_PAY_URL);

        // 请求body参数
        String reqdata = "{"
                + "\"time_expire\":\"2021-02-07T10:34:56+08:00\","
                + "\"amount\": {"
                + "\"total\":100,"
                + "\"currency\":\"CNY\""
                + "},"
                + "\"mchid\":\"" + WxCommon.MCHID + "\","
                + "\"description\":\"Image形象店-深圳腾大-QQ公仔\","
                + "\"notify_url\":\"" + WxCommon.NOTIFY_URL + "\","
                + "\"out_trade_no\":\"" + tradeNo + "\","
                + "\"goods_tag\":\"WXG\","
                + "\"appid\":\"" + WxCommon.APP_ID + "\","
                + "\"attach\":\"自定义数据说明\","
                + "\"detail\": {"
                + "\"invoice_id\":\"wx123\","
                + "\"goods_detail\": ["
                + "{"
                + "\"goods_name\":\"iPhoneX 256G\","
                + "\"wechatpay_goods_id\":\"1001\","
                + "\"quantity\":1,"
                + "\"merchant_goods_id\":\"商品编码\","
                + "\"unit_price\":828800"
                + "},"
                + "{"
                + "\"goods_name\":\"iPhoneX 256G\","
                + "\"wechatpay_goods_id\":\"1001\","
                + "\"quantity\":1,"
                + "\"merchant_goods_id\":\"商品编码\","
                + "\"unit_price\":828800"
                + "}"
                + "],"
                + "\"cost_price\":608800"
                + "},"
                + "\"scene_info\": {"
                + "\"store_info\": {"
                + "\"address\":\"广东省深圳市南山区科技中一道10000号\","
                + "\"area_code\":\"440305\","
                + "\"name\":\"腾讯大厦分店\","
                + "\"id\":\"0001\""
                + "},"
                + "\"device_id\":\"013467007045764\","
                + "\"payer_client_ip\":\"14.23.150.211\""
                + "}"
                + "}";
        StringEntity reqEntity = new StringEntity(
                reqdata, ContentType.create("application/json", "utf-8"));
        httpPost.setEntity(reqEntity);
        httpPost.addHeader("Accept", "application/json");

//        //构造签名参数
//        //构造签名参数
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("appid", WxCommon.APP_ID);
//        jsonObject.put("mchid", WxCommon.MCHID);
//        jsonObject.put("description", "充值");
//        jsonObject.put("out_trade_no", tradeNo);
//        jsonObject.put("notify_url", WxCommon.NOTIFY_URL);
//        PayPageDto payPageDto=new PayPageDto();
//        payPageDto.setTotal(100);
//        jsonObject.put("amount", payPageDto);
//        String token = SignDemo.getToken(method, httpurl, jsonObject.toJSONString(), nonceStr, timestamp);
//        httpPost.setHeader("Authorization", "WECHATPAY2-SHA256-RSA2048" + " " + token);

        //完成签名并执行请求
        CloseableHttpResponse response = httpClient.execute(httpPost);


        try {
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                String content = EntityUtils.toString(httpEntity, "utf8");
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            response.close();
        }
    }
}