package cn.quant.baa.pay.acquirer.weixin;

import cn.quant.baa.pay.acquirer.AcquirerProperties;
import cn.quant.baa.pay.acquirer.MerchantAcquirer;
import cn.quant.baa.pay.jpa.entity.PayHistoryEntity;
import cn.quant.baa.pay.model.web.*;
import cn.quant.spring.util.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;

/**
 * Created by Administrator on 2021/8/31 0031.
 */
public class WeiXinMerchantAcquirer extends MerchantAcquirer {

    private WebClient webClient;

    /**
     * 微信签名格式定义
     */
    String TOKEN_PATTERN = "mchid=\"%s\",nonce_str=\"%s\",timestamp=\"%d\",serial_no=\"%s\",signature=\"%s\"";

    /**
     * 微信签名前缀
     */
    String SCHEMA = "WECHATPAY2-SHA256-RSA2048 ";

    /**
     * 商户私钥
     */
    PrivateKey privateKey;

    /**
     * 平台证书
     */
    X509Certificate payCerKey;

    ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 支付初始化
     *  1. 初始化私钥
     *  2. 初始化平台证书
     *  3. 初始化webClient
     *
     * @param properties
     * @return
     * @throws Exception
     */
    @Override
    public MerchantAcquirer init(AcquirerProperties properties) throws Exception {
        super.init(properties);

        privateKey = getPrivateKey(properties.getPrivateKey());

        payCerKey = loadCertificate(properties.getPayCertKey());

        this.webClient = WebClient.builder().baseUrl(properties.getDomain())
                .defaultHeader("Accept", "application/json")
                .defaultHeader("User-Agent", "QuantGroup PayCenter Java Api")
                .build();
        return this;
    }

    @Override
    public Object code() {
        return this.properties.getMchChanId().toString();
    }

    @Override
    public JsonNode pay(PayRequestData payRequestData, PayHistoryEntity payHistoryEntity) {
        ObjectNode bodyNode = objectMapper.createObjectNode();
        // 转换金额为分
        BigInteger amount = new BigDecimal(payRequestData.getAmount()).multiply(new BigDecimal(100)).toBigInteger();
        bodyNode.put("mchid", properties.getPayAcctId())
                .put("appid", properties.getPayAppId())
                .put("attach", payRequestData.getAttach())
                .put("description", payRequestData.getSubject())
                .put("notify_url", payRequestData.getNotifyUrl())
                .put("out_trade_no", payRequestData.getOutTradeNo());
        bodyNode.putObject("amount")
                .put("total", amount);
        ObjectNode sceneInfo = objectMapper.createObjectNode()
                .put("payer_client_ip", "127.0.0.1");
        switch (properties.getAccessCode()) {
            case H5:
                sceneInfo.putObject("h5_info").put("type", "Wap");
                break;
            case JS:
                bodyNode.putObject("payer")
                        .put("openid", "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o");
                break;
            case APP:
            default:
        }
        bodyNode.set("scene_info", sceneInfo);
        String payAccess = properties.getPayAccess();
        return doExecute(payAccess, bodyNode);
    }

    @Override
    public JsonNode checkPay(CheckPayRequestData checkPayRequestData) {
        ObjectNode bodyNode = objectMapper.createObjectNode();
        bodyNode.put("mchid", properties.getPayAcctId());
        String payAccess = properties.getPayAccess().replace("{out_trade_no}", checkPayRequestData.getOutTradeNo());
        return doExecute(payAccess, bodyNode);
    }

    @Override
    public JsonNode checkRefund(CheckRefundRequestData checkRefundRequestData) {
        String payAccess = properties.getPayAccess().replace("{out_refund_no}", checkRefundRequestData.getOutRefundNo());
        return doExecute(payAccess, null);
    }

    @Override
    public JsonNode close(CloseRequestData closeRequestData) {
        ObjectNode bodyNode = objectMapper.createObjectNode();
        bodyNode.put("mchid", properties.getPayAcctId());
        String payAccess = properties.getPayAccess().replace("{out_trade_no}", closeRequestData.getOutTradeNo());
        return doExecute(payAccess, bodyNode);
    }

    @Override
    public JsonNode refund(RefundRequestData refundRequestData) {
        // 转换金额为分
        BigInteger amount = new BigDecimal(refundRequestData.getRefundAmount()).multiply(new BigDecimal(100)).toBigInteger();
        ObjectNode bodyNode = objectMapper.createObjectNode();
        bodyNode.put("out_trade_no", refundRequestData.getOutTradeNo());
        bodyNode.put("out_refund_no", refundRequestData.getOutRefundNo());
        bodyNode.put("reason", refundRequestData.getRefundReason());
//        bodyNode.put("notify_url", "");
        bodyNode.putObject("amount")
                .put("refund", amount)
                .put("total", amount)
                .put("currency", "CNY");
        String payAccess = properties.getPayAccess();
        return doExecute(payAccess, bodyNode);
    }

