package api

import (
	"fmt"
	"github.com/kataras/iris/v12"
	"main/utils"
	"regexp"
)

func getMenu(ctx iris.Context) {
	var resTmp []subMenu
	var res []resMenu
	user := utils.GetLoginUser(ctx)
	if utils.DataIsNil(user) {
		return
	}
	if len(utils.MenuList) == 0 {
		utils.UpdateMenuList()
	}
	resTmp = append(resTmp, subMenu{MenuId: "000", Name: "首页", Icon: "bi-emoji-wink", Path: "/", RouteOnly: false})
	for _, menu := range utils.MenuList {
		patternWhiteList := fmt.Sprintf("^%s,|,%s,|,%s$|%s", user.Username, user.Username, user.Username, user.Username)
		regWhiteList := regexp.MustCompile(patternWhiteList)
		patternUserType := fmt.Sprintf("^%s,|,%s,|,%s$|%s", user.Type, user.Type, user.Type, user.Type)
		regUserType := regexp.MustCompile(patternUserType)
		if match := regWhiteList.MatchString(menu.WhiteList); match || regUserType.MatchString(menu.UserType) {
			resTmp = append(resTmp, subMenu{
				MenuId:    menu.MenuId,
				Name:      menu.Name,
				Icon:      menu.Icon,
				Path:      menu.Path,
				RouteOnly: menu.RouteOnly,
			})
		}
	}
	for _, menu := range resTmp {
		if menu.RouteOnly {
			res = append(res, resMenu{MenuId: menu.MenuId, Name: menu.Name, Icon: menu.Icon, Path: menu.Path, RouteOnly: menu.RouteOnly})
			continue
		}
		if len(menu.MenuId) == 3 {
			var tmp []subMenu
			for _, sub := range resTmp {
				if len(sub.MenuId) == 5 && sub.MenuId[0:3] == menu.MenuId && !sub.RouteOnly {
					tmp = append(tmp, sub)
				}
			}
			res = append(res, resMenu{MenuId: menu.MenuId, Name: menu.Name, Icon: menu.Icon, Path: menu.Path, Detail: tmp})
		}
	}
	err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
	if utils.ErrHandle(ctx, err) {
		return
	}
}
