﻿-- =============================================
-- Admin Database Initialization Script
-- Framework Template - MiAssessment
-- 
-- This script creates all tables for the Admin database
-- and inserts default data (admin user, roles, permissions, menus)
--
-- Requirements: 2.1-2.13, 13.1-13.10
-- =============================================

USE [MiAssessment_Admin];
GO

-- =============================================
-- 1. Create Departments Table
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[departments]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[departments] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [ParentId] BIGINT NOT NULL DEFAULT 0,
        [Name] NVARCHAR(100) NOT NULL,
        [Code] VARCHAR(50) NULL,
        [Description] NVARCHAR(500) NULL,
        [SortOrder] INT NOT NULL DEFAULT 0,
        [Status] TINYINT NOT NULL DEFAULT 1,
        [CreatedAt] DATETIME NOT NULL DEFAULT GETDATE(),
        [UpdatedAt] DATETIME NULL,
        CONSTRAINT [PK_departments] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    PRINT N'Table departments created successfully';
END
GO

-- =============================================
-- 2. Create Admin Users Table
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[admin_users]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[admin_users] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [Username] VARCHAR(50) NOT NULL,
        [PasswordHash] VARCHAR(255) NOT NULL,
        [RealName] NVARCHAR(50) NULL,
        [Avatar] VARCHAR(500) NULL,
        [Email] VARCHAR(100) NULL,
        [Phone] VARCHAR(20) NULL,
        [DepartmentId] BIGINT NULL,
        [Status] TINYINT NOT NULL DEFAULT 1,
        [LastLoginTime] DATETIME NULL,
        [LastLoginIp] VARCHAR(50) NULL,
        [LoginFailCount] INT NOT NULL DEFAULT 0,
        [LockoutEnd] DATETIME NULL,
        [CreatedAt] DATETIME NOT NULL DEFAULT GETDATE(),
        [UpdatedAt] DATETIME NULL,
        [CreatedBy] BIGINT NULL,
        [Remark] NVARCHAR(500) NULL,
        CONSTRAINT [PK_admin_users] PRIMARY KEY CLUSTERED ([Id] ASC),
        CONSTRAINT [FK_admin_users_departments] FOREIGN KEY ([DepartmentId]) 
            REFERENCES [dbo].[departments] ([Id]) ON DELETE SET NULL
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [IX_admin_users_username] ON [dbo].[admin_users] ([Username] ASC);
    PRINT N'Table admin_users created successfully';
END
GO

-- =============================================
-- 3. Create Roles Table
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[roles]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[roles] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [Name] NVARCHAR(50) NOT NULL,
        [Code] VARCHAR(50) NOT NULL,
        [Description] NVARCHAR(500) NULL,
        [SortOrder] INT NOT NULL DEFAULT 0,
        [Status] TINYINT NOT NULL DEFAULT 1,
        [IsSystem] BIT NOT NULL DEFAULT 0,
        [CreatedAt] DATETIME NOT NULL DEFAULT GETDATE(),
        [UpdatedAt] DATETIME NULL,
        CONSTRAINT [PK_roles] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [IX_roles_code] ON [dbo].[roles] ([Code] ASC);
    PRINT N'Table roles created successfully';
END
GO

-- =============================================
-- 4. Create Permissions Table
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[permissions]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[permissions] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [Name] NVARCHAR(100) NOT NULL,
        [Code] VARCHAR(100) NOT NULL,
        [Module] VARCHAR(50) NULL,
        [Description] NVARCHAR(500) NULL,
        [CreatedAt] DATETIME NOT NULL DEFAULT GETDATE(),
        CONSTRAINT [PK_permissions] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [IX_permissions_code] ON [dbo].[permissions] ([Code] ASC);
    PRINT N'Table permissions created successfully';
END
GO

