using HoneyBox.Admin.Data;
using HoneyBox.Admin.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace HoneyBox.Admin.Services;

/// <summary>
/// 数据初始化服务实现
/// </summary>
public class DataSeeder : IDataSeeder
{
    private readonly AdminDbContext _dbContext;
    private readonly ILogger<DataSeeder> _logger;

    public DataSeeder(AdminDbContext dbContext, ILogger<DataSeeder> logger)
    {
        _dbContext = dbContext;
        _logger = logger;
    }

    /// <inheritdoc />
    public async Task SeedAsync()
    {
        _logger.LogInformation("开始数据初始化...");

        await SeedDepartmentsAsync();
        await SeedPermissionsAsync();
        await SeedRolesAsync();
        await SeedMenusAsync();
        await SeedAdminUserAsync();

        _logger.LogInformation("数据初始化完成");
    }

    /// <summary>
    /// 初始化部门
    /// </summary>
    private async Task SeedDepartmentsAsync()
    {
        if (await _dbContext.Departments.AnyAsync())
        {
            _logger.LogDebug("部门数据已存在，跳过初始化");
            return;
        }

        var rootDepartment = new Department
        {
            ParentId = 0,
            Name = "总公司",
            Code = "root",
            Description = "根部门",
            SortOrder = 0,
            Status = 1,
            CreatedAt = DateTime.Now
        };

        _dbContext.Departments.Add(rootDepartment);
        await _dbContext.SaveChangesAsync();
        _logger.LogInformation("初始化根部门完成");
    }

