package models

import (
	"fmt"
	"log"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

// SysMenu 菜单权限表
type SysMenu struct {
	ID        uuid.UUID  `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
	ParentID  *uuid.UUID `gorm:"type:uuid" json:"parentId"`
	Name      string     `gorm:"type:varchar(50)" json:"name"`
	Path      string     `gorm:"type:varchar(200)" json:"path"`
	Component string     `gorm:"type:varchar(255)" json:"component"`
	Perms     string     `gorm:"type:varchar(100)" json:"perms"`      // 权限标识: system:user:list
	Icon      string     `gorm:"type:varchar(100)" json:"icon"`
	Type      string     `gorm:"type:varchar(1)" json:"type"`         // M:目录 C:菜单 F:按钮
	OrderNum  int        `gorm:"type:int" json:"orderNum"`
	Visible   string     `gorm:"type:varchar(1);default:'0'" json:"visible"` // 0:显示 1:隐藏
	Status    string     `gorm:"type:varchar(1);default:'0'" json:"status"`  // 0:正常 1:停用
	Children  []*SysMenu `gorm:"-" json:"children"`                          // 子菜单
}

// SysRoleMenu 角色和菜单关联表
type SysRoleMenu struct {
	RoleID uuid.UUID `gorm:"type:uuid;primary_key" json:"roleId"`
	MenuID uuid.UUID `gorm:"type:uuid;primary_key" json:"menuId"`
}

func InitSysMenuData(db *gorm.DB) {
	var count int64
	db.Model(&SysMenu{}).Count(&count)
	if count > 0 {
		// 增量检查: AI监控分析是否存在，如果不存在则添加
		addAIMenu(db)
		return
	}

	fmt.Println("Initializing Menu Data...")

	menus := []struct {
		Name      string
		Path      string
		Component string
		Icon      string
		Type      string
		OrderNum  int
		Perms     string
		Children  []struct {
			Name      string
			Path      string
			Component string
			Perms     string
			Type      string
			OrderNum  int
			Children  []struct {
				Name     string
				Perms    string
				Type     string
				OrderNum int
			}
		}
	}{
		{
			Name:      "资源与物联中心",
			Path:      "/resource",
			Component: "Layout",
			Type:      "M",
			Icon:      "Connection",
			OrderNum:  1,
			Children: []struct {
				Name      string
				Path      string
				Component string
				Perms     string
				Type      string
				OrderNum  int
				Children  []struct {
					Name     string
					Perms    string
					Type     string
					OrderNum int
				}
			}{
				{Name: "数据源配置", Path: "datasource", Component: "resource/DataSource", Perms: "resource:datasource:list", Type: "C", OrderNum: 1, Children: []struct {
					Name     string
					Perms    string
					Type     string
					OrderNum int
				}{
					{Name: "新增", Perms: "resource:datasource:add", Type: "F", OrderNum: 1},
					{Name: "修改", Perms: "resource:datasource:edit", Type: "F", OrderNum: 2},
					{Name: "删除", Perms: "resource:datasource:remove", Type: "F", OrderNum: 3},
				}},
				{Name: "设备管理", Path: "import", Component: "DeviceList", Perms: "resource:import:list", Type: "C", OrderNum: 2},
				{Name: "清洗公式模板", Path: "cleaning-template", Component: "resource/CleaningTemplate", Perms: "resource:cleaning-template:list", Type: "C", OrderNum: 3},
				{Name: "空间拓扑管理", Path: "topology", Component: "resource/Topology", Perms: "resource:topology:list", Type: "C", OrderNum: 4},
			},
		},
		{
			Name:      "监控与控制中心",
			Path:      "/monitor",
			Component: "Layout",
			Type:      "M",
			Icon:      "Monitor",
			OrderNum:  2,
			Children: []struct {
				Name      string
				Path      string
				Component string
				Perms     string
				Type      string
				OrderNum  int
				Children  []struct {
					Name     string
					Perms    string
					Type     string
					OrderNum int
				}
			}{
				{Name: "综合态势大屏", Path: "dashboard", Component: "monitor/Dashboard", Perms: "monitor:dashboard:list", Type: "C", OrderNum: 1},
				{Name: "告警规则配置", Path: "alarm-config", Component: "monitor/AlarmConfig", Perms: "monitor:alarm-config:list", Type: "C", OrderNum: 2},
				{Name: "实时告警台", Path: "alarms", Component: "monitor/AlarmConsole", Perms: "monitor:alarms:list", Type: "C", OrderNum: 3},
				{Name: "AI监控分析", Path: "ai-analysis", Component: "monitor/AIAnalysis", Perms: "monitor:ai-analysis:list", Type: "C", OrderNum: 4},
			},
		},
		{
			Name:      "能耗分析引擎",
			Path:      "/analysis",
			Component: "Layout",
			Type:      "M",
			Icon:      "TrendCharts",
			OrderNum:  3,
			Children: []struct {
				Name      string
				Path      string
				Component string
				Perms     string
				Type      string
				OrderNum  int
				Children  []struct {
					Name     string
					Perms    string
					Type     string
					OrderNum int
				}
			}{
				{Name: "统计报表", Path: "report", Component: "analysis/Report", Perms: "analysis:report:list", Type: "C", OrderNum: 1},
				{Name: "损耗与能效分析", Path: "loss", Component: "analysis/LossAnalysis", Perms: "analysis:loss:list", Type: "C", OrderNum: 2},
			},
		},
		{
			Name:      "运维管理",
			Path:      "/ops",
			Component: "Layout",
			Type:      "M",
			Icon:      "Notebook",
			OrderNum:  4,
			Children: []struct {
				Name      string
				Path      string
				Component string
				Perms     string
				Type      string
				OrderNum  int
				Children  []struct {
					Name     string
					Perms    string
					Type     string
					OrderNum int
				}
			}{
				{Name: "巡检台账", Path: "inspection", Component: "ops/Inspection", Perms: "ops:inspection:list", Type: "C", OrderNum: 1},
				{Name: "操作审计日志", Path: "audit", Component: "ops/AuditLog", Perms: "ops:audit:list", Type: "C", OrderNum: 2},
				{Name: "数据备份", Path: "backup", Component: "ops/DataBackup", Perms: "ops:backup:list", Type: "C", OrderNum: 3},
				{Name: "系统日志", Path: "logs", Component: "ops/LogViewer", Perms: "ops:logs:list", Type: "C", OrderNum: 4},
			},
		},
		{
			Name:      "系统设置",
			Path:      "/system",
			Component: "Layout",
			Type:      "M",
			Icon:      "Setting",
			OrderNum:  5,
			Children: []struct {
				Name      string
				Path      string
				Component string
				Perms     string
				Type      string
				OrderNum  int
				Children  []struct {
					Name     string
					Perms    string
					Type     string
					OrderNum int
				}
			}{
				{Name: "用户管理", Path: "user", Component: "system/UserList", Perms: "system:user:list", Type: "C", OrderNum: 1, Children: []struct {
					Name     string
					Perms    string
					Type     string
					OrderNum int
				}{
					{Name: "用户新增", Perms: "system:user:add", Type: "F", OrderNum: 1},
					{Name: "用户修改", Perms: "system:user:edit", Type: "F", OrderNum: 2},
					{Name: "用户删除", Perms: "system:user:remove", Type: "F", OrderNum: 3},
				}},
				{Name: "角色管理", Path: "role", Component: "system/RoleList", Perms: "system:role:list", Type: "C", OrderNum: 2, Children: []struct {
					Name     string
					Perms    string
					Type     string
					OrderNum int
				}{
					{Name: "角色新增", Perms: "system:role:add", Type: "F", OrderNum: 1},
					{Name: "角色修改", Perms: "system:role:edit", Type: "F", OrderNum: 2},
					{Name: "角色删除", Perms: "system:role:remove", Type: "F", OrderNum: 3},
				}},
				{Name: "字典与参数", Path: "settings", Component: "system/Settings", Perms: "system:settings:list", Type: "C", OrderNum: 3},
			},
		},
	}

	tx := db.Begin()

	// Find admin role to assign perms
	var adminRole SysRole
	if err := tx.Where("role_key = ?", "admin").First(&adminRole).Error; err != nil {
		tx.Rollback()
		log.Printf("Admin role not found when initializing menus: %v", err)
		return
	}

	for _, m := range menus {
		menu := SysMenu{
			Name:      m.Name,
			Path:      m.Path,
			Component: m.Component,
			Icon:      m.Icon,
			Type:      m.Type,
			OrderNum:  m.OrderNum,
			Visible:   "0",
			Status:    "0",
		}
		if err := tx.Create(&menu).Error; err != nil {
			tx.Rollback()
			log.Printf("Error creating menu %s: %v", m.Name, err)
			return
		}
		
		// Link to admin
		tx.Create(&SysRoleMenu{RoleID: adminRole.ID, MenuID: menu.ID})

		for _, c := range m.Children {
			child := SysMenu{
				ParentID:  &menu.ID,
				Name:      c.Name,
				Path:      c.Path,
				Component: c.Component,
				Perms:     c.Perms,
				Type:      c.Type,
				OrderNum:  c.OrderNum,
				Visible:   "0",
				Status:    "0",
			}
			if err := tx.Create(&child).Error; err != nil {
				tx.Rollback()
				log.Printf("Error creating menu %s: %v", c.Name, err)
				return
			}
			// Link to admin
			tx.Create(&SysRoleMenu{RoleID: adminRole.ID, MenuID: child.ID})

			for _, btn := range c.Children {
				btnMenu := SysMenu{
					ParentID: &child.ID,
					Name:     btn.Name,
					Perms:    btn.Perms,
					Type:     btn.Type,
					OrderNum: btn.OrderNum,
					Visible:  "0",
					Status:   "0",
				}
				if err := tx.Create(&btnMenu).Error; err != nil {
					tx.Rollback()
					log.Printf("Error creating button %s: %v", btn.Name, err)
					return
				}
				// Link to admin
				tx.Create(&SysRoleMenu{RoleID: adminRole.ID, MenuID: btnMenu.ID})
			}
		}
	}

	tx.Commit()
	fmt.Println("Menu Data Initialized")
}

func addAIMenu(db *gorm.DB) {
	// 1. Check if menu exists
	var count int64
	db.Model(&SysMenu{}).Where("path = ?", "ai-analysis").Count(&count)
	if count > 0 {
		return
	}

	fmt.Println("Adding missing AI Analysis menu...")

	// 2. Find Parent "监控与控制中心" (path='/monitor')
	var parent SysMenu
	if err := db.Where("path = ?", "/monitor").First(&parent).Error; err != nil {
		fmt.Printf("Parent menu not found: %v\n", err)
		return 
	}

	// 3. Create Menu
	menu := SysMenu{
		ParentID:  &parent.ID,
		Name:      "AI监控分析",
		Path:      "ai-analysis",
		Component: "monitor/AIAnalysis",
		Perms:     "monitor:ai-analysis:list",
		Type:      "C",
		OrderNum:  4,
		Visible:   "0",
		Status:    "0",
	}
	if err := db.Create(&menu).Error; err != nil {
		fmt.Printf("Failed to create AI menu: %v\n", err)
		return
	}

	// 4. Assign to Admin
	var adminRole SysRole
	if err := db.Where("role_key = ?", "admin").First(&adminRole).Error; err == nil {
		db.Create(&SysRoleMenu{RoleID: adminRole.ID, MenuID: menu.ID})
		fmt.Println("AI Analysis menu added and assigned to admin.")
	}
}
