using BDU.Models;
using BDU.Windows;
using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Path = System.IO.Path;

namespace BDU.Windows
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class Login : MetroWindow
    {
        public List<UserModel> UserList { get; set; } = new List<UserModel>();

        private readonly string filePath = Path.Combine(SystemConfig.Instance.SystemPath, "Users.json");

        public Login()
        {
            InitializeComponent();
            FindUsersByJson();
        }

        //查询用户列表
        public void FindUsersByJson()
        {
            if (File.Exists(filePath))
            {
                string listStr = File.ReadAllText(filePath);
                //反序列化
                UserList = JsonSerializer.Deserialize<List<UserModel>>(listStr)!;
            }
            else
            {
                UserList = [];
                UserList.Add(new()
                {
                    UserName = "超级管理员",
                    UserAccount ="admin",
                    UserId = Guid.NewGuid(),
                    PassWord = "admin",
                    Role = 2
                });
                string listStr = JsonSerializer.Serialize(UserList, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(filePath, listStr);
            }
        }

        private void LoginClick(object sender, RoutedEventArgs e)
        {
            if (!Regex.IsMatch(nameBox.Text, @"^[^\s\u4e00-\u9fa5]+$") || !Regex.IsMatch(pwdBox.Password, @"^[^\s\u4e00-\u9fa5]+$"))
            {
                MessageBox.Show("请输入正确格式的账号或密码");
                return;
            }
            UserModel? userInfo = UserList.Where(item => item.UserAccount == nameBox.Text && item.PassWord == pwdBox.Password).FirstOrDefault();
            if (userInfo != null)
            {
                userInfo.LoginCount += 1;
                userInfo.LoginTime = DateTime.Now;

                //保存文件
                string listStr = JsonSerializer.Serialize(UserList, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(filePath, listStr);

                new MainWindow(userInfo).Show();
                this.Close();
            }
            else
            {
                MessageBox.Show("用户名或密码错误");
            }
        }

        private void Login_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                LoginClick(sender, e);
            }
        }
    }
}