-- =============================================
-- 5. Create Menus Table
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[menus]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[menus] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [ParentId] BIGINT NOT NULL DEFAULT 0,
        [Name] NVARCHAR(50) NOT NULL,
        [Path] VARCHAR(200) NULL,
        [Component] VARCHAR(200) NULL,
        [Icon] VARCHAR(100) NULL,
        [MenuType] TINYINT NOT NULL DEFAULT 1,
        [Permission] VARCHAR(100) NULL,
        [SortOrder] INT NOT NULL DEFAULT 0,
        [Status] TINYINT NOT NULL DEFAULT 1,
        [IsExternal] BIT NOT NULL DEFAULT 0,
        [IsCache] BIT NOT NULL DEFAULT 1,
        [CreatedAt] DATETIME NOT NULL DEFAULT GETDATE(),
        [UpdatedAt] DATETIME NULL,
        CONSTRAINT [PK_menus] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE NONCLUSTERED INDEX [IX_menus_parent_sort] ON [dbo].[menus] ([ParentId] ASC, [SortOrder] ASC);
    PRINT N'Table menus created successfully';
END
GO

-- =============================================
-- 6. Create Admin User Roles Table
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[admin_user_roles]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[admin_user_roles] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [AdminUserId] BIGINT NOT NULL,
        [RoleId] BIGINT NOT NULL,
        CONSTRAINT [PK_admin_user_roles] PRIMARY KEY CLUSTERED ([Id] ASC),
        CONSTRAINT [FK_admin_user_roles_admin_users] FOREIGN KEY ([AdminUserId]) 
            REFERENCES [dbo].[admin_users] ([Id]) ON DELETE CASCADE,
        CONSTRAINT [FK_admin_user_roles_roles] FOREIGN KEY ([RoleId]) 
            REFERENCES [dbo].[roles] ([Id]) ON DELETE CASCADE
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [IX_admin_user_roles_unique] ON [dbo].[admin_user_roles] ([AdminUserId] ASC, [RoleId] ASC);
    PRINT N'Table admin_user_roles created successfully';
END
GO

-- =============================================
-- 7. Create Role Menus Table
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[role_menus]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[role_menus] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [RoleId] BIGINT NOT NULL,
        [MenuId] BIGINT NOT NULL,
        CONSTRAINT [PK_role_menus] PRIMARY KEY CLUSTERED ([Id] ASC),
        CONSTRAINT [FK_role_menus_roles] FOREIGN KEY ([RoleId]) 
            REFERENCES [dbo].[roles] ([Id]) ON DELETE CASCADE,
        CONSTRAINT [FK_role_menus_menus] FOREIGN KEY ([MenuId]) 
            REFERENCES [dbo].[menus] ([Id]) ON DELETE CASCADE
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [IX_role_menus_unique] ON [dbo].[role_menus] ([RoleId] ASC, [MenuId] ASC);
    PRINT N'Table role_menus created successfully';
END
GO

-- =============================================
-- 8. Create Role Permissions Table
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[role_permissions]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[role_permissions] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [RoleId] BIGINT NOT NULL,
        [PermissionId] BIGINT NOT NULL,
        CONSTRAINT [PK_role_permissions] PRIMARY KEY CLUSTERED ([Id] ASC),
        CONSTRAINT [FK_role_permissions_roles] FOREIGN KEY ([RoleId]) 
            REFERENCES [dbo].[roles] ([Id]) ON DELETE CASCADE,
        CONSTRAINT [FK_role_permissions_permissions] FOREIGN KEY ([PermissionId]) 
            REFERENCES [dbo].[permissions] ([Id]) ON DELETE CASCADE
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [IX_role_permissions_unique] ON [dbo].[role_permissions] ([RoleId] ASC, [PermissionId] ASC);
    PRINT N'Table role_permissions created successfully';
END
GO

