using log4net;
using log4net.Core;
using log4net.Repository.Hierarchy;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using DM_Weight.Finger;
using DM_Weight.Models;
using DM_Weight.msg;
using DM_Weight.Port;
using DM_Weight.util;
using DM_Weight.Views;
using System.Collections.ObjectModel;
using Microsoft.Win32;
using System.Xml;
using System.Diagnostics;
using DM_Weight.HIKVISION;
using System.Security.AccessControl;
namespace DM_Weight.ViewModels
{
    public class LoginWindowViewModel : BindableBase, IRegionMemberLifetime, IConfirmNavigationRequest
    {
        private readonly ILog logger = LogManager.GetLogger(typeof(LoginWindowViewModel));
        private string username;
        private string password;
        private Boolean _loginBtnEnable = true;
        IRegionManager _regionManager;
        IEventAggregator _eventAggregator;
        SocketHelper _socketHelper;
        private int loginMode = Convert.ToInt32(ConfigurationManager.AppSettings["loginMode"]?.ToString() ?? "1");
        private string firstLogin = ConfigurationManager.AppSettings["firstLogin"]?.ToString() ?? "operator";
        public bool SingleLogin
        {
            get => ReadAppSetting("loginMode") == "1";
            //get => loginMode == 1;
        }
        public bool MultiLogin
        {
            //get => loginMode == 2;
            get => ReadAppSetting("loginMode") == "2";
        }
        public string LoginUserCheck
        {
            get => ReadAppSetting("loginUser");
        }
        private HkcChangeShifts listHkcChangeShifts = new HkcChangeShifts();
        private FingerprintUtil _fingerprintUtil;
        private PortUtil _portUtil;
        //private CHKFunction _chkFunction;
        public Boolean LoginBtnEnable { get { return _loginBtnEnable; } set { SetProperty(ref _loginBtnEnable, value); } }
        public string Password { get { return password; } set { SetProperty(ref password, value); } }
        public string Username { get { return username; } set { SetProperty(ref username, value); } }
        public UserList Operator { get; set; }
        public UserList Reviewer { get; set; }
        //public bool DrawerPortMsg
        //{
        //    get => !_portUtil.drawerSerial.IsOpen;
        //}
        //public bool CanBusPortMsg
        //{
        //    get => _portUtil._canBusExsit && !_portUtil.canBusSerial.IsOpen;
        //}
        private bool _fingerMsg = CHKFunction.HKUserId >= 0;
        public bool FingerMsg
        {
            get => _fingerMsg;
            set => SetProperty(ref _fingerMsg, value);
        }
        /// 
        /// 网口连接标识
        /// 
        private bool _netMsg = false;
        public bool NetMsg
        {
            get => _netMsg;
            set => SetProperty(ref _netMsg, value);
        }
        //public bool FridgePortMsg
        //{
        //    get => !_portUtil.fridgeSerial.IsOpen;
        //}
        //温湿度
        public bool WSDPortMsg
        {
            get => !_portUtil.wsdSerial.IsOpen;
        }
        //录像机登录状态
        //private bool _hikMsg;
        //public bool HIKMsg
        //{
        //    get=>_hikMsg;
        //    set=>SetProperty(ref _hikMsg, value);
        //}
        //public LoginWindowViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, PortUtil portUtil, FingerprintUtil fingerprintUtil)
        //{
        //    _fingerprintUtil = fingerprintUtil;
        //    _portUtil = portUtil;
        //    _regionManager = regionManager;
        //    _eventAggregator = eventAggregator;
        //}
        public LoginWindowViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, PortUtil portUtil, FingerprintUtil fingerprintUtil,SocketHelper socketHelper)
        {
            _fingerprintUtil = fingerprintUtil;
            _portUtil = portUtil;
            //_chkFunction= chcFunction;
            _regionManager = regionManager;
            _eventAggregator = eventAggregator;
            _socketHelper= socketHelper;
            FingerMsg = !_fingerprintUtil.bIsConnected;
            NetMsg=!_socketHelper.ConnectedStatus;
            _eventAggregator.GetEvent().Subscribe(LoginEvent);
        }
        private DelegateCommand? _loginCommand;
        private DelegateCommand? _exitCommand;
        public DelegateCommand LoginCommand =>
_loginCommand ??= new DelegateCommand(Login);
        public DelegateCommand ExitCommand =>
_exitCommand ??= new DelegateCommand(Exit);
        public bool KeepAlive => false;
        void Login()
        {
            LoginBtnEnable = false;
            if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
            {
                if (Username.Equals("hkcadmin") && Password.Equals("hkc123"))
                {
                    ObservableCollection defaultAll = RoleManagerWindowViewModel.defaultAll;
                    PremissionDm[] a = new PremissionDm[defaultAll.Count];
                    Array.Copy(defaultAll.ToArray(), 0, a, 0, defaultAll.Count);
                    a[4].Children.Add(new PremissionDm()
                    {
                        Id = 54,
                        PremissionName = "调试页面",
                        PremissionPath = "DebugWindow",
                    });
                    //添加参数,键值对格式
                    keys.Add("operator", new UserList()
                    {
                        UserName = Username,
                        Nickname = "华康测试账号",
                        Id = 9999,
                        Role = new RoleDm()
                        {
                            Id = 9999,
                            RoleName = "hkcadmin",
                            Permissions = a.ToList()
                        },
                    });
                    _regionManager.RequestNavigate("MainRegion", "HomeWindow", keys);
                }
                else
                {
                    UserList userList = SqlSugarHelper.Db.Queryable()
                                        .Includes(u => u.Role)
                                        .First(u => u.UserName == username && (ConfigurationManager.AppSettings["machineId"].ToString().Equals(u.MachineId)));
                    if (userList == null)
                    {
                        AlertMsg alertMsg = new AlertMsg
                        {
                            Message = "无此用户",
                            Type = MsgType.ERROR
                        };
                        _eventAggregator.GetEvent().Publish(alertMsg);
                        Username = "";
                        Password = "";
                    }
                    else if (userList.Role == null || userList.Role.Permissions.Count <= 0)
                    {
                        AlertMsg alertMsg = new AlertMsg
                        {
                            Message = "用户还未设置权限,请联系管理员",
                            Type = MsgType.ERROR
                        };
                        _eventAggregator.GetEvent().Publish(alertMsg);
                        Username = "";
                        Password = "";
                    }
                    else
                    {
                        //1仅当班人、审核人可登录
                        if (LoginUserCheck.Equals("1"))
                        {
                            //检查当前登录人是否是值班人 (审核人与发药人)
                            listHkcChangeShifts = SqlSugarHelper.Db.Queryable()
                               .Where(cs => cs.State == "0").First();
                            if (listHkcChangeShifts != null)
                            {
                                if (!listHkcChangeShifts.FromOperator.Equals(userList.UserName) && !listHkcChangeShifts.FromRviewer.Equals(userList.UserName))
                                {
                                    AlertMsg alertMsg = new AlertMsg
                                    {
                                        Message = "仅值班人可登录,当前登录人非值班人",
                                        Type = MsgType.ERROR
                                    };
                                    _eventAggregator.GetEvent().Publish(alertMsg);
                                    Username = "";
                                    Password = "";
                                    return;
                                }
                            }
                        }
                        if (userList.PassWord == MD5.GetMD5Hash(Password))
                        {
                            SetUser(userList);
                        }
                        else
                        {
                            AlertMsg alertMsg = new AlertMsg
                            {
                                Message = "密码错误",
                                Type = MsgType.ERROR
                            };
                            _eventAggregator.GetEvent().Publish(alertMsg);
                            Password = "";
                        }
                    }
                }
            }
            else
            {
                AlertMsg alertMsg = new AlertMsg
                {
                    Message = "请输入账号或密码",
                    Type = MsgType.ERROR
                };
                _eventAggregator.GetEvent().Publish(alertMsg);
            }
            LoginBtnEnable = true;
        }
        private NavigationParameters keys = new NavigationParameters();
        void SetUser(UserList user)
        {
            // 单人登录模式
            if (SingleLogin)
            {
                //添加参数,键值对格式
                keys.Add("operator", user);
                //System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
                //{
                    _regionManager.RequestNavigate("MainRegion", "HomeWindow", keys);
                //}));
            }
            // 双人登录模式
            else
            {
                // 如果已经录入了发药人,已经有一个用户登录
                if (keys.ContainsKey("operator"))
                {
                    if (keys.GetValue("operator").Id != user.Id)
                    {
                        keys.Add("reviewer", user);
                        Reviewer = user;
                        RaisePropertyChanged("Reviewer");
                        //System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
                        //{
                        _regionManager.RequestNavigate("MainRegion", "HomeWindow", keys);
                        //}));
                    }
                    else
                    {
                        AlertMsg alertMsg = new AlertMsg
                        {
                            Message = "该发药人账号已登录,请输入不同账号",
                            Type = MsgType.ERROR
                        };
                        _eventAggregator.GetEvent().Publish(alertMsg);
                    }
                }
                // 如果已经录入了审核人, 已经有一个用户登录
                else if (keys.ContainsKey("reviewer"))
                {
                    if (keys.GetValue("reviewer").Id != user.Id)
                    {
                        keys.Add("operator", user);
                        Operator = user;
                        RaisePropertyChanged("Operator");
                        //System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
                        //{
                        _regionManager.RequestNavigate("MainRegion", "HomeWindow", keys);
                        //}));
                    }
                    else
                    {
                        AlertMsg alertMsg = new AlertMsg
                        {
                            Message = "该审核人账号已登录,请输入不同账号",
                            Type = MsgType.ERROR
                        };
                        _eventAggregator.GetEvent().Publish(alertMsg);
                    }
                }
                // 第一个用户登录
                else
                {
                    //1仅当班人、审核人可登录
                    if (LoginUserCheck.Equals("1"))
                    {
                        if (listHkcChangeShifts != null)
                        {
                            if (listHkcChangeShifts.FromOperator.Equals(user.UserName))
                            {
                                keys.Add("operator", user);
                                Operator = user;
                                RaisePropertyChanged("Operator");
                            }
                            else
                            {
                                keys.Add("reviewer", user);
                                Reviewer = user;
                                RaisePropertyChanged("Reviewer");
                            }
                            Username = string.Empty;
                            Password = string.Empty;
                            return;
                        }
                    }
                    if (firstLogin.Equals("operator"))
                    {
                        keys.Add("operator", user);
                        Operator = user;
                        RaisePropertyChanged("Operator");
                    }
                    else
                    {
                        keys.Add("reviewer", user);
                        Reviewer = user;
                        RaisePropertyChanged("Reviewer");
                    }
                    Username = string.Empty;
                    Password = string.Empty;
                }
            }
        }
        void Exit()
        {
            //_chkFunction.HIKLoginOut();
            Process.GetCurrentProcess().Kill();
            Environment.Exit(0);
        }
        void LoginEvent(FingerprintMsg msg)
        {
            logger.Info(msg.ToString());
            if (msg.Message.Equals("CONNECT"))
            {
                FingerMsg = !msg.Result;
            }
            if (LoginBtnEnable)
            {
                if (msg.Message.Equals("LOGIN"))
                {
                    UserList userList = SqlSugarHelper.Db.Queryable()
                    .Includes(u => u.Role)
                    .First(u => u.Id == msg.Id && (ConfigurationManager.AppSettings["machineId"].ToString().Equals(u.MachineId)));
                    if (userList == null)
                    {
                        AlertMsg alertMsg = new AlertMsg
                        {
                            Message = "无此用户",
                            Type = MsgType.ERROR
                        };
                        _eventAggregator.GetEvent().Publish(alertMsg);
                        Username = "";
                        Password = "";
                    }
                    else if (userList.Role == null)
                    {
                        AlertMsg alertMsg = new AlertMsg
                        {
                            Message = "用户还未设置权限,请联系管理员",
                            Type = MsgType.ERROR
                        };
                        _eventAggregator.GetEvent().Publish(alertMsg);
                        Username = "";
                        Password = "";
                    }
                    else
                    {
                        //1仅当班人、审核人可登录
                        if (LoginUserCheck.Equals("1"))
                        {
                            //检查当前登录人是否是值班人 (审核人与发药人)
                            listHkcChangeShifts = SqlSugarHelper.Db.Queryable()
                               .Where(cs => cs.State == "0").First();
                            if (listHkcChangeShifts != null)
                            {
                                if (!listHkcChangeShifts.FromOperator.Equals(userList.UserName) && !listHkcChangeShifts.FromRviewer.Equals(userList.UserName))
                                {
                                    AlertMsg alertMsg = new AlertMsg
                                    {
                                        Message = "仅值班人可登录,当前登录人非值班人",
                                        Type = MsgType.ERROR
                                    };
                                    _eventAggregator.GetEvent().Publish(alertMsg);
                                    Username = "";
                                    Password = "";
                                    return;
                                }
                            }
                        }
                        SetUser(userList);
                    }
                }
            }
        }
        //这个方法用于拦截请求,continuationCallback(true)就是不拦截,continuationCallback(false)拦截本次操作
        public void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback)
        {
            continuationCallback(true);
        }
        //接收导航传过来的参数  现在是在此处初始化了表格数据
        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            //FingerMsg = !_fingerprintUtil.bIsConnected;
            //_eventAggregator.GetEvent().Subscribe(LoginEvent);
        }
        //每次导航的时候,该实列用不用重新创建,true是不重新创建,false是重新创建
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }
        //这个方法用于拦截请求
        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            _eventAggregator.GetEvent().Unsubscribe(LoginEvent);
        }
        //手动实现调用配置的逻辑 规避修改配置文件后不起作用的问题
        public string ReadAppSetting(string key)
        {
            string xPath = $"/configuration/appSettings//add[@key='{key}']";
            XmlDocument doc = new XmlDocument();
            string exeFileName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            doc.Load(exeFileName + ".dll.config");
            XmlNode node = doc.SelectSingleNode(xPath);
            return node.Attributes["value"].Value.ToString();
        }
    }
}