using Dapper;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace 全自动水压检测仪.DATA
{
    /// <summary>
    /// 用户数据访问层
    /// </summary>
    public class UserRepository
    {
        private readonly string _connectionString;

        public UserRepository()
        {
            _connectionString = "Server=localhost;Database=fullautowaterpressure;User=root;Password=123456;port=3306;charset=utf8;";
        }

        /// <summary>
        /// 根据用户名查询用户
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>用户对象，不存在返回null</returns>
        public User GetUserByUsername(string username)
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                connection.Open();
                
                // 明确指定字段映射，避免命名差异问题
                string sql = @"SELECT 
                                id AS Id,
                                username AS Username,
                                password_hash AS PasswordHash,
                                salt AS Salt,
                                user_role AS UserRole,
                                status AS Status,
                                create_time AS CreateTime,
                                update_time AS UpdateTime,
                                last_login_time AS LastLoginTime
                             FROM sys_users
                             WHERE username = @username AND status = 1";
                
                var user = connection.QueryFirstOrDefault<User>(sql, new { username });
                
                // 调试输出
                if (user != null)
                {
                    System.Diagnostics.Debug.WriteLine($"\n[GetUserByUsername] 查询结果:");
                    System.Diagnostics.Debug.WriteLine($"  用户名: {user.Username}");
                    System.Diagnostics.Debug.WriteLine($"  PasswordHash: '{user.PasswordHash ?? "(null)"}'");
                    System.Diagnostics.Debug.WriteLine($"  PasswordHash 长度: {user.PasswordHash?.Length ?? 0}");
                    System.Diagnostics.Debug.WriteLine($"  Salt: '{user.Salt ?? "(null)"}'");
                    System.Diagnostics.Debug.WriteLine($"  UserRole: {user.UserRole}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"\n[GetUserByUsername] 未找到用户: {username}");
                }
                
                return user;
            }
        }

        /// <summary>
        /// 根据ID查询用户
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户对象，不存在返回null</returns>
        public User GetUserById(int userId)
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                connection.Open();
                
                // 明确指定字段映射
                string sql = @"SELECT 
                                id AS Id,
                                username AS Username,
                                password_hash AS PasswordHash,
                                salt AS Salt,
                                user_role AS UserRole,
                                status AS Status,
                                create_time AS CreateTime,
                                update_time AS UpdateTime,
                                last_login_time AS LastLoginTime
                             FROM sys_users 
                             WHERE id = @id";
                
                return connection.QueryFirstOrDefault<User>(sql, new { id = userId });
            }
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <param name="plainPassword">明文密码</param>
        /// <returns>是否创建成功</returns>
        public bool CreateUser(User user, string plainPassword)
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                connection.Open();
                
                // 简单明文密码存储
                string passwordHash = plainPassword;  // 直接使用明文
                string salt = "";  // 空字符串

                string sql = @"INSERT INTO sys_users
                             (username, password_hash, salt, user_role, status, create_time)
                             VALUES
                             (@username, @passwordHash, @salt, @userRole, 1, CURRENT_TIMESTAMP)";

                int result = connection.Execute(sql, new
                {
                    username = user.Username,
                    passwordHash = passwordHash,
                    salt = salt,
                    userRole = user.UserRole
                });

                return result > 0;
            }
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns>是否更新成功</returns>
        public bool UpdateUser(User user)
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                connection.Open();
                string sql = @"UPDATE sys_users
                             SET username = @username, user_role = @userRole, status = @status
                             WHERE id = @id";

                int result = connection.Execute(sql, new
                {
                    username = user.Username,
                    userRole = user.UserRole,
                    status = user.Status,
                    id = user.Id
                });

                return result > 0;
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>是否删除成功</returns>
        public bool DeleteUser(int userId)
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                connection.Open();
                string sql = @"DELETE FROM sys_users WHERE id = @id";
                int result = connection.Execute(sql, new { id = userId });
                return result > 0;
            }
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns>用户列表</returns>
        public List<User> GetAllUsers()
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                connection.Open();
                
                // 明确指定字段映射
                string sql = @"SELECT 
                                id AS Id,
                                username AS Username,
                                password_hash AS PasswordHash,
                                salt AS Salt,
                                user_role AS UserRole,
                                status AS Status,
                                create_time AS CreateTime,
                                update_time AS UpdateTime,
                                last_login_time AS LastLoginTime
                             FROM sys_users 
                             ORDER BY create_time DESC";
                
                return connection.Query<User>(sql).ToList();
            }
        }

        /// <summary>
        /// 用户修改密码
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="oldPassword">旧密码</param>
        /// <param name="newPassword">新密码</param>
        /// <returns>是否修改成功</returns>
        public bool ChangePassword(int userId, string oldPassword, string newPassword)
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                connection.Open();

                // 先验证旧密码
                User user = GetUserById(userId);
                if (user == null)
                    return false;

                // 简单明文密码比较
                if (user.PasswordHash != oldPassword)
                    return false;

                // 更新新密码（明文）
                string newPasswordHash = newPassword;
                string newSalt = "";

                string sql = @"UPDATE sys_users
                             SET password_hash = @passwordHash, salt = @salt, update_time = CURRENT_TIMESTAMP
                             WHERE id = @id";

                int result = connection.Execute(sql, new
                {
                    passwordHash = newPasswordHash,
                    salt = newSalt,
                    id = userId
                });

                return result > 0;
            }
        }

        /// <summary>
        /// 管理员重置用户密码
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="newPassword">新密码</param>
        /// <returns>是否重置成功</returns>
        public bool ResetPassword(int userId, string newPassword)
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                connection.Open();

                // 简单明文密码存储
                string newPasswordHash = newPassword;
                string newSalt = "";

                string sql = @"UPDATE sys_users
                             SET password_hash = @passwordHash, salt = @salt, update_time = CURRENT_TIMESTAMP
                             WHERE id = @id";

                int result = connection.Execute(sql, new
                {
                    passwordHash = newPasswordHash,
                    salt = newSalt,
                    id = userId
                });

                return result > 0;
            }
        }

        /// <summary>
        /// 更新最后登录时间
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>是否更新成功</returns>
        public bool UpdateLastLoginTime(string username)
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                connection.Open();
                string sql = @"UPDATE sys_users
                             SET last_login_time = CURRENT_TIMESTAMP
                             WHERE username = @username";
                int result = connection.Execute(sql, new { username });
                return result > 0;
            }
        }
    }
}
