package digital_ticket

import (
	"github.com/gin-gonic/gin"
	"wails-app/internal/model/common/response"
	"wails-app/internal/modules/digital-ticket/repository"
	"wails-app/internal/modules/digital-ticket/service"
)

var ticketSvc = service.NewTicketService()

func GetTicket(c *gin.Context) {
	t, err := ticketSvc.GetByTicketNo(c.Param("ticketNo"))
	if err != nil {
		response.FailWithMessage("票不存在", c)
		return
	}
	response.OkWithData(t, c)
}

type payReq struct {
	PaymentMethod  string  `json:"payment_method"`
	PaymentOrderNo string  `json:"payment_order_no"`
	PaidAmount     float64 `json:"paid_amount"`
}

func PayTicket(c *gin.Context) {
	var req payReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	t, err := ticketSvc.GetByTicketNo(c.Param("ticketNo"))
	if err != nil {
		response.FailWithMessage("票不存在", c)
		return
	}
	extra := map[string]interface{}{
		"payment_method": req.PaymentMethod, "payment_order_no": req.PaymentOrderNo,
		"paid_amount": req.PaidAmount,
		"fee": t.Fee,
	}
	if err := ticketSvc.Transition(t.ID, service.StatePaid, extra); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithMessage("支付成功", c)
}

func ExitTicket(c *gin.Context) {
	t, err := ticketSvc.GetByTicketNo(c.Param("ticketNo"))
	if err != nil {
		response.FailWithMessage("票不存在", c)
		return
	}
	if err := ticketSvc.Transition(t.ID, service.StateExited, nil); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithMessage("已离场", c)
}

func ListTickets(c *gin.Context) {
	var q repository.TicketListQuery
	if err := c.ShouldBindQuery(&q); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := ticketSvc.List(q)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithDetailed(response.PageResult{List: list, Total: total, Page: q.Page, PageSize: q.PageSize}, "查询成功", c)
}

func SetupDigitalTicketRouter(router *gin.RouterGroup) {
	dt := router.Group("/digital-ticket")
	{
		dt.GET("/:ticketNo", GetTicket)
		dt.POST("/:ticketNo/pay", PayTicket)
		dt.POST("/:ticketNo/exit", ExitTicket)
	}
	dt2 := router.Group("/digital-ticket")
	{
		dt2.GET("/list", ListTickets)
	}
}
