using System;
using System.Windows.Forms;
using 全自动水压检测仪.DATA;

namespace 全自动水压检测仪
{
    public partial class LoginForm : Form
    {
        private UserRepository _userRepository;
        private int _selectedUserType = 0; // 0=普通用户, 1=管理员

        public LoginForm()
        {
            InitializeComponent();
            _userRepository = new UserRepository();
        }

        /// <summary>
        /// 用户类型切换事件
        /// </summary>
        private void rbUserType_CheckedChanged(object sender, EventArgs e)
        {
            if (rbAdmin.Checked)
            {
                _selectedUserType = 1; // 管理员
            }
            else if (rbNormalUser.Checked)
            {
                _selectedUserType = 0; // 普通用户
            }
            
            // 切换用户类型时自动清空用户名和密码
            txtUsername.Clear();
            txtPassword.Clear();
            txtUsername.Focus();
        }

        /// <summary>
        /// 登录按钮点击事件
        /// </summary>
        private void btnLogin_Click(object sender, EventArgs e)
        {
            string username = txtUsername.Text.Trim();
            string password = txtPassword.Text;

            // 输入验证
            if (string.IsNullOrEmpty(username))
            {
                MessageBox.Show("请输入用户名！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtUsername.Focus();
                return;
            }

            if (string.IsNullOrEmpty(password))
            {
                MessageBox.Show("请输入密码！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPassword.Focus();
                return;
            }

            try
            {
                // 查询用户
                User user = _userRepository.GetUserByUsername(username);

                if (user == null)
                {
                    MessageBox.Show("用户名或密码错误！", "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtPassword.Clear();
                    txtPassword.Focus();
                    return;
                }

                // 获取数据库中存储的密码
                string storedPassword = user.PasswordHash ?? "";
                
                // 详细调试输出
                System.Diagnostics.Debug.WriteLine($"\n========== 登录验证详细信息 ==========");
                System.Diagnostics.Debug.WriteLine($"用户名: {username}");
                System.Diagnostics.Debug.WriteLine($"输入密码: '{password}'");
                System.Diagnostics.Debug.WriteLine($"输入密码长度: {password.Length}");
                System.Diagnostics.Debug.WriteLine($"数据库密码: '{storedPassword}'");
                System.Diagnostics.Debug.WriteLine($"数据库密码长度: {storedPassword.Length}");
                System.Diagnostics.Debug.WriteLine($"盐值: '{user.Salt ?? "(null)"}'");
                
                // 检查是否是旧的加密格式（Base64 编码的哈希值）
                bool isOldFormat = storedPassword.Length > 20 && (storedPassword.Contains("+") || storedPassword.Contains("/") || storedPassword.Contains("="));
                System.Diagnostics.Debug.WriteLine($"是否旧格式: {isOldFormat}");
                
                bool passwordValid = false;
                
                if (isOldFormat)
                {
                    // 旧格式：需要重置
                    System.Diagnostics.Debug.WriteLine($"检测到旧的加密格式，需要重置密码");
                    MessageBox.Show("检测到旧的密码格式！\n\n请重启程序，系统会自动修复密码。\n\n或者手动运行 SQL 脚本：\n查询并修复密码.sql",
                        "需要重置密码", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtPassword.Clear();
                    txtPassword.Focus();
                    return;
                }
                else
                {
                    // 新格式：明文比较
                    passwordValid = (password == storedPassword);
                    System.Diagnostics.Debug.WriteLine($"明文比较结果: {passwordValid}");
                    
                    // 逐字符比较（用于调试）
                    if (!passwordValid && password.Length == storedPassword.Length)
                    {
                        System.Diagnostics.Debug.WriteLine($"逐字符比较:");
                        for (int i = 0; i < password.Length; i++)
                        {
                            char c1 = password[i];
                            char c2 = storedPassword[i];
                            System.Diagnostics.Debug.WriteLine($"  位置 {i}: 输入='{c1}'({(int)c1}) 数据库='{c2}'({(int)c2}) 相同={c1 == c2}");
                        }
                    }
                }
                
                System.Diagnostics.Debug.WriteLine($"最终验证结果: {passwordValid}");
                System.Diagnostics.Debug.WriteLine($"======================================\n");
                
                if (!passwordValid)
                {
                    MessageBox.Show("用户名或密码错误！", "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtPassword.Clear();
                    txtPassword.Focus();
                    return;
                }

                // 验证用户类型是否匹配
                if (user.UserRole != _selectedUserType)
                {
                    string expectedType = _selectedUserType == 1 ? "管理员" : "普通用户";
                    string actualType = user.UserRole == 1 ? "管理员" : "普通用户";
                    MessageBox.Show($"用户类型不匹配！\n\n该账户是【{actualType}】\n请选择正确的用户类型后重新登录。", 
                        "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 登录成功
                _userRepository.UpdateLastLoginTime(username);

                // 保存登录信息到LoginData
                LoginData.UserName = username;
                LoginData.UserPower = user.UserRole;
                LoginData.CurrentUserId = user.Id;
                LoginData.LoginTime = DateTime.Now;

                // 关闭登录窗体，返回 DialogResult.OK
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"登录失败：{ex.Message}\n\n请检查数据库连接是否正常。", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 退出按钮点击事件
        /// </summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        /// 回车键快速登录
        /// </summary>
        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnLogin_Click(sender, e);
            }
        }

        private void panelMain_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
