using 智慧物流软件系统.ViewModel;
using HandyControl.Controls;
using HandyControl.Tools.Extension;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
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 MessageBox = HandyControl.Controls.MessageBox;
using Window = System.Windows.Window;
using 智慧物流软件系统.Views.Controls;
using WCS.Model.ApiModel.User;
using WCS.Model;
using 智慧物流软件系统.Api;
using WCS.Model.ApiModel;

namespace 智慧物流软件系统
{
    /// <summary>
    /// 用户信息
    /// </summary>
    public partial class UserEditView : Window
    {
        public UserEditView()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns>true:成功，false:取消</returns>
        public static bool Show(UserModel userBase, CrudEnum crudEnum)
        {
            bool isOk = false;

            var roleList = new List<RoleModel>();
            //调用接口获取权限列表
            var dia = Dialog.Show(new TextDialog());
            try
            {
                var body = new GetUsersRequest()
                {
                    UserName = LocalStatic.CurrentUser,
                    DeviceType = LocalFile.Config.DeviceType,
                    Info = string.Empty,
                };
                var Result = ApiHelp.GetDataFromHttp<ResponseBase<List<RoleModel>>>(LocalFile.Config.ApiIpHost + "user/getRoles", body, "POST");
                if (Result != null && Result.Data != null)
                {
                    roleList = Result.Data;
                }
            }
            catch (Exception ex)
            {
                Growl.Error("加载数据失败：" + ex.Message);
            }
            finally
            {
                dia.Close();
            }

            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                var view = new UserEditView();

                try
                {
                    if (crudEnum == CrudEnum.Read)
                        view.qr.IsEnabled = false;

                    var rs = roleList.Where(o => !o.IsAdmin).ToList();

                    view.textBox.Text = userBase.LoginName;
                    view.passwordBox.Password = userBase.Password;
                    view.checkComboBox.ItemsSource = rs;
                    view.checkComboBox.DisplayMemberPath = nameof(RoleModel.Name);
                    view.checkComboBox.SelectedValuePath = nameof(RoleModel.Id);

                    //var aaa = rs.Where(o => userBase.RoleIds.Contains(o.Id)).ToList();
                    //ListBoxAttach.SetSelectedItems(view.checkComboBox, aaa);

                    foreach (var item in userBase.RoleIds)
                    {
                        var aaa = rs.FirstOrDefault(o => o.Id == item);
                        if (aaa != null)
                            view.checkComboBox.SelectedItems.Add(aaa);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    view = null;
                    return;
                }

                view.qr.Click += (s, e) =>
                {
                    try
                    {
                        UserModel newuser = new UserModel()
                        {
                            Id = userBase.Id,
                            IsAdmin = userBase.IsAdmin,
                            LoginName = view.textBox.Text.Trim(),
                            Password = view.passwordBox.Password,
                            RoleIds = view.checkComboBox.SelectedItems.Cast<RoleModel>().Select(o => o.Id).ToList(),
                            Time = userBase.Time,
                        };

                        if (crudEnum == CrudEnum.Update)
                        {
                            if (string.IsNullOrEmpty(newuser.LoginName))
                            {
                                MessageBox.Show("请输入名称");
                                return;
                            }
                            try
                            {
                                var body = new AddUserRequest<UserModel>()
                                {
                                    UserName = LocalStatic.CurrentUser,
                                    DeviceType = LocalFile.Config.DeviceType,
                                    User = newuser,
                                    AddOrUpdate = AddOrUpdate.Update
                                };
                                var Result = ApiHelp.GetDataFromHttp<ResponseCommon<object>>(LocalFile.Config.ApiIpHost + "user/addUser", body, "POST");
                                if (Result != null && Result.Code == 200)
                                {
                                    isOk = true;
                                    view.Close();
                                }
                                else
                                {
                                    Growl.Error(Result.Message);
                                }
                            }
                            catch (Exception ex)
                            {
                                Growl.Error("更新数据失败：" + ex.Message);
                            }

                        }
                        else if (crudEnum == CrudEnum.Create)
                        {
                            newuser.Id = 0;
                            newuser.Time = DateTime.Now;

                            if (string.IsNullOrEmpty(newuser.LoginName))
                            {
                                MessageBox.Show("请输入名称");
                                return;
                            }

                            //调用接口获取权限列表
                            try
                            {
                                var body = new AddUserRequest<UserModel>()
                                {
                                    UserName = LocalStatic.CurrentUser,
                                    DeviceType = LocalFile.Config.DeviceType,
                                    User = newuser,
                                    AddOrUpdate = AddOrUpdate.Add
                                };
                                var Result = ApiHelp.GetDataFromHttp<ResponseCommon<object>>(LocalFile.Config.ApiIpHost + "user/addUser", body, "POST");
                                if (Result != null && Result.Code == 200)
                                {
                                    isOk = true;
                                    view.Close();
                                }
                                else
                                {
                                    Growl.Error(Result.Message);
                                }
                            }
                            catch (Exception ex)
                            {
                                Growl.Error("新增用户失败：" + ex.Message);
                            }
                        }
                        else
                        {
                            MessageBox.Show("不支持此操作");
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                        return;
                    }
                    //isOk = true;
                    //view.Close();
                };

                view.ShowDialog();
                view = null;
            }));

            return isOk;
        }

        private void qx(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
