package controllers

import (
	"ems-backend/models"
	"fmt"
	"net/http"
	"sort"

	"github.com/gin-gonic/gin"
)

// GetRouters 获取用户路由信息
func GetRouters(c *gin.Context) {
	// 1. 获取当前用户（由 Auth middleware 写入 Context）
	username := c.GetString("username")
	if username == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
		return
	}

	// 2. 获取用户角色
	// 如果是 admin，返回所有菜单
	// 否则根据角色关联查询菜单
	var menuList []models.SysMenu

	if username == "admin" {
		models.DB.Order("order_num").Find(&menuList)
		// 兜底逻辑：如果 admin 用户没有任何菜单数据，或者数据明显过少（脏数据），尝试初始化
		if len(menuList) < 5 {
            // 先清空旧数据，防止 ID 冲突或重复
            models.DB.Exec("DELETE FROM sys_role_menus")
            models.DB.Exec("DELETE FROM sys_menus")
			models.InitSysMenuData(models.DB)
			models.DB.Order("order_num").Find(&menuList)
		}
	} else {
		// 查找用户 -> 角色 -> 菜单
		var user models.User
		if err := models.DB.Where("username = ?", username).First(&user).Error; err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "User not found"})
			return
		}

		var menuIds []string
		models.DB.Table("sys_role_menus rm").
			Select("rm.menu_id").
			Joins("JOIN sys_user_roles ur ON ur.role_id = rm.role_id").
			Where("ur.user_id = ?", user.ID).
			Pluck("rm.menu_id", &menuIds)
			
		if len(menuIds) > 0 {
			models.DB.Where("id IN ? AND status = '0'", menuIds).Order("order_num").Find(&menuList)
		}
	}

	// 3. 构建菜单树和权限列表
	fmt.Printf("GetRouters: found %d menus for user %s\n", len(menuList), username)
	menuTree := buildMenuTree(menuList)
	perms := extractPerms(menuList)

	c.JSON(http.StatusOK, gin.H{
		"menus": menuTree,
		"permissions": perms,
	})
}

// GetMenuTree 获取所有菜单树（用于角色分配权限）
func GetMenuTree(c *gin.Context) {
	var menuList []models.SysMenu
	models.DB.Order("order_num").Find(&menuList)
	
	// Convert to tree structure appropriate for frontend tree select
	// We can reuse buildMenuTree but ensure we return all fields needed
	menuTree := buildMenuTree(menuList)
	
	c.JSON(http.StatusOK, menuTree)
}

// GetRoleMenuIds 获取指定角色的菜单ID集合
func GetRoleMenuIds(c *gin.Context) {
	roleId := c.Param("roleId")
	
	var menuIds []string
	models.DB.Model(&models.SysRoleMenu{}).
		Where("role_id = ?", roleId).
		Pluck("menu_id", &menuIds)
		
	c.JSON(http.StatusOK, menuIds)
}


func buildMenuTree(menus []models.SysMenu) []models.SysMenu {
	var tree []models.SysMenu
	menuMap := make(map[string]*models.SysMenu)

	// 1. Initialize map
	for i := range menus {
		menus[i].Children = []*models.SysMenu{}
		menuMap[menus[i].ID.String()] = &menus[i]
	}

	// 2. Build tree structure
	for i := range menus {
		menu := &menus[i]
		if menu.ParentID != nil {
			if parent, ok := menuMap[menu.ParentID.String()]; ok {
				parent.Children = append(parent.Children, menu)
			}
		}
	}

	// 3. Collect roots
	for i := range menus {
		if menus[i].ParentID == nil {
			tree = append(tree, menus[i])
		}
	}
	
	// 对每一层的 Children 进行排序
	sortChildren(tree)
	
	return tree
}

func sortChildren(menus []models.SysMenu) {
	sort.Slice(menus, func(i, j int) bool {
		return menus[i].OrderNum < menus[j].OrderNum
	})
	for _, menu := range menus {
		if len(menu.Children) > 0 {
			// menu.Children 是 []*SysMenu，需要转换一下才能排序，或者直接用 slice 自定义排序
			sortChildrenPtr(menu.Children)
		}
	}
}

func sortChildrenPtr(menus []*models.SysMenu) {
	sort.Slice(menus, func(i, j int) bool {
		return menus[i].OrderNum < menus[j].OrderNum
	})
	for _, menu := range menus {
		if len(menu.Children) > 0 {
			sortChildrenPtr(menu.Children)
		}
	}
}

func extractPerms(menus []models.SysMenu) []string {
	var perms []string
	for _, menu := range menus {
		if menu.Perms != "" {
			perms = append(perms, menu.Perms)
		}
	}
	return perms
}