-- =============================================
-- 9. Create Admin User Menus Table (User-specific menus)
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[admin_user_menus]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[admin_user_menus] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [AdminUserId] BIGINT NOT NULL,
        [MenuId] BIGINT NOT NULL,
        CONSTRAINT [PK_admin_user_menus] PRIMARY KEY CLUSTERED ([Id] ASC),
        CONSTRAINT [FK_admin_user_menus_admin_users] FOREIGN KEY ([AdminUserId]) 
            REFERENCES [dbo].[admin_users] ([Id]) ON DELETE CASCADE,
        CONSTRAINT [FK_admin_user_menus_menus] FOREIGN KEY ([MenuId]) 
            REFERENCES [dbo].[menus] ([Id]) ON DELETE CASCADE
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [IX_admin_user_menus_unique] ON [dbo].[admin_user_menus] ([AdminUserId] ASC, [MenuId] ASC);
    PRINT N'Table admin_user_menus created successfully';
END
GO

-- =============================================
-- 10. Create Department Menus Table
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[department_menus]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[department_menus] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [DepartmentId] BIGINT NOT NULL,
        [MenuId] BIGINT NOT NULL,
        CONSTRAINT [PK_department_menus] PRIMARY KEY CLUSTERED ([Id] ASC),
        CONSTRAINT [FK_department_menus_departments] FOREIGN KEY ([DepartmentId]) 
            REFERENCES [dbo].[departments] ([Id]) ON DELETE CASCADE,
        CONSTRAINT [FK_department_menus_menus] FOREIGN KEY ([MenuId]) 
            REFERENCES [dbo].[menus] ([Id]) ON DELETE CASCADE
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [IX_department_menus_unique] ON [dbo].[department_menus] ([DepartmentId] ASC, [MenuId] ASC);
    PRINT N'Table department_menus created successfully';
END
GO

-- =============================================
-- 11. Create Operation Logs Table
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[operation_logs]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[operation_logs] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [AdminUserId] BIGINT NULL,
        [Username] VARCHAR(50) NULL,
        [Module] VARCHAR(50) NULL,
        [Action] VARCHAR(50) NULL,
        [Method] VARCHAR(10) NULL,
        [Url] VARCHAR(500) NULL,
        [Ip] VARCHAR(50) NULL,
        [RequestData] NVARCHAR(MAX) NULL,
        [ResponseData] NVARCHAR(MAX) NULL,
        [Status] TINYINT NOT NULL DEFAULT 1,
        [ErrorMsg] NVARCHAR(2000) NULL,
        [Duration] INT NOT NULL DEFAULT 0,
        [CreatedAt] DATETIME NOT NULL DEFAULT GETDATE(),
        CONSTRAINT [PK_operation_logs] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE NONCLUSTERED INDEX [IX_operation_logs_admin_user] ON [dbo].[operation_logs] ([AdminUserId] ASC);
    CREATE NONCLUSTERED INDEX [IX_operation_logs_created_at] ON [dbo].[operation_logs] ([CreatedAt] DESC);
    PRINT N'Table operation_logs created successfully';
END
GO

-- =============================================
-- 12. Create Refresh Tokens Table
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[refresh_tokens]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[refresh_tokens] (
        [Id] BIGINT IDENTITY(1,1) NOT NULL,
        [AdminUserId] BIGINT NOT NULL,
        [TokenHash] VARCHAR(256) NOT NULL,
        [ExpiresAt] DATETIME NOT NULL,
        [CreatedAt] DATETIME NOT NULL DEFAULT GETDATE(),
        [CreatedByIp] VARCHAR(50) NULL,
        [RevokedAt] DATETIME NULL,
        [RevokedByIp] VARCHAR(50) NULL,
        [ReplacedByToken] VARCHAR(256) NULL,
        CONSTRAINT [PK_refresh_tokens] PRIMARY KEY CLUSTERED ([Id] ASC),
        CONSTRAINT [FK_refresh_tokens_admin_users] FOREIGN KEY ([AdminUserId]) 
            REFERENCES [dbo].[admin_users] ([Id]) ON DELETE CASCADE
    );
    
    CREATE NONCLUSTERED INDEX [IX_refresh_tokens_admin_user] ON [dbo].[refresh_tokens] ([AdminUserId] ASC);
    CREATE NONCLUSTERED INDEX [IX_refresh_tokens_token_hash] ON [dbo].[refresh_tokens] ([TokenHash] ASC);
    PRINT N'Table refresh_tokens created successfully';