    /**
     *
     * @param payAccess
     * @param bodyNode
     * @return
     */
    private JsonNode doExecute(String payAccess, ObjectNode bodyNode) {
        String method = properties.getAccessMethod();
        UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(payAccess);
        String requestBody = "";
        // 处理GET请求
        if (HttpMethod.GET.name().equals(method)) {
            if (null != bodyNode) {
                bodyNode.fields().forEachRemaining((entry) -> {
                    uriComponentsBuilder.queryParam(entry.getKey(), entry.getValue().asText());
                });
            }
        } else {
            // 非GET请求的时候处理requestBody
            try {
                if (null != bodyNode) {
                    requestBody = objectMapper.writeValueAsString(bodyNode);
                }
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        String uri = uriComponentsBuilder.build().toString();
        long timestamp = System.currentTimeMillis() / 1000;
        String nonceStr = UUID.randomUUID().toString().replace("-", "");
        // 代签名字符串
        String signText = joining("\n", method, uri, String.valueOf(timestamp), nonceStr, requestBody);
        String sign = sign(signText);
        String token = String.format(TOKEN_PATTERN, properties.getPayAcctId(), nonceStr, timestamp, properties.getPayCertNo(), sign);
        Mono<ClientResponse> mono = webClient.method(HttpMethod.resolve(method))
                .uri(uri)
                .header("Authorization", SCHEMA.concat(token))
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(requestBody)
                .exchange();
        ClientResponse response = mono.block();
        JsonNode bodyJsonNode = objectMapper.createObjectNode();
        if (response != null) {
            Mono<String> resultMono = response.bodyToMono(String.class);
            String body = resultMono.block();
            if (null == body) {
                body = "";
            }
            try {
                bodyJsonNode = objectMapper.readTree(body);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

            if (response.statusCode().value() >= 200 && response.statusCode().value() < 300) {
                //Request-ID
                String requestId = response.headers().asHttpHeaders().getFirst("Request-ID");
                //当前使用的微信平台证书序列号
                String serial = response.headers().asHttpHeaders().getFirst("Wechatpay-Serial");
                //微信服务器的时间戳
                String wxTimestamp = response.headers().asHttpHeaders().getFirst("Wechatpay-Timestamp");
                //微信服务器提供的随机串
                String nonce = response.headers().asHttpHeaders().getFirst("Wechatpay-Nonce");
                //微信平台签名
                String signature = response.headers().asHttpHeaders().getFirst("Wechatpay-Signature");

                //签名信息
                String wsSignText = joining("\n", wxTimestamp, nonce, body);
                if (verify(wsSignText, signature)) {
                    return bodyJsonNode;
                }
                // TODO: 签名校验失败，做异常处理
                throw new RuntimeException("签名校验失败");
            } else {
                return bodyJsonNode;
                // TODO: 返回异常，做异常处理
//                throw new RuntimeException("返回异常，做异常处理");
            }
        }
        return bodyJsonNode;
    }

    /**
     * 签名
     *
     * @param signText 需要签名的字符串
     * @return
     */
    public String sign(String signText) {
        try {
            Signature sign = Signature.getInstance(properties.getSignType());
            sign.initSign(this.privateKey);
            sign.update(signText.getBytes());
            return Base64.getEncoder().encodeToString(sign.sign());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持SHA256withRSA", e);
        } catch (SignatureException e) {
            throw new RuntimeException("签名计算失败", e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException("无效的私钥", e);
        }
    }

    /**
     * 获取证书。
     *
     * @param certString 证书内容
     * @return X509证书
     */
    public X509Certificate loadCertificate(String certString) {
        try {
            ByteArrayInputStream fis = new ByteArrayInputStream(certString.getBytes());
            CertificateFactory cf = CertificateFactory.getInstance("X509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(fis);
            cert.checkValidity();
            return cert;
        } catch (CertificateExpiredException var3) {
            throw new RuntimeException("证书已过期", var3);
        } catch (CertificateNotYetValidException var4) {
            throw new RuntimeException("证书尚未生效", var4);
        } catch (CertificateException var5) {
            throw new RuntimeException("无效的证书", var5);
        }
    }

    /**
     * RSA验签名检查
     *
     * @param content           待签名数据
     * @param signature              签名值
     * @return 布尔值
     */
    public boolean verify(String content, String signature) {
        try {
            Signature sign = Signature.getInstance(properties.getSignType());
            sign.initVerify(payCerKey);
            sign.update(content.getBytes());
            return sign.verify(Base64.getDecoder().decode(signature));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持SHA256withRSA", e);
        } catch (SignatureException e) {
            throw new RuntimeException("签名验证过程发生了错误", e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException("无效的证书", e);
        }
    }

    /**
     * 获取私钥。
     *
     * @param certString 私钥文件内容(required)
     * @return 私钥对象
     */
    public PrivateKey getPrivateKey(String certString) {
        try {
            String privateKey = certString
                    .replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "")
                    .replaceAll("\\s+", "");

            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(
                    new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持RSA", e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException("无效的密钥格式");
        }
    }

    /**
     * 获取公钥。
     *
     * @param certString 公钥文件内容(required)
     * @return 私钥对象
     */
    public static PublicKey getPublicKey(String certString) throws IOException {
        try {
            String publicKey = certString
                    .replace("-----BEGIN PUBLIC KEY-----", "")
                    .replace("-----END PUBLIC KEY-----", "")
                    .replaceAll("\\s+", "");

            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePublic(
                    new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey)));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持RSA", e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException("无效的密钥格式");
        }
    }

    /**
     * 字符串数组拼接为字符串
     *
     * @param separator 分隔符
     * @param str       字符数组
     * @return 字符串
     */
    public String joining(String separator, String... str) {
        StringBuilder builder = new StringBuilder();
        for (String s : str) {
            builder.append(s).append(separator);
        }
        return builder.toString();
    }

}