/*
   绑定视图：Login.xaml
   文件说明：用于控制用户登录/退出
*/

using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using HslCommunication.Enthernet.Redis;
using MWS.Data.InterFace;
using MWS.Data.Manager;
using MWS.Domain.ViewModel;
using MWS.Library;
using MWS.Library.Common.Helper;
using MWS.Library.Common.MD5Poxy;
using MWS.Model;
using MWSDomain.Common.CoreLib;
using MWSDomain.SysModule;
using MWSDomain.ViewDialog.Sign;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;

namespace MWSDomain.ViewModel.Sign
{
    /// <summary>
    /// 登录逻辑处理
    /// </summary>
    public class LoginViewModel : BaseHostDialogOperation
    {
        #region 用户名/密码

        private string _Report;
        private string userName = string.Empty;
        private string passWord = string.Empty;
        private bool _IsCancel = true;
        private bool _UserChecked;



        /// <summary>
        /// 进度报告
        /// </summary>
        public string Report
        {
            get { return _Report; }
            set { _Report = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName
        {
            get { return userName; }
            set { userName = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 记住密码
        /// </summary>
        public bool UserChecked
        {
            get { return _UserChecked; }
            set { _UserChecked = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 密码
        /// </summary>
        public string Password
        {
            get { return passWord; }
            set { passWord = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 禁用按钮
        /// </summary>
        public bool IsCancel
        {
            get { return _IsCancel; }
            set { _IsCancel = value; RaisePropertyChanged(); }
        }

        #endregion 用户名/密码

        private RedisClient _redisClient;
        #region 命令(Binding Command)

        private RelayCommand _signCommand;

        public RelayCommand SignCommand
        {
            get
            {
                if (_signCommand == null)
                {
                    _signCommand = new RelayCommand(() => Login());
                }
                return _signCommand;
            }
        }

        private RelayCommand _exitCommand;

        public RelayCommand ExitCommand
        {
            get
            {
                if (_exitCommand == null)
                {
                    _exitCommand = new RelayCommand(() => ApplicationShutdown());
                }
                return _exitCommand;
            }
        }

        #endregion 命令(Binding Command)

        #region Login/Exit

        public LoginViewModel()
        {
            _redisClient = new RedisClient("127.0.0.1", 6379, null);
            _redisClient.SelectDB(1);

        }
        /// <summary>
        /// 登陆系统
        /// </summary>
        public async void Login()
        {
            try
            {
                //UserName = "admin";
                //passWord = "123123";
                if (!string.IsNullOrWhiteSpace(UserName) && !string.IsNullOrWhiteSpace(Password))
                {
                    this.IsCancel = false;
                    IUser user = new UserManager();
                    this.Report = "正在验证登录 . . .";
                    DateTime now = DateTime.Now;
                    var loginTask = await user.Login(UserName, CEncoder.Encode(Password));
                    if (loginTask.Success)
                    {
                        IUserLog userLog = new UserLogManager();
                        //if (UserChecked) SaveLoginInfo();

                        #region 设置用户基础信息

                        var req = loginTask.Data as 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 = req.Id,
                            CreateTime = now,
                            Account = req.Account,
                            UserName = req.UserName,
                            LoginTime = now,
                            LogOutTime = now
                        };
                        userLog.Insert(t_UserLog);
                        #endregion
                        #region 用户信息存redis

                        var userObject = new JObject {
                                   new JProperty("Id", req.Id),
                                   new JProperty("Account", req.Account),
                                   new JProperty("UserName", req.UserName),
                                   new JProperty("Password", req.Password),
                                   new JProperty("AutoLogin", UserChecked),
                                 };
                        var result = _redisClient.WriteKey("UserLogin", userObject.ToString());
                        #endregion
                        #region 加载用户资料

                        this.Report = "加载用户信息 . . .";

                        #endregion 加载用户资料

                        #region 初始化首页

                        this.Report = "初始化首页 . . .";
                        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();

                        #endregion 初始化首页
                    }
                    else
                        this.Report = loginTask.Message;
                }
                else
                {
                    this.Report = "账号或密码不对 . . .";
                }
            }
            catch (Exception ex)
            {
                this.Report = ex.Message;

                LogHelper.WriteLog("登录错误", ex);
            }
            finally
            {
                this.IsCancel = true;
            }
        }

        /// <summary>
        /// 自动登陆系统
        /// </summary>
        public async void AutoLogin()
        {
            try
            {
                UserName = "admin";
                passWord = "123123";
                if (!string.IsNullOrWhiteSpace(UserName) && !string.IsNullOrWhiteSpace(Password))
                {
                    this.IsCancel = false;
                    IUser user = new UserManager();
                    this.Report = "正在验证登录 . . .";
                    DateTime now = DateTime.Now;
                    var loginTask = await user.Login(UserName, CEncoder.Encode(Password));
                    if (loginTask.Success)
                    {
                        IUserLog userLog = new UserLogManager();
                        if (UserChecked) SaveLoginInfo();

                        #region 设置用户基础信息

                        var req = loginTask.Data as 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 = req.Id,
                            CreateTime = now,
                            Account = req.Account,
                            UserName = req.UserName,
                            LoginTime = now,
                            LogOutTime = now
                        };
                        userLog.Insert(t_UserLog);
                        #endregion
                        #region 用户信息存redis

                        var userObject = new JObject {
                                   new JProperty("Id", req.Id),
                                   new JProperty("Account", req.Account),
                                   new JProperty("UserName", req.UserName),
                                   new JProperty("Password", req.Password),
                                   new JProperty("AutoLogin", UserChecked),
                                 };
                        var result = _redisClient.WriteKey("UserLogin", userObject.ToString());
                        #endregion
                        #region 加载用户资料

                        this.Report = "加载用户信息 . . .";

                        #endregion 加载用户资料

                        #region 初始化首页

                        this.Report = "初始化首页 . . .";
                        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();

                        #endregion 初始化首页
                    }
                    else
                        this.Report = loginTask.Message;
                }
                else
                {
                    this.Report = "账号或密码不对 . . .";
                }
            }
            catch (Exception ex)
            {
                this.Report = ex.Message;

                LogHelper.WriteLog("登录错误", ex);
            }
            finally
            {
                this.IsCancel = true;
            }
        }

        /// <summary>
        /// 关闭系统
        /// </summary>
        public void ApplicationShutdown()
        {
            Messenger.Default.Send("", "ApplicationShutdown");
        }

        #endregion Login/Exit

        #region 记住密码

        /// <summary>
        /// 读取本地配置信息
        /// </summary>
        public void ReadConfigInfo()
        {
            string cfgINI = AppDomain.CurrentDomain.BaseDirectory + SerivceFiguration.INI_CFG;
            if (File.Exists(cfgINI))
            {
                IniFile ini = new IniFile(cfgINI);
                UserName = ini.IniReadValue("Login", "User");
                Password = CEncoder.Decode(ini.IniReadValue("Login", "Password"));
                UserChecked = ini.IniReadValue("Login", "SaveInfo") == "Y";
            }
        }

        /// <summary>
        /// 保存登录信息
        /// </summary>
        private void SaveLoginInfo()
        {
            string cfgINI = AppDomain.CurrentDomain.BaseDirectory + SerivceFiguration.INI_CFG;
            IniFile ini = new IniFile(cfgINI);
            ini.IniWriteValue("Login", "User", UserName);
            ini.IniWriteValue("Login", "Password", CEncoder.Encode(Password));
            ini.IniWriteValue("Login", "SaveInfo", UserChecked ? "Y" : "N");
        }

        #endregion 记住密码
    }
}