package router

import (
	"demo/data/dao"
	"demo/data/dao/manage"
	"demo/data/domain"
	"demo/data/domain/vo"
	"demo/share"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"time"
)

func OrderRouter(engine *gin.RouterGroup) {
	order := engine.Group("/order")
	{
		//根据用户登录id获取用户登录信息
		//order.POST("/submit", GetOrderData)
		PushRouter(order, "POST", "/submit", CreateOrder)
		PushRouter(order, "POST", "/list", GetOrderList)
	}
}

// CreateOrder GetOrderData 创建订单
func CreateOrder(c *gin.Context) {
	id := GetUserIdByToken(c)
	if id == 0 {
		return
	}

	data := share.GetJsonAnyParam(c)
	skuId, _ := data("skuId")
	count, _ := data("count")
	couponUserId, _ := data("couponUserId")
	contactInformation, _ := data("contactInformation")

	sku, err := dao.SelectSkuBySkuId(cast.ToInt(skuId))
	fmt.Println(sku)
	if err != nil {
		c.JSON(200, CreateResultError(1000, "商品规格不存在"))
		return
	}
	//查询库存数量
	if sku.InventoryNumber < cast.ToInt64(count) {
		c.JSON(200, CreateResultError(1000, "库存不足"))
		return
	}

	tp := sku.Price * float64(cast.ToInt(count))
	//判断是否可以使用优惠券
	belong, s, err := dao.GetSkuBelong(cast.ToInt64(skuId), cast.ToInt64(couponUserId), tp)
	if !belong {
		if s == "" {
			c.JSON(200, CreateResultError(500, "查询错误"))
			return
		} else {
			c.JSON(200, CreateResultError(500, s))
			return
		}
	}
	order := &domain.GoodsOrder{}
	order.SkuId = cast.ToInt64(skuId)
	order.Count = cast.ToInt64(count)
	order.CouponUserId = cast.ToInt64(couponUserId)
	order.ContactInformation = cast.ToString(contactInformation)

	order.OrderName = fmt.Sprint(sku.SkuName, "【x", count, "】")
	order.Price = sku.Price
	order.TotalPrice = sku.Price * float64(cast.ToInt(count))
	order.CreateBy = id
	order.CreateTime = time.Now()
	order, err = dao.CreateOrder(order)
	if err != nil {
		c.JSON(200, CreateResultError(1000, "创建订单失败"))
		return
	}
	c.JSON(200, CreateResultData(*order))

}

// PayBuyTest 支付回调模拟
func PayBuyTest(c *gin.Context) {
	id := GetUserIdByToken(c)
	if id == 0 {
		return
	}
	data := share.GetJsonAnyParam(c)
	orderId, _ := data("orderId")
	dao.OrderPaySuccess(cast.ToInt64(orderId), id)
}

// GetOrderList 获取订单列表
func GetOrderList(c *gin.Context) {
	id := GetUserIdByToken(c)
	if id == 0 {
		return
	}
	orders, err := dao.GetOrderByUserId(id)
	var ids = make([]int64, 0)
	for _, order := range orders {
		ids = append(ids, order.CouponUserId)
	}
	skus, err := manage.GetGoodsSkuListInId(ids)
	if err != nil {
		c.JSON(200, CreateResultError(1000, "查询失败"))
	}
	var vos = make([]vo.OrderVo, 0)
	for _, order := range orders {
		var vo vo.OrderVo
		vo.Order = order
		for _, sku := range skus {
			if order.CouponUserId == sku.Id {
				vo.Sku = sku
				break
			}
		}
		vos = append(vos, vo)
	}
	c.JSON(200, CreateResultData(map[string]interface{}{
		"vos": vos,
		"len": len(vos),
	}))
}
