using DM_Weight.Common;
using DM_Weight.Models;
using DM_Weight.msg;
using DM_Weight.Port;
using DM_Weight.util;
using log4net;
using log4net.Repository.Hierarchy;
using MaterialDesignThemes.Wpf;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
namespace DM_Weight.ViewModels
{
public class BiaoDingDialogViewModel : BindableBase, IDialogAware, IRegionMemberLifetime
{
private readonly ILog logger = LogManager.GetLogger(typeof(BiaoDingWindowViewModel));
public string Title => "标定";
public bool KeepAlive => false;
private string titleStr;
public string TitleStr
{
get => titleStr;
set { SetProperty(ref titleStr, value); }
}
private ChannelStock channelStock;
private string WindowName = "BiaoDingDialog";
private string strMessage;
public string StrMessage
{
get => strMessage;
set => SetProperty(ref strMessage, value);
}
private int _status = 0;
public int Status { get => _status; set => SetProperty(ref _status, value); }
private SolidColorBrush _colorBrush;
public SolidColorBrush SnackbarBackground
{
get => _colorBrush;
set => SetProperty(ref _colorBrush, value);
}
private ISnackbarMessageQueue _snackbarMessageQueue = new SnackbarMessageQueue(TimeSpan.FromSeconds(3));
public ISnackbarMessageQueue SnackbarMessageQueue
{
get => _snackbarMessageQueue;
set => SetProperty(ref _snackbarMessageQueue, value);
}
//标定数量
private int _bdQuantity = 0;
public int BDQuantity
{
get => _bdQuantity;
set => SetProperty(ref _bdQuantity, value);
}
///
/// 标定按钮是否可用
///
private bool _biaoDingEnable = true;
public bool BiaoDingEnable
{
get => _biaoDingEnable; set
{
SetProperty(ref _biaoDingEnable, value);
}
}
//关闭按钮是否可用
private bool _closeIsEnable = true;
public bool CloseIsEnable
{
get => _closeIsEnable;
set
{
SetProperty(ref _closeIsEnable, value);
}
}
public event Action RequestClose;
public bool CanCloseDialog()
{
return true;
}
public void OnDialogClosed()
{
// 取消消息订阅
//_eventAggregator.GetEvent().Unsubscribe(DoMyPrismEvent);
}
public void OnDialogOpened(IDialogParameters parameters)
{
//_eventAggregator.GetEvent().Subscribe(DoMyPrismEvent);
channelStock = parameters.GetValue("channelStock");
if (channelStock != null)
{
TitleStr = $"正在标定{channelStock.ColNo}号库位";
BiaoDingEnable = false;
if (channelStock.Quantity > 0)
{
StrMessage = "库位库存不为零,请取出药品后点击【清空】按钮,清空完成后输入标定数量并放入对应数量药品并根据下一步提示操作";
}
else
{
Status = 1;
StrMessage = "正在清零,清零完成后输入标定数量并放入对应数量药品后点击【标定】按钮";
ClearMethod();
}
}
}
private PortUtil _portUtil;
IEventAggregator _eventAggregator;
public BiaoDingDialogViewModel(PortUtil portUtil, IEventAggregator eventAggregator)
{
_portUtil = portUtil;
_eventAggregator = eventAggregator;
}
//void DoMyPrismEvent(DeviceMsg msg)
//{
// if (msg.WindowName.Equals(WindowName))
// {
// IGrouping grouping = enumerator.Current;
// int DrawerNo = grouping.Key;
// List channelStocks = grouping.ToList();
// switch (msg.EventType)
// {
// // 抽屉打开
// case EventType.DRAWEROPEN:
// if (Status == 1)
// {
// if (channelStocks[0].process == 1)
// {
// channelStocks.ForEach(it => it.process = 2);
// }
// }
// //是冰箱抽屉则开冰箱抽屉时发送延迟报警指令
// CheckIsFridgeOpen();
// break;
// // 抽屉关闭
// case EventType.DRAWERCLOSE:
// if (Status == 1)
// {
// if (channelStocks[0].process == 2)
// {
// channelStocks.ForEach(it => it.process = 3);
// }
// IGrouping groupingBefore = enumerator.Current;
// int DrawerNoBefore = groupingBefore.Key;
// if (enumerator.MoveNext())
// {
// IGrouping groupingAfter = enumerator.Current;
// int DrawerNoAfter = groupingAfter.Key;
// if (DrawerNoBefore < 9 && DrawerNoAfter > 8)
// {
// Thread.Sleep(50);
// }
// OpenOneByOne();
// }
// // 已经全部取出
// else
// {
// Status = 3;
// }
// }
// //是冰箱抽屉则开冰箱抽屉时发送延迟报警指令
// CheckIsFridgeClose();
// break;
// // 数量变化
// case EventType.UPDATEQUANTITY:
// if (Status == 1)
// {
// logger.Info($"抽屉【{DrawerNo}】库位药品数量【{msg.Quantitys}】");
// }
// break;
// // 打开失败
// case EventType.OPENERROR:
// AlertMsg alertMsg = new AlertMsg
// {
// Message = msg.Message,
// Type = MsgType.ERROR
// };
// _eventAggregator.GetEvent().Publish(alertMsg);
// Status = 0;
// break;
// }
// }
//}
//标定
public DelegateCommand BiaoDingCommand
{
get => new DelegateCommand(async () =>
{
if (BDQuantity <= 0)
{
AlertMsg alertMsg = new AlertMsg
{
Message = "请输入标定数量",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent().Publish(alertMsg);
return;
}
try
{
if (Status == 3)
{
CloseIsEnable = false;
//提示输入标定数量,发26指令
await _portUtil.SetNumCount(channelStock.DrawerNo, channelStock.ColNo, BDQuantity);
Status = 4;
Thread.Sleep(200);
_portUtil.DrawerNo = channelStock.DrawerNo;
//发27指令查询数量是否写标定时写入的数量一致,一致则标定成功,不一致则标定失败
int stock = await _portUtil.CheckQuantityForBiaoDing(channelStock.ColNo);
if (!(stock == BDQuantity))
{
int i = 1;
while (i <= 50 && i > 0 && Status > 0)
{
try
{
Thread.Sleep(200);
stock = await _portUtil.CheckQuantityForBiaoDing(channelStock.ColNo);
if (stock == BDQuantity)
{
logger.Info($"标定完成{stock},{BDQuantity},次数{i}"); //标定成功
AlertMsg alertMsg = new AlertMsg
{
Message = "标定成功",
Type = MsgType.SUCCESS,
};
_eventAggregator.GetEvent().Publish(alertMsg);
i = 0;
// 更新数据 标定状态
channelStock.PosNo = 1;
SqlSugarHelper.Db.Updateable(channelStock).UpdateColumns(it => it.PosNo).ExecuteCommand();
}
else
{
i++;
logger.Info($"标定数量不一致{stock},{BDQuantity},次数{i}");
}
}
catch (Exception ex)
{
logger.Error($"标定存在异常{ex.Message}");
continue;
}
}
RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel));
if (i == 51)
{
AlertMsg alertMsg = new AlertMsg
{
Message = "标定失败",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent().Publish(alertMsg);
}
}
else
{
//标定成功
AlertMsg alertMsg = new AlertMsg
{
Message = "标定成功",
Type = MsgType.SUCCESS,
};
_eventAggregator.GetEvent().Publish(alertMsg);
logger.Info($"标定完成{stock},{BDQuantity}");
}
CloseIsEnable = true;
}
}
catch (Exception e)
{
logger.Error($"标定异常{e.Message}");
AlertMsg alertMsg = new AlertMsg
{
Message = "标定失败",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent().Publish(alertMsg);
}
});
}
//清零
public DelegateCommand ClearCommand
{
get => new DelegateCommand(async () =>
{
////发计数请零指令
//await _portUtil.ClearCount(channelStock.DrawerNo, channelStock.ColNo);
//Status = 3;
//Thread.Sleep(300);
////发查数指令
//_portUtil.DrawerNo = channelStock.DrawerNo;
//int stock = await _portUtil.CheckQuantityForBiaoDing(channelStock.ColNo);
//if (stock != 0)
//{
// SnackbarBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#00e676"));
// SnackbarMessageQueue.Enqueue("清零成功");
// BiaoDingEnable = true;
//}
//else
//{
// SnackbarBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#f44336"));
// SnackbarMessageQueue.Enqueue("清零失败");
//}
//_portUtil.ResetData();
Status = 1;
ClearMethod();
});
}
//取消
public DelegateCommand CancelCommand
{
get => new DelegateCommand(() =>
{
logger.Info("取消");
Status = 0;
});
}
//关闭
public DelegateCommand BtnCloseCommand
{
get => new DelegateCommand(() =>
{
logger.Info("关闭窗口");
Status = 0;
RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel));
});
}
private void ClearMethod()
{
int i = 0;
int iClear = 0;
new PromiseUtil().taskAsyncLoop(200, 0, async (options, next, stop) =>
{
i++;
if (Status == 0 || i > 20)
{
System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{
SnackbarBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#f44336"));
SnackbarMessageQueue.Enqueue("清零失败,请重试操作");
}));
stop();
}
else
{
try
{
if (iClear == 0)
{
logger.Info($"清零操作{i}");
//无库存发送计数清零指令
await _portUtil.ClearCount(channelStock.DrawerNo, channelStock.ColNo);
iClear += 1;
next();
}
else
{
logger.Info($"查数操作{i}");
//发查数指令
_portUtil.DrawerNo = channelStock.DrawerNo;
_portUtil.Operate = true;
int stock = await _portUtil.CheckQuantityForBiaoDing(channelStock.ColNo);
if (stock != 0)
{
stop();
System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{
SnackbarBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#00e676"));
SnackbarMessageQueue.Enqueue("清零成功");
}));
BiaoDingEnable = true;
_portUtil.ResetData();
Status = 3;
}
else
{
next();
}
}
}
catch (Exception e)
{
logger.Error($"清零异常{e.Message}");
next();
}
}
});
}
}
}