package system

import (
	"context"

	"kra/internal/biz/system"
	"kra/internal/data/model"

	"github.com/pkg/errors"
	"gorm.io/gorm"
)

const initOrderMenu = initOrderAuthority + 1

type initMenu struct{}

func NewInitMenu() system.SubInitializer {
	return &initMenu{}
}

func (i *initMenu) InitializerName() string {
	return model.TableNameSysBaseMenu
}

func (i *initMenu) MigrateTable(ctx context.Context) (context.Context, error) {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return ctx, system.ErrMissingDBContext
	}
	return ctx, db.AutoMigrate(&model.SysBaseMenu{})
}

func (i *initMenu) TableCreated(ctx context.Context) bool {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return false
	}
	return db.Migrator().HasTable(&model.SysBaseMenu{})
}

func (i *initMenu) InitializeData(ctx context.Context) (next context.Context, err error) {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return ctx, system.ErrMissingDBContext
	}

	// 定义所有父级菜单
	allMenus := []model.SysBaseMenu{
		{MenuLevel: 0, Hidden: false, ParentID: 0, Path: "dashboard", Name: "dashboard", Component: "view/dashboard/index.vue", Sort: 1, Title: "仪表盘", Icon: "odometer"},
		{MenuLevel: 0, Hidden: false, ParentID: 0, Path: "about", Name: "about", Component: "view/about/index.vue", Sort: 9, Title: "关于我们", Icon: "info-filled"},
		{MenuLevel: 0, Hidden: false, ParentID: 0, Path: "admin", Name: "superAdmin", Component: "view/superAdmin/index.vue", Sort: 3, Title: "超级管理员", Icon: "user"},
		{MenuLevel: 0, Hidden: true, ParentID: 0, Path: "person", Name: "person", Component: "view/person/person.vue", Sort: 4, Title: "个人信息", Icon: "message"},
		{MenuLevel: 0, Hidden: false, ParentID: 0, Path: "example", Name: "example", Component: "view/example/index.vue", Sort: 7, Title: "示例文件", Icon: "management"},
		{MenuLevel: 0, Hidden: false, ParentID: 0, Path: "systemTools", Name: "systemTools", Component: "view/systemTools/index.vue", Sort: 5, Title: "系统工具", Icon: "tools"},
		{MenuLevel: 0, Hidden: false, ParentID: 0, Path: "https://github.com/tx7do/kratos-admin", Name: "https://github.com/tx7do/kratos-admin", Component: "/", Sort: 0, Title: "官方网站", Icon: "home-filled"},
		{MenuLevel: 0, Hidden: false, ParentID: 0, Path: "state", Name: "state", Component: "view/system/state.vue", Sort: 8, Title: "服务器状态", Icon: "cloudy"},
		{MenuLevel: 0, Hidden: false, ParentID: 0, Path: "plugin", Name: "plugin", Component: "view/routerHolder.vue", Sort: 6, Title: "插件系统", Icon: "cherry"},
	}

	// 先创建父级菜单
	if err = db.Create(&allMenus).Error; err != nil {
		return ctx, errors.Wrap(err, model.TableNameSysBaseMenu+"父级菜单初始化失败!")
	}

	// 建立菜单映射
	menuNameMap := make(map[string]int64)
	for _, menu := range allMenus {
		menuNameMap[menu.Name] = menu.ID
	}

	// 定义子菜单
	childMenus := []model.SysBaseMenu{
		// superAdmin子菜单
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["superAdmin"], Path: "authority", Name: "authority", Component: "view/superAdmin/authority/authority.vue", Sort: 1, Title: "角色管理", Icon: "avatar"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["superAdmin"], Path: "menu", Name: "menu", Component: "view/superAdmin/menu/menu.vue", Sort: 2, Title: "菜单管理", Icon: "tickets", KeepAlive: true},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["superAdmin"], Path: "api", Name: "api", Component: "view/superAdmin/api/api.vue", Sort: 3, Title: "api管理", Icon: "platform", KeepAlive: true},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["superAdmin"], Path: "user", Name: "user", Component: "view/superAdmin/user/user.vue", Sort: 4, Title: "用户管理", Icon: "coordinate"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["superAdmin"], Path: "dictionary", Name: "dictionary", Component: "view/superAdmin/dictionary/sysDictionary.vue", Sort: 5, Title: "字典管理", Icon: "notebook"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["superAdmin"], Path: "operation", Name: "operation", Component: "view/superAdmin/operation/sysOperationRecord.vue", Sort: 6, Title: "操作历史", Icon: "pie-chart"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["superAdmin"], Path: "sysParams", Name: "sysParams", Component: "view/superAdmin/params/sysParams.vue", Sort: 7, Title: "参数管理", Icon: "compass"},

		// example子菜单
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["example"], Path: "upload", Name: "upload", Component: "view/example/upload/upload.vue", Sort: 5, Title: "媒体库（上传下载）", Icon: "upload"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["example"], Path: "breakpoint", Name: "breakpoint", Component: "view/example/breakpoint/breakpoint.vue", Sort: 6, Title: "断点续传", Icon: "upload-filled"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["example"], Path: "customer", Name: "customer", Component: "view/example/customer/customer.vue", Sort: 7, Title: "客户列表（资源示例）", Icon: "avatar"},

		// systemTools子菜单
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["systemTools"], Path: "autoCode", Name: "autoCode", Component: "view/systemTools/autoCode/index.vue", Sort: 1, Title: "代码生成器", Icon: "cpu", KeepAlive: true},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["systemTools"], Path: "formCreate", Name: "formCreate", Component: "view/systemTools/formCreate/index.vue", Sort: 3, Title: "表单生成器", Icon: "magic-stick", KeepAlive: true},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["systemTools"], Path: "system", Name: "system", Component: "view/systemTools/system/system.vue", Sort: 4, Title: "系统配置", Icon: "operation"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["systemTools"], Path: "autoCodeAdmin", Name: "autoCodeAdmin", Component: "view/systemTools/autoCodeAdmin/index.vue", Sort: 2, Title: "自动化代码管理", Icon: "magic-stick"},
		{MenuLevel: 1, Hidden: true, ParentID: menuNameMap["systemTools"], Path: "autoCodeEdit/:id", Name: "autoCodeEdit", Component: "view/systemTools/autoCode/index.vue", Sort: 0, Title: "自动化代码-${id}", Icon: "magic-stick"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["systemTools"], Path: "autoPkg", Name: "autoPkg", Component: "view/systemTools/autoPkg/autoPkg.vue", Sort: 0, Title: "模板配置", Icon: "folder"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["systemTools"], Path: "exportTemplate", Name: "exportTemplate", Component: "view/systemTools/exportTemplate/exportTemplate.vue", Sort: 5, Title: "导出模板", Icon: "reading"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["systemTools"], Path: "picture", Name: "picture", Component: "view/systemTools/autoCode/picture.vue", Sort: 6, Title: "AI页面绘制", Icon: "picture-filled"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["systemTools"], Path: "mcpTool", Name: "mcpTool", Component: "view/systemTools/autoCode/mcp.vue", Sort: 7, Title: "Mcp Tools模板", Icon: "magnet"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["systemTools"], Path: "mcpTest", Name: "mcpTest", Component: "view/systemTools/autoCode/mcpTest.vue", Sort: 7, Title: "Mcp Tools测试", Icon: "partly-cloudy"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["systemTools"], Path: "sysVersion", Name: "sysVersion", Component: "view/systemTools/version/version.vue", Sort: 8, Title: "版本管理", Icon: "server"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["systemTools"], Path: "sysError", Name: "sysError", Component: "view/systemTools/sysError/sysError.vue", Sort: 9, Title: "错误日志", Icon: "warn"},

		// plugin子菜单
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["plugin"], Path: "https://github.com/tx7do/kratos-admin", Name: "https://github.com/tx7do/kratos-admin", Component: "https://github.com/tx7do/kratos-admin", Sort: 0, Title: "插件市场", Icon: "shop"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["plugin"], Path: "installPlugin", Name: "installPlugin", Component: "view/systemTools/installPlugin/index.vue", Sort: 1, Title: "插件安装", Icon: "box"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["plugin"], Path: "pubPlug", Name: "pubPlug", Component: "view/systemTools/pubPlug/pubPlug.vue", Sort: 3, Title: "打包插件", Icon: "files"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["plugin"], Path: "plugin-email", Name: "plugin-email", Component: "plugin/email/view/index.vue", Sort: 4, Title: "邮件插件", Icon: "message"},
		{MenuLevel: 1, Hidden: false, ParentID: menuNameMap["plugin"], Path: "anInfo", Name: "anInfo", Component: "plugin/announcement/view/info.vue", Sort: 5, Title: "公告管理[示例]", Icon: "scaleToOriginal"},
	}

	// 创建子菜单
	if err = db.Create(&childMenus).Error; err != nil {
		return ctx, errors.Wrap(err, model.TableNameSysBaseMenu+"子菜单初始化失败!")
	}

	// 组合所有菜单作为返回结果
	allEntities := append(allMenus, childMenus...)
	next = context.WithValue(ctx, i.InitializerName(), allEntities)
	return next, nil
}

func (i *initMenu) DataInserted(ctx context.Context) bool {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {
		return false
	}
	if errors.Is(db.Where("path = ?", "autoPkg").First(&model.SysBaseMenu{}).Error, gorm.ErrRecordNotFound) {
		return false
	}
	return true
}