    /// <summary>
    /// 初始化权限
    /// </summary>
    private async Task SeedPermissionsAsync()
    {
        if (await _dbContext.Permissions.AnyAsync())
        {
            _logger.LogDebug("权限数据已存在，跳过初始化");
            return;
        }

        var permissions = new List<Permission>
        {
            // 菜单管理
            new() { Name = "菜单列表", Code = "menu:list", Module = "菜单管理", CreatedAt = DateTime.Now },
            new() { Name = "菜单详情", Code = "menu:detail", Module = "菜单管理", CreatedAt = DateTime.Now },
            new() { Name = "创建菜单", Code = "menu:create", Module = "菜单管理", CreatedAt = DateTime.Now },
            new() { Name = "更新菜单", Code = "menu:update", Module = "菜单管理", CreatedAt = DateTime.Now },
            new() { Name = "删除菜单", Code = "menu:delete", Module = "菜单管理", CreatedAt = DateTime.Now },

            // 角色管理
            new() { Name = "角色列表", Code = "role:list", Module = "角色管理", CreatedAt = DateTime.Now },
            new() { Name = "角色详情", Code = "role:detail", Module = "角色管理", CreatedAt = DateTime.Now },
            new() { Name = "创建角色", Code = "role:create", Module = "角色管理", CreatedAt = DateTime.Now },
            new() { Name = "更新角色", Code = "role:update", Module = "角色管理", CreatedAt = DateTime.Now },
            new() { Name = "删除角色", Code = "role:delete", Module = "角色管理", CreatedAt = DateTime.Now },
            new() { Name = "分配菜单", Code = "role:assign_menu", Module = "角色管理", CreatedAt = DateTime.Now },
            new() { Name = "分配权限", Code = "role:assign_permission", Module = "角色管理", CreatedAt = DateTime.Now },

            // 权限管理
            new() { Name = "权限列表", Code = "permission:list", Module = "权限管理", CreatedAt = DateTime.Now },
            new() { Name = "权限详情", Code = "permission:detail", Module = "权限管理", CreatedAt = DateTime.Now },
            new() { Name = "创建权限", Code = "permission:create", Module = "权限管理", CreatedAt = DateTime.Now },
            new() { Name = "更新权限", Code = "permission:update", Module = "权限管理", CreatedAt = DateTime.Now },
            new() { Name = "删除权限", Code = "permission:delete", Module = "权限管理", CreatedAt = DateTime.Now },

            // 管理员管理
            new() { Name = "管理员列表", Code = "user:list", Module = "管理员管理", CreatedAt = DateTime.Now },
            new() { Name = "管理员详情", Code = "user:detail", Module = "管理员管理", CreatedAt = DateTime.Now },
            new() { Name = "创建管理员", Code = "user:create", Module = "管理员管理", CreatedAt = DateTime.Now },
            new() { Name = "更新管理员", Code = "user:update", Module = "管理员管理", CreatedAt = DateTime.Now },
            new() { Name = "删除管理员", Code = "user:delete", Module = "管理员管理", CreatedAt = DateTime.Now },
            new() { Name = "分配角色", Code = "user:assign_role", Module = "管理员管理", CreatedAt = DateTime.Now },
            new() { Name = "分配部门", Code = "user:assign_department", Module = "管理员管理", CreatedAt = DateTime.Now },
            new() { Name = "分配专属菜单", Code = "user:assign_menu", Module = "管理员管理", CreatedAt = DateTime.Now },
            new() { Name = "重置密码", Code = "user:reset_password", Module = "管理员管理", CreatedAt = DateTime.Now },

            // 部门管理
            new() { Name = "部门列表", Code = "department:list", Module = "部门管理", CreatedAt = DateTime.Now },
            new() { Name = "部门详情", Code = "department:detail", Module = "部门管理", CreatedAt = DateTime.Now },
            new() { Name = "创建部门", Code = "department:create", Module = "部门管理", CreatedAt = DateTime.Now },
            new() { Name = "更新部门", Code = "department:update", Module = "部门管理", CreatedAt = DateTime.Now },
            new() { Name = "删除部门", Code = "department:delete", Module = "部门管理", CreatedAt = DateTime.Now },
            new() { Name = "分配菜单", Code = "department:assign_menu", Module = "部门管理", CreatedAt = DateTime.Now },

            // 操作日志
            new() { Name = "日志列表", Code = "log:list", Module = "操作日志", CreatedAt = DateTime.Now },
            new() { Name = "日志详情", Code = "log:detail", Module = "操作日志", CreatedAt = DateTime.Now },

            // ========== 业务模块权限 ==========

            // 系统配置
            new() { Name = "查看配置", Code = "config:view", Module = "系统配置", CreatedAt = DateTime.Now },
            new() { Name = "编辑配置", Code = "config:edit", Module = "系统配置", CreatedAt = DateTime.Now },

            // 用户管理（业务）
            new() { Name = "用户列表", Code = "user:list", Module = "用户管理", CreatedAt = DateTime.Now },
            new() { Name = "用户详情", Code = "user:view", Module = "用户管理", CreatedAt = DateTime.Now },
            new() { Name = "资金变动", Code = "user:money", Module = "用户管理", CreatedAt = DateTime.Now },
            new() { Name = "状态管理", Code = "user:status", Module = "用户管理", CreatedAt = DateTime.Now },
            new() { Name = "测试账号", Code = "user:test", Module = "用户管理", CreatedAt = DateTime.Now },
            new() { Name = "清空绑定", Code = "user:clear", Module = "用户管理", CreatedAt = DateTime.Now },
            new() { Name = "赠送礼品", Code = "user:gift", Module = "用户管理", CreatedAt = DateTime.Now },

            // VIP管理
            new() { Name = "VIP列表", Code = "vip:list", Module = "VIP管理", CreatedAt = DateTime.Now },
            new() { Name = "VIP编辑", Code = "vip:edit", Module = "VIP管理", CreatedAt = DateTime.Now },

            // 商品管理
            new() { Name = "商品列表", Code = "goods:list", Module = "商品管理", CreatedAt = DateTime.Now },
            new() { Name = "商品详情", Code = "goods:view", Module = "商品管理", CreatedAt = DateTime.Now },
            new() { Name = "添加商品", Code = "goods:add", Module = "商品管理", CreatedAt = DateTime.Now },
            new() { Name = "编辑商品", Code = "goods:edit", Module = "商品管理", CreatedAt = DateTime.Now },
            new() { Name = "删除商品", Code = "goods:delete", Module = "商品管理", CreatedAt = DateTime.Now },
            new() { Name = "商品状态", Code = "goods:status", Module = "商品管理", CreatedAt = DateTime.Now },

            // 订单管理
            new() { Name = "订单列表", Code = "order:list", Module = "订单管理", CreatedAt = DateTime.Now },
            new() { Name = "订单详情", Code = "order:view", Module = "订单管理", CreatedAt = DateTime.Now },
            new() { Name = "发货管理", Code = "order:ship", Module = "订单管理", CreatedAt = DateTime.Now },
            new() { Name = "订单导出", Code = "order:export", Module = "订单管理", CreatedAt = DateTime.Now },

            // 财务管理
            new() { Name = "财务查看", Code = "finance:view", Module = "财务管理", CreatedAt = DateTime.Now },

            // 仪表盘
            new() { Name = "仪表盘查看", Code = "dashboard:view", Module = "仪表盘", CreatedAt = DateTime.Now },
            new() { Name = "仪表盘编辑", Code = "dashboard:edit", Module = "仪表盘", CreatedAt = DateTime.Now },
        };

        _dbContext.Permissions.AddRange(permissions);
        await _dbContext.SaveChangesAsync();
        _logger.LogInformation("初始化权限完成，共 {Count} 条", permissions.Count);
    }


