package controller

import (
	"log"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"

	"tower_api/pkg/payment"
	"tower_api/service"
)

var (
	orderService = service.NewOrderService()
)

type OrderController struct {
}

func NewOrderController() *OrderController {
	return &OrderController{}
}

// CallBack 订单支付成功后回调
func (o *OrderController) CallBack(c *gin.Context) {
	//1. 匹配支付渠道
	payChannel := strings.TrimSpace(c.Param("channel"))
	pay, err := payment.Dispatch(payChannel)
	if err != nil {
		c.String(http.StatusOK, "payment not found")
		return
	}
	//2. 回调参数验证签名+验证订单是否支付成功
	orderSn, amount, err := pay.Callback(c)
	if err != nil {
		log.Println("处理订单回调出错:" + err.Error())
		c.String(http.StatusOK, pay.ReplyContent(false))
		return
	}
	//3. 根据订单号获取订单信息
	orderInfo := orderService.GetOrderInfo(orderSn)
	if orderInfo.Id == 0 {
		log.Println(orderSn + "订单信息为找到")
		c.String(http.StatusOK, pay.ReplyContent(false))
		return
	}
	//3.1 若已支付则返回成功
	if orderInfo.OrderState > 0 {
		c.String(http.StatusOK, pay.ReplyContent(true))
		return
	}
	//3.2 若订单金额不匹配，返回成功，并飞书通知
	if orderInfo.OrderPrice != amount {
		payment.MoneyNotMatchNotify(orderInfo, amount)
		c.String(http.StatusOK, pay.ReplyContent(true))
		return
	}
	//4 确定订单是否成功
	err = pay.Confirm()
	if err != nil {
		log.Println(orderSn + "确认失败:" + err.Error())
		c.String(http.StatusOK, pay.ReplyContent(false))
		return
	}
	//5 公共处理支付成功逻辑
	err = orderService.UpdateState(orderSn, orderInfo.PlayerId)
	if err != nil {
		log.Println("处理订单出错:" + err.Error())
		c.String(http.StatusOK, pay.ReplyContent(false))
		return
	}
	//6 返回响应信息
	c.String(http.StatusOK, pay.ReplyContent(true))
}
