using Dapper;
using MySql.Data.MySqlClient;
using System;
using System.Diagnostics;

namespace 全自动水压检测仪.DATA
{
    /// <summary>
    /// 数据库初始化辅助类
    /// 用于创建用户表和初始化默认管理员账户
    /// </summary>
    public static class DatabaseInitializer
    {
        private static readonly string _connectionString = "Server=localhost;Database=fullautowaterpressure;User=root;Password=123456;port=3306;charset=utf8;";

        /// <summary>
        /// 初始化用户表和默认管理员账户
        /// </summary>
        public static void Initialize()
        {
            try
            {
                CreateUsersTable();
                CreateDefaultAdminIfNotExists();
            }
            catch (Exception ex)
            {
                throw new Exception($"数据库初始化失败：{ex.Message}", ex);
            }
        }

        /// <summary>
        /// 强制重置默认用户（删除并重新创建）
        /// </summary>
        public static void ForceResetDefaultUsers()
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                connection.Open();

                try
                {
                    // 删除现有的默认用户
                    connection.Execute("DELETE FROM sys_users WHERE username IN ('admin', 'csi')");
                    Debug.WriteLine("已删除现有默认用户");

                    // 重新创建
                    CreateUserIfNotExists(connection, "admin", "admin123", 1);
                    CreateUserIfNotExists(connection, "csi", "123456", 0);

                    Debug.WriteLine("默认用户重置完成！");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"重置用户失败: {ex.Message}");
                    throw;
                }
            }
        }

        /// <summary>
        /// 创建用户表
        /// </summary>
        private static void CreateUsersTable()
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                connection.Open();

                // 先检查表是否存在，如果不存在则创建
                string checkTableSql = @"SELECT COUNT(*) FROM information_schema.tables
                                      WHERE table_schema = @database AND table_name = 'sys_users'";
                int tableExists = connection.ExecuteScalar<int>(checkTableSql, new { database = "fullautowaterpressure" });

                if (tableExists == 0)
                {
                    string sql = @"
                        CREATE TABLE `sys_users` (
                          `id` INT NOT NULL AUTO_INCREMENT COMMENT '用户ID',
                          `username` VARCHAR(50) NOT NULL COMMENT '用户名',
                          `password_hash` VARCHAR(255) NOT NULL COMMENT '密码哈希值',
                          `salt` VARCHAR(64) NOT NULL COMMENT '盐值',
                          `user_role` TINYINT NOT NULL DEFAULT 0 COMMENT '用户角色：0=普通用户，1=管理员',
                          `status` TINYINT NOT NULL DEFAULT 1 COMMENT '状态：0=禁用，1=启用',
                          `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                          `update_time` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
                          `last_login_time` DATETIME DEFAULT NULL COMMENT '最后登录时间',
                          PRIMARY KEY (`id`),
                          UNIQUE KEY `uk_username` (`username`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统用户表'";

                    connection.Execute(sql);
                }
            }
        }

        /// <summary>
        /// 创建默认管理员账户（如果不存在）
        /// 默认账户：admin / admin123
        /// </summary>
        private static void CreateDefaultAdminIfNotExists()
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                connection.Open();

                try
                {
                    // 先检查 sys_users 表是否存在
                    string checkTableSql = @"SELECT COUNT(*) FROM information_schema.tables
                                           WHERE table_schema = @database AND table_name = 'sys_users'";
                    int tableExists = connection.ExecuteScalar<int>(checkTableSql, new { database = "fullautowaterpressure" });

                    if (tableExists == 0)
                    {
                        Debug.WriteLine("sys_users table does not exist, skipping admin creation");
                        return;
                    }

                    // 创建默认管理员账户 admin / admin123
                    CreateUserIfNotExists(connection, "admin", "admin123", 1);

                    // 创建默认普通用户账户 csi / 123456
                    CreateUserIfNotExists(connection, "csi", "123456", 0);
                }
                catch (Exception ex)
                {
                    // 捕获其他异常
                    Debug.WriteLine($"✗ Error creating default users: {ex.GetType().Name} - {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 创建用户（如果不存在）
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="username">用户名</param>
        /// <param name="password">密码（明文）</param>
        /// <param name="userRole">用户角色：0=普通用户，1=管理员</param>
        private static void CreateUserIfNotExists(MySqlConnection connection, string username, string password, int userRole)
        {
            try
            {
                // 检查用户是否已存在
                string checkUserSql = "SELECT COUNT(*) FROM `sys_users` WHERE `username` = @username";
                int userExists = connection.ExecuteScalar<int>(checkUserSql, new { username });

                if (userExists > 0)
                {
                    Debug.WriteLine($"用户 '{username}' 已存在，跳过创建");
                    return;
                }

                // 简单明文密码存储
                // password_hash 字段存储明文密码
                // salt 字段存储空字符串（保持兼容性）
                string passwordHash = password;  // 直接使用明文
                string salt = "";  // 空字符串

                // 调试输出
                Debug.WriteLine($"\n=== 创建用户: {username} ===");
                Debug.WriteLine($"  密码: {password}");
                Debug.WriteLine($"  角色: {(userRole == 1 ? "管理员" : "普通用户")}");

                // 插入用户
                string insertSql = @"
                    INSERT INTO `sys_users`
                    (`username`, `password_hash`, `salt`, `user_role`, `status`, `create_time`)
                    VALUES (@username, @passwordHash, @salt, @userRole, @status, NOW())";

                int rowsAffected = connection.Execute(insertSql, new
                {
                    username = username,
                    passwordHash = passwordHash,
                    salt = salt,
                    userRole = userRole,
                    status = 1  // 启用
                });

                if (rowsAffected > 0)
                {
                    string roleText = userRole == 1 ? "管理员" : "普通用户";
                    Debug.WriteLine($"✓ 用户创建成功: {username} / {password} ({roleText})");
                }
                else
                {
                    Debug.WriteLine($"✗ 创建用户失败: {username}");
                }
            }
            catch (MySqlException ex)
            {
                Debug.WriteLine($"✗ MySQL错误 (创建用户 '{username}'): [{ex.Number}] {ex.Message}");
                
                if (ex.Number == 1062)
                {
                    Debug.WriteLine($"用户 '{username}' 已存在（重复键）");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"✗ 异常 (创建用户 '{username}'): {ex.Message}");
            }
        }
    }
}
