package api

import (
	"gadmin/config"
	"gadmin/internal/admin/forms"
	"gadmin/internal/admin/service"
	"gadmin/internal/gorm/model"
	"gadmin/internal/gorm/query"
	"gadmin/utility/serializer"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func AdminRoleList(c *gin.Context) {
	var req forms.AdminRoleListReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}
	if err := forms.ParseParams(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	c.JSON(200, service.AdminRole.List(c, req))
}

func AdminRoleAuthOption(c *gin.Context) {
	var (
		//keys  []int
		lists []*forms.Option
	)
	//permissions, err := config.GetAllPermissions()
	permissions := config.GetAllOptions()

	//if err != nil {
	//	c.JSON(200, ErrorResponse(err))
	//	return
	//}

	//for k, _ := range config.AuthNameMap {
	//	keys = append(keys, k)
	//}
	//
	//sort.Ints(keys)

	for _, v := range permissions {
		lists = append(lists, &forms.Option{
			Value: v.ID,
			Label: v.Name,
			Name:  v.Name,
		})
	}

	c.JSON(200, serializer.Suc(lists))
}

func AdminRolePageOption(c *gin.Context) {

	lists := make(map[int32][]*forms.TreeOption)

	menuMap, err := GetAllMenuList(c)
	if err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}
	for systemId, items := range menuMap {
		for _, item := range items {
			if item.Meta.IsSuper {
				continue
			}
			menu := &forms.TreeOption{
				Key:      item.Id,
				Label:    item.Meta.Title,
				Children: []*forms.TreeOption{},
			}
			if len(item.Children) > 0 {
				for _, children := range item.Children {
					if children.Meta.IsSuper {
						continue
					}
					menu.Children = append(menu.Children, &forms.TreeOption{
						Key:   children.Id,
						Label: children.Meta.Title,
					})
				}
			}
			if _, ok := lists[systemId]; !ok {
				lists[systemId] = []*forms.TreeOption{menu}
			} else {
				lists[systemId] = append(lists[systemId], menu)
			}
		}
	}

	c.JSON(200, serializer.Suc(lists))
}

// AdminRoleOption 角色选项
func AdminRoleOption(c *gin.Context) {
	var (
		q     = query.Use(config.AdminDB).AdminRole
		m     = q.WithContext(c)
		lists []*model.AdminRole
		list  []forms.Option
		err   error
	)

	if err = m.Scan(&lists); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	for _, v := range lists {
		list = append(list, forms.Option{
			Value: v.ID,
			Label: v.Name,
			Name:  v.Name,
		})
	}

	c.JSON(200, serializer.Suc(list))
}

func AdminRoleEdit(c *gin.Context) {
	var req forms.AdminRoleEditReq
	if err := c.ShouldBind(&req); err != nil {
		logrus.Error(err)
		c.JSON(200, ErrorResponse(err))
		return
	}
	if err := forms.ParseParams(&req); err != nil {
		c.JSON(200, ErrorResponse(err))
		return
	}

	c.JSON(200, service.AdminRole.Edit(c, req))
}
