using BDU.Models;
using DocumentFormat.OpenXml.Spreadsheet;
using MahApps.Metro.Controls;
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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.Navigation;
using System.Windows.Shapes;
using Path = System.IO.Path;

namespace BDU.Windows
{
    /// <summary>
    /// UsersManage.xaml 的交互逻辑
    /// </summary>
    [AddINotifyPropertyChangedInterface]
    public partial class UsersManage : MetroWindow
    {
        public ObservableCollection<UserModel> UserList { get; set; }

        public UserModel SelectedUser { get; set; } = new();

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

        public UsersManage()
        {
            InitializeComponent();
            this.DataContext = this;
            LoadUserJson();
        }

        protected override void OnClosed(EventArgs e)
        {
            string listStr = JsonSerializer.Serialize(UserList, new JsonSerializerOptions { WriteIndented = true });
            File.WriteAllText(filePath, listStr);
            base.OnClosed(e);
        }

        private void AddUserClick(object sender, RoutedEventArgs e)
        {
            UserSettingWindow tmp = new();
            tmp.ShowDialog();
            var userFind = UserList.FirstOrDefault(x => x.UserAccount == tmp.UserInfo.UserAccount);
            if (userFind != null && userFind.UserId != tmp.UserInfo.UserId)
            {
                MessageBox.Show("用户添加失败：账号已存在");
                return;
            }
            if (tmp.IsSave)
            {
                UserList.Add(tmp.UserInfo);
            }
        }

        //反序列化用户列表
        public void LoadUserJson()
        {
            if (File.Exists(filePath))
            {
                // 反序列化用户列表
                string json = File.ReadAllText(filePath, Encoding.UTF8);
                // 移除 /* 多行注释 */
                json = Regex.Replace(json, @"/\*.*?\*/", "", RegexOptions.Singleline);
                var list = JsonSerializer.Deserialize<List<UserModel>>(json);
                UserList = new ObservableCollection<UserModel>(list!);
            }
            else
            {
                UserList = [];
                UserList.Add(new()
                {
                    UserName = "超级管理员",
                    UserAccount = "admin",
                    PassWord = "admin",
                    Role = 2
                });
                string listStr = JsonSerializer.Serialize(UserList, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(filePath, listStr);
            }
        }

        private void DelUserClick(object sender, RoutedEventArgs e)
        {
            if (userTable.SelectedItems.Count < 1)
            {
                MessageBox.Show("请选择至少一名用户！", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            MessageBoxResult result = MessageBox.Show($"确定执行删除操作？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                List<UserModel> deleteUsers = [];
                foreach (var item in userTable.SelectedItems)
                {
                    if (item is UserModel user)
                    {
                        deleteUsers.Add(user);
                    }
                }
                foreach (var deleteUser in deleteUsers)
                {
                    UserList.Remove(deleteUser);
                }
            }

        }

        private void GroupBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left) DragMove();
        }

        private void EditUserClick(object sender, RoutedEventArgs e)
        {
            if (userTable.SelectedItems.Count != 1)
            {
                MessageBox.Show("请选择一名用户！", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (userTable.SelectedItem is UserModel user)
            {
                var tmp = new UserSettingWindow(new(user));
                tmp.ShowDialog();
                var userFind = UserList.FirstOrDefault(x => x.UserAccount == tmp.UserInfo.UserAccount);
                if (userFind != null && userFind.UserId != tmp.UserInfo.UserId)
                {
                    MessageBox.Show("用户添加失败：账号已存在");
                    return;
                }
                if (tmp.IsSave)
                {
                    userFind!.UserName = tmp.UserInfo.UserName;
                    userFind!.PassWord = tmp.UserInfo.PassWord;
                    userFind!.LoginCount = tmp.UserInfo.LoginCount;
                    userFind!.Role = tmp.UserInfo.Role;
                }
            }
        }
    }
}
