package trade

import (
	"Wine-Server/utils"
	"Wine-Server/utils/tables"
	"github.com/gorilla/websocket"
)

// queryUser @super.order.QueryUser
func queryUser(conn *websocket.Conn, data any) {
	var param queryUserParam
	err := utils.AnyTrans(data, &param)
	if err != nil {
		utils.Logger.Println(err)
		_ = conn.WriteJSON(utils.WsEvent("adminTradeQueryUserRes", utils.Fail("参数错误")))
		return
	}
	total, users, err := tables.UserQuery(param.Id, param.Vip, param.Limit, param.Page)
	if err != nil {
		utils.Logger.Println(err)
		_ = conn.WriteJSON(utils.WsEvent("adminTradeQueryUserRes", utils.Fail("查询用户失败")))
		return
	}
	_ = conn.WriteJSON(utils.WsEvent(
		"adminTradeQueryUserRes",
		utils.Success(utils.JsonType{"total": total, "list": users}),
	))
}

// queryTrade @super.order.QueryTrade
func queryTrade(conn *websocket.Conn, data any) {
	var param queryTradeParam
	err := utils.AnyTrans(data, &param)
	if err != nil {
		utils.Logger.Println(err)
		_ = conn.WriteJSON(utils.WsEvent("adminTradeQueryTradeRes", utils.Fail("参数错误")))
		return
	}
	total, trades, err := tables.TradeQuery(param.Cond, param.Uid, param.Limit, param.Page)
	if err != nil {
		utils.Logger.Println(err)
		_ = conn.WriteJSON(utils.WsEvent("adminTradeQueryTradeRes", utils.Fail("查询订单失败")))
		return
	}
	_ = conn.WriteJSON(utils.WsEvent(
		"adminTradeQueryTradeRes",
		utils.Success(utils.JsonType{"total": total, "list": trades}),
	))
}

// refund @super.order.Refund
func refund(conn *websocket.Conn, manager *tables.ManagerTable, data any) {
	var param refundParam
	err := utils.AnyTrans(data, &param)
	if err != nil {
		utils.Logger.Println(err)
		_ = conn.WriteJSON(utils.WsEvent("adminTradeRefundRes", utils.Fail("参数错误")))
		return
	}
	trade := tables.TradeTable{Id: param.Tid}
	err = trade.Get()
	if err != nil {
		utils.Logger.Println(err)
		_ = conn.WriteJSON(utils.WsEvent("adminTradeRefundRes", utils.Fail("订单查询失败")))
		return
	}
	if trade.Cash < param.Cash {
		utils.Logger.Println(err)
		_ = conn.WriteJSON(utils.WsEvent("adminTradeRefundRes", utils.Fail("超出原订单金额")))
		return
	}
	refund := tables.RefundTable{Tid: param.Tid, Manager: manager.Id, Cash: param.Cash, Reason: param.Reason}
	err = refund.Insert()
	if err != nil {
		err = refund.Get()
		refund.Manager, refund.Cash, refund.Reason = manager.Id, param.Cash, param.Reason
		err = refund.UpdateSelf()
	}
	_ = conn.WriteJSON(utils.WsEvent("adminTradeRefundRes", utils.Success(nil)))
	// update user table
	user := tables.UserTable{Id: trade.Payer}
	_ = user.Get()
	user.RefundCount++
	user.RefundCost += uint64(param.Cash)
}
