package front

import (
	"PaymentCenter/app/constants/common"
	"PaymentCenter/app/constants/errorcode"
	"PaymentCenter/app/models/paychannelmodel"
	"PaymentCenter/app/services"
	"PaymentCenter/app/third/paymentService"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-pay/gopay"
	"github.com/go-pay/gopay/alipay"
	"github.com/go-pay/gopay/wechat/v3"
	"github.com/go-pay/xlog"
	"github.com/qit-team/snow-core/log/logger"
	"strconv"

	"net/http"
)

// WxCallback	微信支付回调
func WxCallback(c *gin.Context) {
	logger.Info(c, "WxCallback-回调数据", c.Request)
	payChannelId := c.Param("payChannelId")
	logger.Info(c, "WxCallback-回调数据payChannelId", payChannelId)
	if payChannelId == "" {
		c.String(http.StatusBadRequest, "%s", "fail")
	}

	// 查询应用下的支付配置
	var payChannelModel paychannelmodel.PayChannel
	payChannelIdInt, _ := strconv.Atoi(payChannelId)
	payChannelModel.Id = int64(payChannelIdInt)
	services.PayChannelGet(&payChannelModel)
	if payChannelModel.ChannelType != common.PAY_CHANNEL_WECHAT_H5 {
		logger.Error(c, "WxCallback-回调数据解析支付配置错误,查询的数据不是当前渠道")
		c.String(http.StatusBadRequest, "%s", "fail")
	}

	var wxConfig paymentService.WxPay
	err := json.Unmarshal([]byte(payChannelModel.ExtJson), &wxConfig)
	if err != nil {
		logger.Error(c, "WxCallback-回调数据解析支付配置错误", fmt.Sprintf("错误原因:%s", err.Error()))
		c.String(http.StatusBadRequest, "%s", "fail")
	}
	if wxConfig.ApiV3Key == "" || wxConfig.MchId == "" || wxConfig.PrivateKey == "" || wxConfig.SerialNo == "" {
		logger.Error(c, "WxCallback-回调数据解析支付配置错误,解析出来的信息为空")
		c.String(http.StatusBadRequest, "%s", "fail")
	}
	wxConfig.AppId = payChannelModel.AppId

	notifyReq, err := wechat.V3ParseNotify(c.Request)
	if err != nil {
		logger.Error(c, "WxCallback-回调数据验签失败", err.Error())
		return
	}

	err = paymentService.WxPayCallBack(notifyReq, wxConfig)
	if err != nil {
		logger.Error(c, "WxCallback-回调执行失败,失败原因:", err.Error())
		return
	}

	// ====↓↓↓====异步通知应答====↓↓↓====
	// 退款通知http应答码为200且返回状态码为SUCCESS才会当做商户接收成功,否则会重试。
	// 注意:重试过多会导致微信支付端积压过多通知而堵塞,影响其他正常通知。
	c.JSON(http.StatusOK, &wechat.V3NotifyRsp{Code: gopay.SUCCESS, Message: "成功"})
}

// AliCallback	支付宝支付回调
func AliCallback(c *gin.Context) {
	logger.Info(c, "AliCallback-回调数据", c.Request)
	payChannelId := c.Param("payChannelId")
	logger.Info(c, "AliCallback-回调数据APPID", payChannelId)
	if payChannelId == "" {
		c.String(http.StatusBadRequest, "%s", "fail")
	}
	// 查询应用下的支付配置
	var payChannelModel paychannelmodel.PayChannel
	payChannelIdInt, _ := strconv.Atoi(payChannelId)
	payChannelModel.Id = int64(payChannelIdInt)
	code := services.PayChannelGet(&payChannelModel)
	if payChannelModel.ChannelType != common.PAY_CHANNEL_ALIPAY_WEB {
		logger.Error(c, "AliCallback-回调数据解析支付配置错误,查询的数据不是当前渠道")
		c.String(http.StatusBadRequest, "%s", "fail")
	}
	if code == errorcode.PayChannelNotFound {
		logger.Error(c, "AliCallback-回调数据未获取到支付配置,404")
		c.String(http.StatusBadRequest, "%s", "fail")
	}

	var aliConfig paymentService.AliPay
	var aliConfigModel struct {
		PrivateKey       string `json:"private_key"`        //	应用私钥
		AppPublicCert    string `json:"app_public_cert"`    //	应用公钥
		AlipayRootCert   string `json:"alipay_root_cert"`   //	支付宝根证书
		AlipayPublicCert string `json:"alipay_public_cert"` //	支付宝公钥
	}
	err := json.Unmarshal([]byte(payChannelModel.ExtJson), &aliConfigModel)
	if err != nil {
		logger.Error(c, "AliCallback-回调数据解析支付配置错误", fmt.Sprintf("错误原因:%s", err.Error()))
		c.String(http.StatusBadRequest, "%s", "fail")
	}
	if aliConfigModel.AlipayPublicCert == "" || aliConfigModel.PrivateKey == "" || aliConfigModel.AppPublicCert == "" || aliConfigModel.AlipayRootCert == "" {
		logger.Error(c, "AliCallback-回调数据解析支付配置错误,解析出来的信息为空")
		c.String(http.StatusBadRequest, "%s", "fail")
	}
	aliConfig.AppId = payChannelModel.AppId
	aliConfig.PrivateKey = aliConfigModel.PrivateKey
	aliConfig.AppPublicCert = []byte(aliConfigModel.AppPublicCert)
	aliConfig.AlipayRootCert = []byte(aliConfigModel.AlipayRootCert)
	aliConfig.AlipayPublicCert = []byte(aliConfigModel.AlipayPublicCert)

	notifyReq, err := alipay.ParseNotifyToBodyMap(c.Request) // c.Request 是 gin 框架的写法
	if err != nil {
		xlog.Error(err)
		return
	}
	err = paymentService.ALiCallBack(notifyReq, aliConfig)
	if err != nil {
		logger.Error(c, "AliCallback-回调执行失败,失败原因:", err.Error())
		return
	}

	c.String(http.StatusOK, "%s", "success")
}