package com.gxwebsoft.common.system.controller;

import cn.hutool.core.util.StrUtil;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.utils.RequestUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.Payment;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RSANotificationConfig;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 会员特权购买记录表控制器
 *
 * @author 科技小王子
 * @since 2023-06-20 18:07:50
 */
@Tag(name = "微信支付结果通知")
@RestController
@RequestMapping("/api/system/wx-pay")
public class WxPayNotifyController extends BaseController {
  @Value("${spring.profiles.active}")
  String active;
  @Resource
  private RedisUtil redisUtil;
  @Resource
  private RequestUtil requestUtil;
  @Resource
  private ConfigProperties conf;

  @Schema(description = "异步通知")
  @PostMapping("/notify/{tenantId}")
  public String wxNotify(@RequestHeader Map<String, String> header, @RequestBody String body, @PathVariable("tenantId") Integer tenantId) {
    System.out.println("异步通知*************** = ");

    // 获取支付配置信息用于解密
    String key = "Payment:1:".concat(tenantId.toString());
    final Payment payment = redisUtil.get(key, Payment.class);
    String privateKey = payment.getApiKey();
    String apiclientCert = conf.getUploadPath().concat("/file").concat(payment.getApiclientCert());

    com.wechat.pay.java.core.notification.RequestParam requestParam = new com.wechat.pay.java.core.notification.RequestParam.Builder()
      .serialNumber(header.get("wechatpay-serial"))
      .nonce(header.get("wechatpay-nonce"))
      .signature(header.get("wechatpay-signature"))
      .timestamp(header.get("wechatpay-timestamp"))
      .body(body)
      .build();

    // 如果已经初始化了 RSAAutoCertificateConfig，可直接使用
    // 没有的话，则构造一个
    NotificationConfig config = new RSANotificationConfig.Builder()
      .apiV3Key(privateKey)
      .certificatesFromPath(apiclientCert)
      .build();

    // 初始化 NotificationParser
    NotificationParser parser = new NotificationParser(config);

    // 以支付通知回调为例，验签、解密并转换成 Transaction
    try {
      Transaction transaction = parser.parse(requestParam, Transaction.class);

      if (StrUtil.equals("支付成功", transaction.getTradeStateDesc())) {

        // 推送微信官方支付结果(携带租户ID的POST请求)
        requestUtil.pushWxPayNotify(transaction, payment);

        return "SUCCESS";
      }
    } catch (Exception $e) {
      System.out.println($e.getMessage());
    }

    return "fail";
  }


}
