package router

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

func DetailRouter(engine *gin.RouterGroup) {
	user := engine.Group("/detail")
	//user.GET("/search", GetSearchByKey)
	PushRouter(user, "GET", "/search", GetSearchByKey)
	//获取文章详情
	//user.GET("/:id", GetDetailData)
	//PushRouter(user, "GET", "/:id", GetDetailData)
	PushRouter(user, "GET", "/:id", GetDetailInfo)
}

// GetDetailData 获取文章详情
func GetDetailData(c *gin.Context) {
	id, err2 := strconv.Atoi(c.Param("id"))
	if err2 != nil {
		c.JSON(200, CreateResultError(400, "param 参数错误"))
		return
	}

	vo, err := dao.SelectGoodsDetailById(int64(id))
	if err != nil || vo.DetailSkuVo.NowSkuId == 0 {
		c.JSON(200, CreateResultError(400, "查询失败"))
		return
	}

	c.JSON(200, CreateResultData(vo))
}

// GetDetailInfo 获取文章详情
func GetDetailInfo(c *gin.Context) {
	id, err2 := strconv.Atoi(c.Param("id"))
	if err2 != nil {
		c.JSON(200, CreateResultError(400, "param 参数错误"))
		return
	}

	vo, err := dao.SelectSkuInfoBySkuId(int64(id))
	if err != nil || vo.Sku.Id == 0 {
		c.JSON(200, CreateResultError(400, "查询失败"))
		return
	}

	c.JSON(200, CreateResultData(vo))
}

func GetSearchByKey(c *gin.Context) {
	key := c.Query("key")
	pageNum := c.Query("pageNum")
	pageSize := c.Query("pageSize")

	if key == "" {
		var sku domain.GoodsSku
		goodsSku, err := manage.GetGoodsSkuList(sku, cast.ToInt(pageNum), cast.ToInt(pageSize))
		if err != nil {
			c.JSON(200, CreateResultError(400, "查询失败"))
			return
		}
		c.JSON(200, CreateResultData(goodsSku))
		return
	}
	vo, s, err := dao.GetSkuByKey(key, cast.ToInt(pageNum), cast.ToInt(pageSize))
	if err != nil {
		fmt.Println("查询异常：", s)
		c.JSON(200, CreateResultError(400, "查询失败"))
		return
	}
	c.JSON(200, CreateResultData(vo))
	return
}