    /// <summary>
    /// 初始化角色
    /// </summary>
    private async Task SeedRolesAsync()
    {
        if (await _dbContext.Roles.AnyAsync())
        {
            _logger.LogDebug("角色数据已存在，跳过初始化");
            return;
        }

        // 创建超级管理员角色
        var superAdminRole = new Role
        {
            Name = "超级管理员",
            Code = "super_admin",
            Description = "拥有系统所有权限",
            SortOrder = 0,
            Status = 1,
            IsSystem = true,
            CreatedAt = DateTime.Now
        };

        _dbContext.Roles.Add(superAdminRole);
        await _dbContext.SaveChangesAsync();

        // 为超级管理员分配所有权限
        var allPermissions = await _dbContext.Permissions.ToListAsync();
        var rolePermissions = allPermissions.Select(p => new RolePermission
        {
            RoleId = superAdminRole.Id,
            PermissionId = p.Id
        });

        _dbContext.RolePermissions.AddRange(rolePermissions);
        await _dbContext.SaveChangesAsync();

        _logger.LogInformation("初始化超级管理员角色完成");
    }

    /// <summary>
    /// 初始化菜单
    /// </summary>
    private async Task SeedMenusAsync()
    {
        if (await _dbContext.Menus.AnyAsync())
        {
            _logger.LogDebug("菜单数据已存在，跳过初始化");
            return;
        }

        // 首页
        var dashboardMenu = new Menu
        {
            ParentId = 0,
            Name = "首页",
            Path = "/",
            Component = "dashboard/index",
            Icon = "HomeFilled",
            MenuType = 2, // 菜单
            SortOrder = 0,
            Status = 1,
            CreatedAt = DateTime.Now
        };
        _dbContext.Menus.Add(dashboardMenu);
        await _dbContext.SaveChangesAsync();

        // 系统管理目录
        var systemMenu = new Menu
        {
            ParentId = 0,
            Name = "系统管理",
            Path = "/system",
            Component = "Layout",
            Icon = "Setting",
            MenuType = 1, // 目录
            SortOrder = 100,
            Status = 1,
            CreatedAt = DateTime.Now
        };
        _dbContext.Menus.Add(systemMenu);
        await _dbContext.SaveChangesAsync();

        // 子菜单
        var subMenus = new List<Menu>
        {
            new()
            {
                ParentId = systemMenu.Id,
                Name = "菜单管理",
                Path = "/system/menu",
                Component = "system/menu/index",
                Icon = "Menu",
                MenuType = 2, // 菜单
                Permission = "menu:list",
                SortOrder = 1,
                Status = 1,
                CreatedAt = DateTime.Now
            },
            new()
            {
                ParentId = systemMenu.Id,
                Name = "角色管理",
                Path = "/system/role",
                Component = "system/role/index",
                Icon = "UserFilled",
                MenuType = 2,
                Permission = "role:list",
                SortOrder = 2,
                Status = 1,
                CreatedAt = DateTime.Now
            },
            new()
            {
                ParentId = systemMenu.Id,
                Name = "权限管理",
                Path = "/system/permission",
                Component = "system/permission/index",
                Icon = "Key",
                MenuType = 2,
                Permission = "permission:list",
                SortOrder = 3,
                Status = 1,
                CreatedAt = DateTime.Now
            },
            new()
            {
                ParentId = systemMenu.Id,
                Name = "部门管理",
                Path = "/system/department",
                Component = "system/department/index",
                Icon = "OfficeBuilding",
                MenuType = 2,
                Permission = "department:list",
                SortOrder = 4,
                Status = 1,
                CreatedAt = DateTime.Now
            },
            new()
            {
                ParentId = systemMenu.Id,
                Name = "管理员管理",
                Path = "/system/user",
                Component = "system/user/index",
                Icon = "User",
                MenuType = 2,
                Permission = "user:list",
                SortOrder = 5,
                Status = 1,
                CreatedAt = DateTime.Now
            },
            new()
            {
                ParentId = systemMenu.Id,
                Name = "操作日志",
                Path = "/system/log",
                Component = "system/log/index",
                Icon = "Document",
                MenuType = 2,
                Permission = "log:list",
                SortOrder = 6,
                Status = 1,
                CreatedAt = DateTime.Now
            }
        };

        _dbContext.Menus.AddRange(subMenus);
        await _dbContext.SaveChangesAsync();

        // 为超级管理员角色分配所有菜单
        var superAdminRole = await _dbContext.Roles.FirstOrDefaultAsync(r => r.Code == "super_admin");
        if (superAdminRole != null)
        {
            var allMenus = await _dbContext.Menus.ToListAsync();
            var roleMenus = allMenus.Select(m => new RoleMenu
            {
                RoleId = superAdminRole.Id,
                MenuId = m.Id
            });

            _dbContext.RoleMenus.AddRange(roleMenus);
            await _dbContext.SaveChangesAsync();
        }

        _logger.LogInformation("初始化系统菜单完成");
    }

