package org.springblade.community.pay.wx.controller;

import cn.hutool.core.util.StrUtil;
import com.ijpay.core.kit.HttpKit;
import com.ijpay.core.kit.WxPayKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springblade.community.pay.wx.config.WxPayV3Config;
import org.springblade.community.pay.wx.event.PayNotifyEvent;
import org.springblade.community.pay.wx.response.WxPayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/pay/wx")
@Api(value = "微信支付", tags = "微信支付接口")
@Slf4j
public class WxPayController {
	@Autowired
	private WxPayV3Config wxPayConfig;

	@Autowired
	private ApplicationContext applicationContext;

	@RequestMapping(value = "/v3/payNotify", method = {RequestMethod.POST, RequestMethod.GET})
	@ApiOperation(value = "微信支付回调")
	public WxPayResponse payNotify(HttpServletRequest request, HttpServletResponse response) {
		WxPayResponse wxPayResponse;
		try {
			String timestamp = request.getHeader("Wechatpay-Timestamp");
			String nonce = request.getHeader("Wechatpay-Nonce");
			String serialNo = request.getHeader("Wechatpay-Serial");
			String signature = request.getHeader("Wechatpay-Signature");

			log.info("timestamp:{} nonce:{} serialNo:{} signature:{}", timestamp, nonce, serialNo, signature);
			String result = HttpKit.readData(request);
			log.info("支付通知密文 {}", result);

			// 需要通过证书序列号查找对应的证书，verifyNotify 中有验证证书的序列号
			String plainText = WxPayKit.verifyNotify(serialNo, result, signature, nonce, timestamp,
				wxPayConfig.getApiKey3(), wxPayConfig.getCertPemPath());

			log.info("支付通知明文 {}", plainText);

			//响应码
			if (StrUtil.isNotEmpty(plainText)) {
				response.setStatus(200);
				wxPayResponse = WxPayResponse.success("成功");
			} else {
				response.setStatus(500);
				wxPayResponse = WxPayResponse.fail("签名错误");
			}

			//发起事件通知
			applicationContext.publishEvent(new PayNotifyEvent<>(this,plainText));

		} catch (Exception e) {
			log.error(e.getMessage());
			response.setStatus(500);
			wxPayResponse = WxPayResponse.fail("服务器异常");
		}
		return wxPayResponse;
	}
}
