using log4net;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using DM_Weight.Models;
using DM_Weight.Port;
using DM_Weight.util;
using DM_Weight.Views;
using System.Timers;
using Unity;
using System.Windows.Threading;
using Newtonsoft.Json.Linq;
using DM_Weight.msg;
using DM_Weight.Common;
using Microsoft.IdentityModel.Logging;
using System.Threading;
using System.Windows.Media;
namespace DM_Weight.ViewModels
{
public class HomeWindowViewModel : BindableBase, IConfirmNavigationRequest, IRegionMemberLifetime
{
private readonly ILog logger = LogManager.GetLogger(typeof(HomeWindowViewModel));
private readonly IDialogService _dialogService;
private UserList? _userList;
private UserList? _userList2;
///
/// 冰箱温度
///
private string _wd = "恒温冷藏抽屉当前温度2.8(非真实数据)";
public string WD { get => _wd; set => SetProperty(ref _wd, value); }
private SolidColorBrush _alertColor = Brushes.White;
public SolidColorBrush AlertColor
{
get => _alertColor;
set => SetProperty(ref _alertColor, value);
}
private int loginMode = Convert.ToInt32(ConfigurationManager.AppSettings["loginMode"]?.ToString() ?? "1");
public bool MultiLogin
{
get => loginMode == 2;
}
//温度区间
private string TemperatureRange = CommonClass.ReadAppSetting("temperatureRange").ToString();
//温度不在区间计时器(超过配置文件中的时间后要报警)
public DateTime? FridgeTime { get; set; }
//冰箱是否异常状态:0正常,1异常
//public string FridgeWorkingState = ConfigurationManager.AppSettings["FridgeworkingState"].ToString();
//冰箱开关状态:0开,1关
public string FridgeState = ConfigurationManager.AppSettings["FridgeState"].ToString();
//冰箱渡不在区间超时时间
private string _outRangeTime = ConfigurationManager.AppSettings["OutRangeTime"].ToString();
public string OutRangeTime { get => _outRangeTime; set => SetProperty(ref _outRangeTime, value); }
private PremissionDm? _selectedMenu;
private PremissionDm? _selectedChildMenu;
private List? _premissionDmList;
public PremissionDm? SelectedChildMenu
{
get { return _selectedChildMenu; }
set
{
if (!_portUtil.Operate)
{
if (value != null)
{
if (value.PremissionPath.Equals("TakeRecordWindow"))
{
//定义传参变量
NavigationParameters keys = new NavigationParameters();
//添加参数,键值对格式
keys.Add("Type", 2);
_regionManager.RequestNavigate("ContentRegion", "MachineRecordWindow", keys);
}
else if (value.PremissionPath.Equals("AddRecordWindow"))
{
//定义传参变量
NavigationParameters keys = new NavigationParameters();
//添加参数,键值对格式
keys.Add("Type", 1);
_regionManager.RequestNavigate("ContentRegion", "MachineRecordWindow", keys);
}
else if (value.PremissionPath.Equals("ReturnRecordWindow"))
{
//定义传参变量
NavigationParameters keys = new NavigationParameters();
//添加参数,键值对格式
keys.Add("Type", 3);
_regionManager.RequestNavigate("ContentRegion", "MachineRecordWindow", keys);
}
else if (value.PremissionPath.Equals("RetrunEmptyRecordWindow"))
{
//定义传参变量
NavigationParameters keys = new NavigationParameters();
//添加参数,键值对格式
keys.Add("Type", 3);
_regionManager.RequestNavigate("ContentRegion", value.PremissionPath, keys);
}
else if (value.PremissionPath.Equals("CheckRecordWindow"))
{
//定义传参变量
NavigationParameters keys = new NavigationParameters();
//添加参数,键值对格式
keys.Add("Type", 4);
_regionManager.RequestNavigate("ContentRegion", "MachineRecordWindow", keys);
}
else
{
if (value.PremissionPath.Equals("ReturnDrugWindow") || value.PremissionPath.Equals("ReturnDrugWindow2"))
{
if (ConfigurationManager.AppSettings["returnDrugMode"].ToString().Equals("1"))
{
_regionManager.RequestNavigate("ContentRegion", "ReturnDrugWindow2");
}
else
{
_regionManager.RequestNavigate("ContentRegion", "ReturnDrugWindow");
}
}
else
{
_regionManager.RequestNavigate("ContentRegion", value.PremissionPath);
}
}
}
SetProperty(ref _selectedChildMenu, value);
}
}
}
public PremissionDm? SelectedMenu
{
get { return _selectedMenu; }
set
{
//if (value != null)
//{
// if (value.PremissionName == "退出")
// {
// logger.Info($"用户【{Operator?.Nickname}】退出登录");
// Operator = null;
// Reviewer = null;
// _regionManager.RequestNavigate("MainRegion", "LoginWindow");
// }
// else
// {
// SelectedChildMenu = value.Children[0];
// }
//}
SetProperty(ref _selectedMenu, value);
}
}
private DelegateCommand _selectionCommon;
public DelegateCommand SelectionCommon
{
get => _selectionCommon ?? (_selectionCommon = new DelegateCommand(SelectionMethod));
}
private void SelectionMethod(ListBox viewName)
{
SelectedMenu = viewName.SelectedItem as PremissionDm;
if (SelectedMenu.PremissionName == "退出")
{
logger.Info($"用户【{Operator?.Nickname}】退出登录");
Operator = null;
Reviewer = null;
_regionManager.RequestNavigate("MainRegion", "LoginWindow");
}
else
{
//SelectedMenu.Children = SelectedMenu.Children;
SelectedChildMenu = SelectedMenu.Children[0];
}
}
public List PremissionDmList { get { return _premissionDmList; } set { SetProperty(ref _premissionDmList, value); } }
public UserList UserList { get { return _userList; } set { SetProperty(ref _userList, value); } }
public UserList UserList2 { get { return _userList2; } set { SetProperty(ref _userList2, value); } }
public static UserList? Operator;
public static UserList? Reviewer;
IRegionManager _regionManager;
IUnityContainer _container;
//是否退出
bool IsLeave = false;
private bool _is16Drawer;
public bool Is16Drawer { get => _is16Drawer; set => SetProperty(ref _is16Drawer, value); }
public bool KeepAlive => false;
private PortUtil _portUtil;
IEventAggregator _eventAggregator;
public HomeWindowViewModel(IRegionManager iRegionManager, PortUtil portUtil, IDialogService dialogService, IUnityContainer container, IEventAggregator eventAggregator)
{
_portUtil = portUtil;
_regionManager = iRegionManager;
_dialogService = dialogService;
_container = container;
this._eventAggregator = eventAggregator;
}
public DelegateCommand OpenFingerDialog
{
get => new DelegateCommand((string Type) =>
{
DialogParameters dialogParameters = new DialogParameters();
dialogParameters.Add("User", Type.Equals("Operator") ? Operator : Reviewer);
DialogServiceExtensions.ShowDialogHost(_dialogService, "FingerprintDialog", dialogParameters, DoDialogResult, "RootDialog");
});
}
public DelegateCommand OpenRecoverCommand
{
get => new DelegateCommand(async () =>
{
try
{
_portUtil.WindowName = "HomeWindow";
_portUtil.Operate = true;
await _portUtil.OpenStorage();
_portUtil.ResetData();
}
catch (Exception ex)
{
logger.Info($"OpenRecoverCommand异常{ex.Message}");
}
});
}
public DelegateCommand OpenEditPasswordDialog
{
get => new DelegateCommand((string Type) =>
{
DialogParameters dialogParameters = new DialogParameters();
dialogParameters.Add("EditPass", true);
dialogParameters.Add("User", Type.Equals("Operator") ? Operator : Reviewer);
DialogServiceExtensions.ShowDialogHost(_dialogService, "EditUserDialog", dialogParameters, DoDialogResult, "RootDialog");
});
}
private void DoDialogResult(IDialogResult dialogResult)
{
// 委托 被动执行 被子窗口执行
// dialogResult 第一方面可以拿到任意参数 第二方面 可判断关闭状态
if (dialogResult.Result == ButtonResult.OK)
{
}
}
public void FindDrawerCount()
{
int count = 0;
if (ConfigurationManager.AppSettings["MultiBatch"].ToString().Equals("1"))
{
count = SqlSugarHelper.Db.Queryable().Where(cs => cs.DrawerType != (Int32)DrawerTypeEnum.recyle)
.Where(cs => cs.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1")).GroupBy(cs => cs.DrawerNo).Select(cs => SqlFunc.AggregateCount(cs.DrawerNo)).Count();
}
else
{
count = SqlSugarHelper.Db.Queryable().Where(cs => cs.DrawerType != (Int32)DrawerTypeEnum.recyle)
.Where(cs => cs.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1")).GroupBy(cs => cs.DrawerNo).Select(cs => SqlFunc.AggregateCount(cs.DrawerNo)).Count();
}
Is16Drawer = count == 16;
}
///
/// 将收到的返回转换成具体温度数值
///
///
///
public string GetResultWD(string receiveData)
{
try
{
//string newStrWD = receiveData.Substring(10, 4);
//logger.Info($"截取后数据newStrWD:{newStrWD}");
int iWD = Convert.ToInt32(receiveData, 16);
logger.Info($"截取后数据iWD:{iWD}");
float fWD = 0;
if (iWD != 0)
{
fWD = iWD * 1.0f / 10;
}
logger.Info($"截取后数据fWD:{fWD}");
string strRet = $"恒温冷藏抽屉当前温度:{fWD}℃;";
return strRet;
}
catch (Exception ex)
{
logger.Info("GetResultWD异常", new Exception($"{ex.ToString()}"));
}
return "数据异常";
}
//这个方法用于拦截请求,continuationCallback(true)就是不拦截,continuationCallback(false)拦截本次操作
public void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback)
{
continuationCallback(true);
}
//接收导航传过来的参数
public void OnNavigatedTo(NavigationContext navigationContext)
{
_portUtil.dateTime = DateTime.Now;
//取出user
UserList = navigationContext.Parameters.GetValue("operator");
Operator = UserList;
logger.Info($"发药人【{Operator.Nickname}】登录");
if (navigationContext.Parameters.ContainsKey("reviewer"))
{
UserList2 = navigationContext.Parameters.GetValue("reviewer");
Reviewer = UserList2;
logger.Info($"审核人【{Reviewer.Nickname}】登录");
}
List premissions = UserList.Role.Permissions;
if (premissions.Count <= 0)
{
Operator = null;
Reviewer = null;
Application.Current.Dispatcher.Invoke(() =>
{
_regionManager.RequestNavigate("MainRegion", "LoginWindow");
});
AlertMsg alertMsg = new AlertMsg
{
Message = $"用户{UserList.Nickname}或还未设置权限,请联系管理员",
Type = MsgType.ERROR
};
_eventAggregator.GetEvent().Publish(alertMsg);
return;
}
//SqlSugarHelper.Db.SqlQueryable(sql)
//.ToTree(pd => pd.Children, pd => pd.ParentId, 0);
PremissionDmList = premissions;
SelectedMenu = premissions[0];
SelectedChildMenu = premissions[0].Children[0];
FindDrawerCount();
int autoExit = Convert.ToInt32(ConfigurationManager.AppSettings["autoExit"] ?? "0");
if (autoExit > 0)
{
//int interval = autoExit * 1000;
new PromiseUtil().taskAsyncLoop(1000, 0, async (options, next, stop) =>
{
try
{
if (!_portUtil.Operate)
{
// 无人操作鼠标键盘
if ((DateTime.Now - _portUtil.dateTime).TotalSeconds > autoExit && CheckComputerFreeState.GetLastInputTime() > autoExit)
{
logger.Info($"设备{autoExit}内无人操作,用户【{Operator?.Nickname}】自动退出登录,_portUtil.Operate:{_portUtil.Operate},totalSecond:{(DateTime.Now - _portUtil.dateTime).TotalSeconds},lastInputTime:{CheckComputerFreeState.GetLastInputTime()},autoExit:{autoExit}");
Operator = null;
Reviewer = null;
//Application.Current.Dispatcher.Invoke(() =>
//{
stop();
System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{
_regionManager.RequestNavigate("MainRegion", "LoginWindow");
}));
//});
//timer.Dispose();
}
else
{
if (Operator == null)
{
stop();
}
else
{
next();
}
}
}
else
{
_portUtil.dateTime = DateTime.Now;
next();
}
}
catch (Exception ex)
{
logger.Info($"自动退出异常:{ex.Message}");
}
});
}
GetFridgeTemperature();
_eventAggregator.GetEvent().Subscribe(GetFridgeTemperature);
}
//获取冰箱温度定时
private void GetFridgeTemperature()
{
//根据配置文件中的 冰箱温度定时时间循环
logger.Info("获取冰箱温度定时");
int TemperatureTimer = Convert.ToInt32(CommonClass.ReadAppSetting("TemperatureTimer")) * 1000;
logger.Info($"获取冰箱温度定时-TemperatureTimer");
string[] tempRange = TemperatureRange.Split('-');
new PromiseUtil().taskAsyncLoop(TemperatureTimer, 0, async (options, next, stop) =>
{
try
{
FridgeState = CommonClass.ReadAppSetting("FridgeState");
if (!_portUtil.FridgeOperate && FridgeState.Equals("0"))
{
string retStr = string.Empty;
byte[] data = null;
float retT = await _portUtil.GetFridgeTemperature();
Thread.Sleep(80);
WD = $"恒温冷藏抽屉当前温度:{Math.Round((retT), 2)}℃;";
AlertColor = Brushes.White;
logger.Info(WD);
if (tempRange != null && tempRange.Count() >= 2)
{
if (retT < Convert.ToSingle(tempRange[0]) || retT > Convert.ToSingle(tempRange[1]))
{
//查询制冷片温度
float retT2 = await _portUtil.GetFridgeTemperature2();
if (retT2 > 65)
{
if (!FridgeState.Equals("1"))
{
//停掉冰箱
await _portUtil.FridgeOff();
CommonClass.SaveAppSetting("FridgeState", "1");
//AlertMsg alertMsg = new AlertMsg
//{
// Message = $"冰箱制冷片温度超过65度,已关闭冰箱制冷功能!!!",
// Type = MsgType.ERROR
//};
//_eventAggregator.GetEvent().Publish(alertMsg);
System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{
DialogParameters dialogParameters = new DialogParameters();
dialogParameters.Add("warnMessage", "冰箱制冷片温度超过65度,已关闭冰箱制冷功能!!!");
DialogServiceExtensions.ShowDialogHost(_dialogService, "WarnDialog", dialogParameters, DoDialogResult, "RootDialog");
}));
}
logger.Info($"制冷片温度超过65度");
Thread.Sleep(100);
//给出提示
WD += "冰箱温度异常,已关闭冰箱制冷功能";
AlertColor = Brushes.Red;
FridgeTime = null;
stop();
}
else
{
if (FridgeTime == null)
{
FridgeTime = DateTime.Now;
//温度不在范围,但没有超过时间
if (IsLeave)
{
FridgeTime = null;
stop();
}
else
{
next();
}
}
else
{
if ((DateTime.Now - FridgeTime.Value).TotalMinutes > Convert.ToInt32(OutRangeTime))
{
logger.Info($"冰箱温度不在范围内,超过{OutRangeTime}分钟");
//停掉冰箱
await _portUtil.FridgeOff();
Thread.Sleep(100);
CommonClass.SaveAppSetting("FridgeState", "0");
//给出提示
WD += "冰箱温度异常,已关闭冰箱制冷功能;";
AlertColor = Brushes.Red;
FridgeState = "1";
CommonClass.SaveAppSetting("FridgeState", "1");
//AlertMsg alertMsg = new AlertMsg
//{
// Message = $"冰箱温度异常,已关闭冰箱制冷功能!!!",
// Type = MsgType.ERROR
//};
//_eventAggregator.GetEvent().Publish(alertMsg);
System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{
DialogParameters dialogParameters = new DialogParameters();
dialogParameters.Add("warnMessage", "冰箱温度异常,已关闭冰箱制冷功能!!!");
DialogServiceExtensions.ShowDialogHost(_dialogService, "WarnDialog", dialogParameters, DoDialogResult, "RootDialog");
}));
FridgeTime = null;
stop();
}
else
{
//温度不在范围,但没有超过时间
if (IsLeave)
{
FridgeTime = null;
stop();
}
else
{
next();
}
}
}
}
}
else
{
if (IsLeave)
{
FridgeTime = null;
stop();
}
else
{
next();
}
}
}
else
{
logger.Info($"获取冰箱温度范围有误{TemperatureRange}");
//if (Convert.ToInt32(ConfigurationManager.AppSettings["hasFridge"]) > 1)
//{
// float retTemp = await _portUtil.GetFridgeTemperature(2);
// Thread.Sleep(80);
// WD += $"{retTemp}℃";
//}
if (IsLeave)
{
FridgeTime = null;
stop();
}
else
{
next();
}
}
}
else
{
WD = $"恒温冷藏抽屉串口关闭或冰箱制冷异常制冷关闭!!!";
AlertColor = Brushes.Red;
FridgeTime = null;
stop();
}
}
catch (Exception ex)
{
logger.Info($"获取冰箱异常:{ex.Message}");
next();
}
});
}
//每次导航的时候,该实列用不用重新创建,true是不重新创建,false是重新创建
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
//这个方法用于拦截请求
public void OnNavigatedFrom(NavigationContext navigationContext)
{
IsLeave = true;
navigationContext.NavigationService.Region.RegionManager.Regions.Remove(PrismManager.SettingViewRegionName);
_eventAggregator.GetEvent().Unsubscribe(GetFridgeTemperature);
}
}
}