package router

import (
	"context"
	"demo/data/dao/back"
	"demo/data/dao/manage"
	"demo/share"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

func BackRouter(engine *gin.RouterGroup) {
	user := engine.Group("/back")
	PushRouter(user, "GET", "/role/authority", GetRoleAndAuthority)
	PushRouter(user, "GET", "/role/menu", GetRoleMenu)
	PushRouter(user, "PUT", "/gen/column", SaveGenTableColumnList)
}

var ctx = context.Background()

// GetRoleAndAuthority 获取用户权限映射表
func GetRoleAndAuthority(c *gin.Context) {
	id := GetUserIdByToken(c)
	userId, err := back.GetAuthorityByUserId(id)
	if err != nil {
		c.JSON(200, CreateResultError(400, "获取角色权限失败"))
		return
	}
	c.JSON(200, CreateResultData(userId))
}

// GetRoleMenu 获取用户菜单
func GetRoleMenu(c *gin.Context) {
	id := GetUserIdByToken(c)
	userId, err := back.GetMenuByUserId(id)
	if err != nil {
		c.JSON(200, CreateResultError(400, "获取菜单失败"))
		return
	}
	c.JSON(200, CreateResultData(userId))
}

func SaveGenTableColumnList(c *gin.Context) {
	data := share.GetJsonAnyParam(c)
	genTableColumnParam, _ := data("list")
	//genTableColumnParam判断是否位数组
	arr, ok := genTableColumnParam.([]interface{})
	if !ok {
		c.JSON(200, CreateResultError(400, "参数错误"))
		return
	}
	for i := 0; i < len(arr); i++ {
		data, ok := arr[i].(map[string]interface{})
		if !ok {
			fmt.Println("666:", arr[i], ok)
			continue
		}
		manage.SetGenTableColumn(UtilStructToMap(data), cast.ToInt64(data["id"]))
	}
	c.JSON(200, CreateResult())
}

func BaseBackRouter(group *gin.RouterGroup) {
	//文章
	BaseArticleRouter(group)
	BaseArticleTagRouter(group)
	BaseArticleTopicRouter(group)
	//权限 or 菜单
	BaseBackRoleRouter(group)
	BaseBackAuthorityRouter(group)
	BaseBackRoleAuthorityRouter(group)
	BaseBackMenuRouter(group)
	BaseBackRoleMenuRouter(group)
	//字典
	BaseDictDataRouter(group)
	BaseDictTypeRouter(group)
	//自动生成
	BaseGenTableRouter(group)
	BaseGenTableColumnRouter(group)
	//商品设置
	BaseGoodsTypeRouter(group)
	BaseGoodsRouter(group)
	BaseGoodsIntroductionRouter(group)
	BaseGoodsCommodityAreaRouter(group)
	BaseGoodsSkuRouter(group)
	BaseGoodsSkuCardRouter(group)
	BaseGoodsTagRouter(group)
	BaseGoodsOrderRouter(group)
	//优惠券
	BaseGoodsCouponRouter(group)
	BaseGoodsCouponUserRouter(group)
	//废弃
	//BaseManageUserRouter(group)
	//商城显示
	BaseShopAdviceCarouselRouter(group)
	BaseShopTopicRouter(group)
	BaseShopTopicSkuRouter(group)
	//用户
	BaseUserRouter(group)
	BaseUserWalletRouter(group)
}