    /// <summary>
    /// 初始化管理员
    /// </summary>
    private async Task SeedAdminUserAsync()
    {
        if (await _dbContext.AdminUsers.AnyAsync())
        {
            _logger.LogDebug("管理员数据已存在，跳过初始化");
            return;
        }

        // 获取根部门
        var rootDepartment = await _dbContext.Departments.FirstOrDefaultAsync(d => d.Code == "root");

        // 创建超级管理员账号
        var adminUser = new AdminUser
        {
            Username = "admin",
            PasswordHash = AuthService.HashPassword("admin123"),
            RealName = "超级管理员",
            DepartmentId = rootDepartment?.Id,
            Status = 1,
            CreatedAt = DateTime.Now
        };

        _dbContext.AdminUsers.Add(adminUser);
        await _dbContext.SaveChangesAsync();

        // 分配超级管理员角色
        var superAdminRole = await _dbContext.Roles.FirstOrDefaultAsync(r => r.Code == "super_admin");
        if (superAdminRole != null)
        {
            _dbContext.AdminUserRoles.Add(new AdminUserRole
            {
                AdminUserId = adminUser.Id,
                RoleId = superAdminRole.Id
            });
            await _dbContext.SaveChangesAsync();
        }

        _logger.LogInformation("初始化超级管理员账号完成: admin / admin123");
    }
}