END
GO

-- =============================================
-- 13. Create Admin Configs Table
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[admin_configs]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[admin_configs] (
        [Id] INT IDENTITY(1,1) NOT NULL,
        [config_key] VARCHAR(100) NOT NULL,
        [config_value] NVARCHAR(MAX) NULL,
        [description] NVARCHAR(200) NULL,
        [created_at] DATETIME NOT NULL DEFAULT GETDATE(),
        [updated_at] DATETIME NULL,
        CONSTRAINT [PK_admin_configs] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [IX_admin_configs_config_key] ON [dbo].[admin_configs] ([config_key] ASC);
    PRINT N'Table admin_configs created successfully';
END
GO

-- =============================================
-- 14. Create Dict Types Table
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[dict_types]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[dict_types] (
        [Id] INT IDENTITY(1,1) NOT NULL,
        [code] VARCHAR(50) NOT NULL,
        [name] NVARCHAR(50) NOT NULL,
        [description] NVARCHAR(200) NULL,
        [source_type] TINYINT NOT NULL DEFAULT 1,
        [source_sql] NVARCHAR(MAX) NULL,
        [status] TINYINT NOT NULL DEFAULT 1,
        [sort] INT NOT NULL DEFAULT 0,
        [created_at] DATETIME NOT NULL DEFAULT GETDATE(),
        [updated_at] DATETIME NULL,
        CONSTRAINT [PK_dict_types] PRIMARY KEY CLUSTERED ([Id] ASC)
    );
    
    CREATE UNIQUE NONCLUSTERED INDEX [IX_dict_types_code] ON [dbo].[dict_types] ([code] ASC);
    CREATE NONCLUSTERED INDEX [IX_dict_types_status_sort] ON [dbo].[dict_types] ([status] ASC, [sort] ASC);
    PRINT N'Table dict_types created successfully';
END
GO

-- =============================================
-- 15. Create Dict Items Table
-- =============================================
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[dict_items]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[dict_items] (
        [Id] INT IDENTITY(1,1) NOT NULL,
        [type_id] INT NOT NULL,
        [label] NVARCHAR(100) NOT NULL,
        [value] VARCHAR(100) NOT NULL,
        [description] NVARCHAR(200) NULL,
        [css_class] VARCHAR(50) NULL,
        [status] TINYINT NOT NULL DEFAULT 1,
        [sort] INT NOT NULL DEFAULT 0,
        [created_at] DATETIME NOT NULL DEFAULT GETDATE(),
        [updated_at] DATETIME NULL,
        CONSTRAINT [PK_dict_items] PRIMARY KEY CLUSTERED ([Id] ASC),
        CONSTRAINT [FK_dict_items_dict_types] FOREIGN KEY ([type_id]) 
            REFERENCES [dbo].[dict_types] ([Id]) ON DELETE CASCADE
    );
    
    CREATE NONCLUSTERED INDEX [IX_dict_items_type_id] ON [dbo].[dict_items] ([type_id] ASC);
    CREATE NONCLUSTERED INDEX [IX_dict_items_type_status_sort] ON [dbo].[dict_items] ([type_id] ASC, [status] ASC, [sort] ASC);
    PRINT N'Table dict_items created successfully';
END
GO


-- =============================================
-- INSERT DEFAULT DATA
-- =============================================

-- =============================================
-- 16. Insert Default Department
-- =============================================
IF NOT EXISTS (SELECT 1 FROM [dbo].[departments] WHERE [Name] = N'总部')
BEGIN
    SET IDENTITY_INSERT [dbo].[departments] ON;
    INSERT INTO [dbo].[departments] ([Id], [ParentId], [Name], [Code], [Description], [SortOrder], [Status], [CreatedAt])
    VALUES (1, 0, N'总部', 'HQ', N'公司总部', 1, 1, GETDATE());
    SET IDENTITY_INSERT [dbo].[departments] OFF;
    PRINT N'Default department inserted';
END
GO

-- =============================================
-- 17. Insert Default Roles
-- =============================================
IF NOT EXISTS (SELECT 1 FROM [dbo].[roles] WHERE [Code] = 'super_admin')
BEGIN
    SET IDENTITY_INSERT [dbo].[roles] ON;
    INSERT INTO [dbo].[roles] ([Id], [Name], [Code], [Description], [SortOrder], [Status], [IsSystem], [CreatedAt])
    VALUES 
        (1, N'超级管理员', 'super_admin', N'拥有系统所有权限', 1, 1, 1, GETDATE()),
        (2, N'管理员', 'admin', N'普通管理员', 2, 1, 0, GETDATE());
    SET IDENTITY_INSERT [dbo].[roles] OFF;
    PRINT N'Default roles inserted';
END
GO

-- =============================================
-- 18. Insert Default Admin User (admin/admin123)
-- Password hash is BCrypt hash of 'admin123'
-- =============================================
IF NOT EXISTS (SELECT 1 FROM [dbo].[admin_users] WHERE [Username] = 'admin')
BEGIN
    SET IDENTITY_INSERT [dbo].[admin_users] ON;
    INSERT INTO [dbo].[admin_users] ([Id], [Username], [PasswordHash], [RealName], [DepartmentId], [Status], [CreatedAt])
    VALUES (1, 'admin', '$2a$11$K7.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5.5', N'超级管理员', 1, 1, GETDATE());
    SET IDENTITY_INSERT [dbo].[admin_users] OFF;
    PRINT N'Default admin user inserted (username: admin, password: [REDACTED]
END
GO

-- =============================================
-- 19. Assign Super Admin Role to Admin User
-- =============================================
IF NOT EXISTS (SELECT 1 FROM [dbo].[admin_user_roles] WHERE [AdminUserId] = 1 AND [RoleId] = 1)
BEGIN
    INSERT INTO [dbo].[admin_user_roles] ([AdminUserId], [RoleId])
    VALUES (1, 1);
    PRINT N'Admin user assigned to super_admin role';
END
GO

-- =============================================
-- 20. Insert Default Permissions
-- =============================================
IF NOT EXISTS (SELECT 1 FROM [dbo].[permissions] WHERE [Code] = 'system:admin:list')
BEGIN
    SET IDENTITY_INSERT [dbo].[permissions] ON;
    INSERT INTO [dbo].[permissions] ([Id], [Name], [Code], [Module], [Description], [CreatedAt])
    VALUES 
        -- System Management
        (1, N'管理员列表', 'system:admin:list', 'system', N'查看管理员列表', GETDATE()),
        (2, N'管理员新增', 'system:admin:add', 'system', N'新增管理员', GETDATE()),
        (3, N'管理员编辑', 'system:admin:edit', 'system', N'编辑管理员', GETDATE()),
        (4, N'管理员删除', 'system:admin:delete', 'system', N'删除管理员', GETDATE()),
        (5, N'角色列表', 'system:role:list', 'system', N'查看角色列表', GETDATE()),
        (6, N'角色新增', 'system:role:add', 'system', N'新增角色', GETDATE()),
        (7, N'角色编辑', 'system:role:edit', 'system', N'编辑角色', GETDATE()),
        (8, N'角色删除', 'system:role:delete', 'system', N'删除角色', GETDATE()),
        (9, N'菜单列表', 'system:menu:list', 'system', N'查看菜单列表', GETDATE()),
        (10, N'菜单新增', 'system:menu:add', 'system', N'新增菜单', GETDATE()),
        (11, N'菜单编辑', 'system:menu:edit', 'system', N'编辑菜单', GETDATE()),
        (12, N'菜单删除', 'system:menu:delete', 'system', N'删除菜单', GETDATE()),
        (13, N'部门列表', 'system:dept:list', 'system', N'查看部门列表', GETDATE()),
        (14, N'部门新增', 'system:dept:add', 'system', N'新增部门', GETDATE()),
        (15, N'部门编辑', 'system:dept:edit', 'system', N'编辑部门', GETDATE()),
        (16, N'部门删除', 'system:dept:delete', 'system', N'删除部门', GETDATE()),
        -- Dictionary Management
        (17, N'字典类型列表', 'system:dict:type:list', 'system', N'查看字典类型列表', GETDATE()),
        (18, N'字典类型新增', 'system:dict:type:add', 'system', N'新增字典类型', GETDATE()),
        (19, N'字典类型编辑', 'system:dict:type:edit', 'system', N'编辑字典类型', GETDATE()),
        (20, N'字典类型删除', 'system:dict:type:delete', 'system', N'删除字典类型', GETDATE()),
        (21, N'字典数据列表', 'system:dict:item:list', 'system', N'查看字典数据列表', GETDATE()),
        (22, N'字典数据新增', 'system:dict:item:add', 'system', N'新增字典数据', GETDATE()),
        (23, N'字典数据编辑', 'system:dict:item:edit', 'system', N'编辑字典数据', GETDATE()),
        (24, N'字典数据删除', 'system:dict:item:delete', 'system', N'删除字典数据', GETDATE()),
        -- Config Management
        (25, N'配置列表', 'system:config:list', 'system', N'查看配置列表', GETDATE()),
        (26, N'配置编辑', 'system:config:edit', 'system', N'编辑配置', GETDATE()),
        -- Upload Management
        (27, N'文件上传', 'system:upload:file', 'system', N'上传文件', GETDATE()),
        -- User Management
        (28, N'用户列表', 'user:list', 'user', N'查看用户列表', GETDATE()),
        (29, N'用户详情', 'user:detail', 'user', N'查看用户详情', GETDATE()),
        (30, N'用户编辑', 'user:edit', 'user', N'编辑用户', GETDATE()),
        (31, N'用户禁用', 'user:disable', 'user', N'禁用用户', GETDATE()),
        -- Operation Log
        (32, N'操作日志', 'system:log:list', 'system', N'查看操作日志', GETDATE());
    SET IDENTITY_INSERT [dbo].[permissions] OFF;
    PRINT N'Default permissions inserted';
END
GO

-- =============================================
-- 21. Assign All Permissions to Super Admin Role
-- =============================================
IF NOT EXISTS (SELECT 1 FROM [dbo].[role_permissions] WHERE [RoleId] = 1)
BEGIN
    INSERT INTO [dbo].[role_permissions] ([RoleId], [PermissionId])
    SELECT 1, [Id] FROM [dbo].[permissions];
    PRINT N'All permissions assigned to super_admin role';
END
GO

-- =============================================
-- 22. Insert Default Menus
-- =============================================
IF NOT EXISTS (SELECT 1 FROM [dbo].[menus] WHERE [Name] = N'系统管理')
BEGIN
    SET IDENTITY_INSERT [dbo].[menus] ON;
    INSERT INTO [dbo].[menus] ([Id], [ParentId], [Name], [Path], [Component], [Icon], [MenuType], [Permission], [SortOrder], [Status], [CreatedAt])
    VALUES 
        -- System Management (Directory)
        (1, 0, N'系统管理', '/system', 'Layout', 'setting', 1, NULL, 1, 1, GETDATE()),
        -- Admin Management
        (2, 1, N'管理员管理', '/system/admin', 'system/admin/index', 'user', 2, 'system:admin:list', 1, 1, GETDATE()),
        (3, 2, N'新增', NULL, NULL, NULL, 3, 'system:admin:add', 1, 1, GETDATE()),
        (4, 2, N'编辑', NULL, NULL, NULL, 3, 'system:admin:edit', 2, 1, GETDATE()),
        (5, 2, N'删除', NULL, NULL, NULL, 3, 'system:admin:delete', 3, 1, GETDATE()),
        -- Role Management
        (6, 1, N'角色管理', '/system/role', 'system/role/index', 'peoples', 2, 'system:role:list', 2, 1, GETDATE()),
        (7, 6, N'新增', NULL, NULL, NULL, 3, 'system:role:add', 1, 1, GETDATE()),
        (8, 6, N'编辑', NULL, NULL, NULL, 3, 'system:role:edit', 2, 1, GETDATE()),
        (9, 6, N'删除', NULL, NULL, NULL, 3, 'system:role:delete', 3, 1, GETDATE()),
        -- Menu Management
        (10, 1, N'菜单管理', '/system/menu', 'system/menu/index', 'tree-table', 2, 'system:menu:list', 3, 1, GETDATE()),
        (11, 10, N'新增', NULL, NULL, NULL, 3, 'system:menu:add', 1, 1, GETDATE()),
        (12, 10, N'编辑', NULL, NULL, NULL, 3, 'system:menu:edit', 2, 1, GETDATE()),
        (13, 10, N'删除', NULL, NULL, NULL, 3, 'system:menu:delete', 3, 1, GETDATE()),
        -- Department Management
        (14, 1, N'部门管理', '/system/dept', 'system/dept/index', 'tree', 2, 'system:dept:list', 4, 1, GETDATE()),
        (15, 14, N'新增', NULL, NULL, NULL, 3, 'system:dept:add', 1, 1, GETDATE()),
        (16, 14, N'编辑', NULL, NULL, NULL, 3, 'system:dept:edit', 2, 1, GETDATE()),
        (17, 14, N'删除', NULL, NULL, NULL, 3, 'system:dept:delete', 3, 1, GETDATE()),
        -- Dictionary Management
        (18, 1, N'字典管理', '/system/dict', 'system/dict/index', 'dict', 2, 'system:dict:type:list', 5, 1, GETDATE()),
        (19, 18, N'类型新增', NULL, NULL, NULL, 3, 'system:dict:type:add', 1, 1, GETDATE()),
        (20, 18, N'类型编辑', NULL, NULL, NULL, 3, 'system:dict:type:edit', 2, 1, GETDATE()),
        (21, 18, N'类型删除', NULL, NULL, NULL, 3, 'system:dict:type:delete', 3, 1, GETDATE()),
        (22, 18, N'数据新增', NULL, NULL, NULL, 3, 'system:dict:item:add', 4, 1, GETDATE()),
        (23, 18, N'数据编辑', NULL, NULL, NULL, 3, 'system:dict:item:edit', 5, 1, GETDATE()),
        (24, 18, N'数据删除', NULL, NULL, NULL, 3, 'system:dict:item:delete', 6, 1, GETDATE()),
        -- Config Management
        (25, 1, N'配置管理', '/system/config', 'system/config/index', 'edit', 2, 'system:config:list', 6, 1, GETDATE()),
        (26, 25, N'编辑', NULL, NULL, NULL, 3, 'system:config:edit', 1, 1, GETDATE()),
        -- Operation Log
        (27, 1, N'操作日志', '/system/log', 'system/log/index', 'log', 2, 'system:log:list', 7, 1, GETDATE()),
        -- User Management (Directory)
        (28, 0, N'用户管理', '/user', 'Layout', 'user', 1, NULL, 2, 1, GETDATE()),
        -- User List
        (29, 28, N'用户列表', '/user/list', 'user/list/index', 'peoples', 2, 'user:list', 1, 1, GETDATE()),
        (30, 29, N'详情', NULL, NULL, NULL, 3, 'user:detail', 1, 1, GETDATE()),
        (31, 29, N'编辑', NULL, NULL, NULL, 3, 'user:edit', 2, 1, GETDATE()),
        (32, 29, N'禁用', NULL, NULL, NULL, 3, 'user:disable', 3, 1, GETDATE());
    SET IDENTITY_INSERT [dbo].[menus] OFF;
    PRINT N'Default menus inserted';
END
GO

-- =============================================
-- 23. Assign All Menus to Super Admin Role
-- =============================================
IF NOT EXISTS (SELECT 1 FROM [dbo].[role_menus] WHERE [RoleId] = 1)
BEGIN
    INSERT INTO [dbo].[role_menus] ([RoleId], [MenuId])
    SELECT 1, [Id] FROM [dbo].[menus];
    PRINT N'All menus assigned to super_admin role';
END
GO

-- =============================================
-- 24. Insert Default Admin Configs
-- =============================================
IF NOT EXISTS (SELECT 1 FROM [dbo].[admin_configs] WHERE [config_key] = 'uploads')
BEGIN
    INSERT INTO [dbo].[admin_configs] ([config_key], [config_value], [description], [created_at])
    VALUES 
        ('uploads', '{"storage_type":"local","local":{"base_path":"uploads","base_url":"/uploads"},"cos":{"secret_id":"","secret_key":"","region":"","bucket":"","base_url":""}}', N'文件上传配置', GETDATE()),
        ('system', '{"site_name":"MiAssessment 管理后台","site_logo":"","copyright":"","version":"1.0.0"}', N'系统基础配置', GETDATE());
    PRINT N'Default admin configs inserted';
END
GO

-- =============================================
-- 25. Insert Default Dictionary Types
-- =============================================
IF NOT EXISTS (SELECT 1 FROM [dbo].[dict_types] WHERE [code] = 'user_status')
BEGIN
    INSERT INTO [dbo].[dict_types] ([code], [name], [description], [source_type], [status], [sort], [created_at])
    VALUES 
        ('user_status', N'用户状态', N'用户账号状态', 1, 1, 1, GETDATE()),
        ('gender', N'性别', N'用户性别', 1, 1, 2, GETDATE()),
        ('yes_no', N'是否', N'通用是否选项', 1, 1, 3, GETDATE());
    PRINT N'Default dictionary types inserted';
END
GO

-- =============================================
-- 26. Insert Default Dictionary Items
-- =============================================
DECLARE @user_status_id INT, @gender_id INT, @yes_no_id INT;

SELECT @user_status_id = [Id] FROM [dbo].[dict_types] WHERE [code] = 'user_status';
SELECT @gender_id = [Id] FROM [dbo].[dict_types] WHERE [code] = 'gender';
SELECT @yes_no_id = [Id] FROM [dbo].[dict_types] WHERE [code] = 'yes_no';

IF @user_status_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM [dbo].[dict_items] WHERE [type_id] = @user_status_id)
BEGIN
    INSERT INTO [dbo].[dict_items] ([type_id], [label], [value], [css_class], [status], [sort], [created_at])
    VALUES 
        (@user_status_id, N'正常', '1', 'success', 1, 1, GETDATE()),
        (@user_status_id, N'禁用', '0', 'danger', 1, 2, GETDATE());
    PRINT N'User status dictionary items inserted';
END

IF @gender_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM [dbo].[dict_items] WHERE [type_id] = @gender_id)
BEGIN
    INSERT INTO [dbo].[dict_items] ([type_id], [label], [value], [css_class], [status], [sort], [created_at])
    VALUES 
        (@gender_id, N'未知', '0', '', 1, 1, GETDATE()),
        (@gender_id, N'男', '1', 'primary', 1, 2, GETDATE()),
        (@gender_id, N'女', '2', 'warning', 1, 3, GETDATE());
    PRINT N'Gender dictionary items inserted';
END

IF @yes_no_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM [dbo].[dict_items] WHERE [type_id] = @yes_no_id)
BEGIN
    INSERT INTO [dbo].[dict_items] ([type_id], [label], [value], [css_class], [status], [sort], [created_at])
    VALUES 
        (@yes_no_id, N'是', '1', 'success', 1, 1, GETDATE()),
        (@yes_no_id, N'否', '0', 'info', 1, 2, GETDATE());
    PRINT N'Yes/No dictionary items inserted';
END
GO

PRINT N'=============================================';
PRINT N'Admin database initialization completed!';
PRINT N'Default admin user: admin / admin123';
PRINT N'=============================================';
GO
