package router

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

func UserRouth(engine *gin.RouterGroup) {
	user := engine.Group("/user")
	{
		user.GET("/info", GetUserInfo)
		user.GET("/wallet", GetUserPurse)
		user.PUT("/name", SetNameValue)
		user.POST("/order", GetUserOrder)
	}
}

// GetUserInfo 获取用户的个人信息
func GetUserInfo(c *gin.Context) {
	header := c.GetHeader("auth-sign")
	if header == "" {
		c.JSON(200, CreateResultError(401, "用户未登录"))
		return
	}
	claims, err := share.ParseToken(header)
	if err != nil {
		c.JSON(200, CreateResultError(401, "用户未登录"))
		return
	}
	var userInfo = configs.User{}
	_, err = configs.Engine.Table("user").Where("id = ?", claims["iss"]).Get(&userInfo)
	if err != nil {
		c.JSON(200, CreateResultError(401, "用户未登录"))
		return
	}
	c.JSON(200, CreateResultData(map[string]any{
		"info": userInfo,
	}))
}

func GetUserPurse(c *gin.Context) {
	id := GetUserIdByToken(c)
	if id == 0 {
		return
	}
	var vo vo.UserWalletVo
	userWallet, err := dao.GetUserWalletByUserId(id)
	if err != nil {
		c.JSON(200, CreateResultError(500, "获取钱包失败"))
	}
	vo.Wallet = userWallet
	vo.CouponUserJDM, err = dao.GetUserCouponByUserId(id)
	if err != nil {
		c.JSON(200, CreateResultError(500, "获取优惠券失败"))
	}
	c.JSON(200, CreateResultData(vo))
}
func SetNameValue(c *gin.Context) {
	id := GetUserIdByToken(c)
	if id == 0 {
		return
	}
	name := c.Query("name")
	fmt.Println(name)
	_, b, err := manage.SetUser(map[string]interface{}{"name": name}, id)
	if err != nil {
		println(err.Error())
		c.JSON(200, CreateResultError(500, "修改失败"))
		return
	}
	if b {
		c.JSON(200, CreateResult())
	} else {
		c.JSON(200, CreateResultError(500, "修改失败"))
	}
}

// GetUserOrder 获取用户订单信息
func GetUserOrder(c *gin.Context) {
	id := GetUserIdByToken(c)
	if id == 0 {
		return
	}
	data := share.GetJsonAnyParam(c)
	pageNum, _ := data("pageNum")
	pageSize, _ := data("pageSize")
	state, _ := data("state")
	vo, err := dao.GetListGoodsOrder(cast.ToString(state), id, cast.ToInt(pageNum), cast.ToInt(pageSize))
	if err != nil {
		c.JSON(200, CreateResultError(500, "获取订单失败"))
	}
	c.JSON(200, CreateResultData(vo))
}
