using GalaSoft.MvvmLight.Messaging;
using HslCommunication.Enthernet.Redis;
using MWS.Data.InterFace;
using MWS.Data.Manager;
using MWS.Domain.ViewModel;
using MWS.Library.Common;
using MWS.Library.Common.MD5Poxy;
using MWS.Model;
using MWSDomain.ViewDialog.Sign;
using Newtonsoft.Json.Linq;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace MWSDomain.View.Sign
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class Login : Window
    {

        private RedisClient _redisClient;
        private User t_User;
        public Login()
        {
            InitializeComponent();
            _redisClient = new RedisClient("127.0.0.1", 6379, null);
            _redisClient.SelectDB(1);
            t_User = new User();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            AutoLogin();
        }
        /// <summary>
        /// 自动登陆系统
        /// </summary>
        public async void AutoLogin()
        {
            try
            {
                //UserName = "admin";
                //passWord = "123123";
                JObject userObject;
                var operateResult = _redisClient.ReadKey("UserLogin");
                if (operateResult.Content != null)
                {
                    userObject = JObject.Parse(operateResult.Content);
                    t_User.Id = userObject.GetValue("Id").ToSafeInt();
                    t_User.Account = userObject.GetValue("Account").ToSafeString();
                    t_User.UserName = userObject.GetValue("UserName").ToSafeString();
                    t_User.Password = userObject.GetValue("Password").ToSafeString();
                    t_User.IsLocked = Convert.ToBoolean(userObject.GetValue("AutoLogin").ToSafeString());

                }
                if (t_User.IsLocked)
                {
                    if (!string.IsNullOrWhiteSpace(t_User.Account) && !string.IsNullOrWhiteSpace(t_User.Password))
                    {

                        IUser user = new UserManager();
                        DateTime now = DateTime.Now;
                        var loginTask = await user.Login(t_User.Account, t_User.Password);
                        if (loginTask.Success)
                        {
                            IUserLog userLog = new UserLogManager();
                            //if (UserChecked) SaveLoginInfo();

                            //#region 设置用户基础信息

                            //var req = loginTask.Data as T_User;
                            //Loginer.LoginerUser.Account = req.Account;
                            //Loginer.LoginerUser.UserName = req.UserName;
                            //Loginer.LoginerUser.IsAdmin = req.Role == 1 ? true : false;

                            //#endregion 设置用户基础信息

                            #region 插入用户登录记录
                            UserLog t_UserLog = new UserLog()
                            {
                                UserId = t_User.Id,
                                CreateTime = now,
                                Account = t_User.Account,
                                UserName = t_User.UserName,
                                LoginTime = now,
                                LogOutTime = now
                            };
                            userLog.Insert(t_UserLog);
                            #endregion
                          
                            #region 初始化首页

                            MainViewModel model = new MainViewModel();
                            model.InitDefaultView();
                            var dialog = new MainViewDlg();
                            dialog.BindViewModel(model);
                            Messenger.Default.Send(string.Empty, "ApplicationHiding");
                            bool taskResult = await dialog.ShowDialog(null, model.ExtendedClosingEventHandler);
                            //this.ApplicationShutdown();
                            this.Close();
                            #endregion 初始化首页
                        }
                    }
                   
                }
               
            }
            catch (Exception ex)
            {
                
            }
            finally
            {
            }
        }
    }

    public static class PasswordBoxHelper
    {
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password",
            typeof(string), typeof(PasswordBoxHelper),
            new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));

        private static void OnPasswordPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;

            string password = (string)e.NewValue;

            if (passwordBox != null && passwordBox.Password != password)
            {
                passwordBox.Password = password;
            }
        }

        public static string GetPassword(DependencyObject dp)
        {
            return (string)dp.GetValue(PasswordProperty);
        }

        public static void SetPassword(DependencyObject dp, string value)
        {
            dp.SetValue(PasswordProperty, value);
        }
    }

    public class PasswordBoxBehavior : Behavior<PasswordBox>
    {
        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.PasswordChanged += OnPasswordChanged;
        }

        private static void OnPasswordChanged(object sender, RoutedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;

            string password = PasswordBoxHelper.GetPassword(passwordBox);

            if (passwordBox != null && passwordBox.Password != password)
            {
                PasswordBoxHelper.SetPassword(passwordBox, passwordBox.Password);
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            AssociatedObject.PasswordChanged -= OnPasswordChanged;
        }
    }

}
