using log4net; using log4net.Repository.Hierarchy; using Prism.Commands; using Prism.Events; using Prism.Mvvm; using Prism.Regions; using Prism.Services.Dialogs; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Speech.Synthesis; using System.Text; using System.Threading.Tasks; using DM_Weight.Models; using DM_Weight.msg; using DM_Weight.Port; using DM_Weight.util; using DM_Weight.Common; using System.Threading; namespace DM_Weight.ViewModels { public class ReturnDrugDialogViewModel : BindableBase, IDialogAware, IRegionMemberLifetime { private readonly ILog logger = LogManager.GetLogger(typeof(ReturnDrugDialogViewModel)); public string Title => "归还药品(记录)"; public event Action RequestClose; private static readonly DateTime Jan1st1970 = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); private string WindowName = "ReturnDrug1Window"; private PortUtil _portUtil; IEventAggregator _eventAggregator; private MachineRecord _machineRecord; public MachineRecord MachineRecord { get { return _machineRecord; } set { SetProperty(ref _machineRecord, value); } } public ReturnDrugDialogViewModel(PortUtil portUtil, IEventAggregator eventAggregator) { _portUtil = portUtil; _eventAggregator = eventAggregator; } void DoMyPrismEvent(DeviceMsg msg) { if (msg.WindowName.Equals(WindowName)) { switch (msg.EventType) { // 抽屉打开 case EventType.DRAWEROPEN: if (Status == 1) { Status = 2; } //是冰箱抽屉则开冰箱抽屉时发送延迟报警指令 CheckIsFridgeOpen(); break; // 抽屉关闭 case EventType.DRAWERCLOSE: if (Status == 2) { Status = 3; } //是冰箱抽屉则开冰箱抽屉时发送延迟报警指令 CheckIsFridgeClose(); break; // 数量变化 case EventType.UPDATEQUANTITY: try { if (Status == 2) { ReturnQuantity = msg.Quantitys[ChannelStock.ColNo - 1]; logger.Info($"抽屉【{ChannelStock.DrawerNo}】库位药品数量【{msg.Quantitys}】"); } } catch (Exception e) { logger.Error(e); } break; // 打开失败 case EventType.OPENERROR: AlertMsg alertMsg = new AlertMsg { Message = msg.Message, Type = MsgType.ERROR, }; _eventAggregator.GetEvent().Publish(alertMsg); Status = 0; break; } } } private int _status = 0; public int Status { get => _status; set => SetProperty(ref _status, value); } private List _channelStocks; public List ChannelStocks { get => _channelStocks; set => SetProperty(ref _channelStocks, value); } private ChannelStock _channelStock; public ChannelStock ChannelStock { get => _channelStock; set => SetProperty(ref _channelStock, value); } private int _returnQuantity; public int ReturnQuantity { get => _returnQuantity; set { if (value < 0) { throw new ArgumentException("还药数量不能是负数"); } if (value > MachineRecord.CanReturnQuantity) { throw new ArgumentException("还药数量超出"); } SetProperty(ref _returnQuantity, value); } } public bool CanCloseDialog() { return Status == 0; } public void OnDialogClosed() { // 取消消息订阅 _eventAggregator.GetEvent().Unsubscribe(DoMyPrismEvent); } public void OnDialogOpened(IDialogParameters parameters) { _eventAggregator.GetEvent().Subscribe(DoMyPrismEvent); MachineRecord _record = parameters.GetValue("record"); MachineRecord = _record; ReturnQuantity = MachineRecord.CanReturnQuantity; RequestData(); } public void RequestData() { List queryData = SqlSugarHelper.Db.Queryable() .Where(cs => cs.DrugId == MachineRecord.DrugId) .Where(cs => cs.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1")) .WhereIF(MachineRecord.ManuNo != null,cs => cs.ManuNo == MachineRecord.ManuNo) .OrderBy(cs => cs.DrawerNo) .OrderBy(cs => cs.ColNo) .ToList(); ChannelStocks = queryData; if(ChannelStocks.Count > 0) { ChannelStock = ChannelStocks[0]; } } public DelegateCommand OpenDrawer { get => new DelegateCommand(() => { if (ChannelStock != null) { Status = 1; _portUtil.SpeakAsync("正在打开" + ChannelStock.DrawerNo + "号抽屉"); _portUtil.WindowName = WindowName; _portUtil.BoardType = ChannelStock.BoardType; _portUtil.ColNos = new int[] { ChannelStock.ColNo }; _portUtil.DrawerNo = ChannelStock.DrawerNo; _portUtil.Start(); } else { AlertMsg alertMsg = new AlertMsg { Message = "请选择退还药品要放入的库位!", Type = MsgType.ERROR, }; _eventAggregator.GetEvent().Publish(alertMsg); } }, () => Status == 0); } private bool _isFinishClick = false; public bool IsFinishClick { get => _isFinishClick; set => SetProperty(ref _isFinishClick, value); } // 完成按钮 public DelegateCommand TakeFinish { get => new DelegateCommand(() => { IsFinishClick = true; string InvoiceId = "RETURN_" + CurrentTimeMillis(); var f = SqlSugarHelper.Db.UseTran(() => { // 更新数据 库存信息 SqlSugarHelper.Db.Updateable(new ChannelStock() { Quantity = ChannelStock.Quantity + ReturnQuantity, Id = ChannelStock.Id, }).UpdateColumns(it => new { it.Quantity }).ExecuteCommand(); // 获取更新完库存后的药品库存 List nowChannels = SqlSugarHelper.Db.Queryable() .Where(cs => cs.MachineId.Equals(ChannelStock.MachineId)) .Where(cs => cs.DrugId.Equals(ChannelStock.DrugId)) .Where(cs => cs.DrawerType == (Int32)DrawerTypeEnum.drawerTypeOne) .ToList(); // 更新数据 取药记录 设置还药数量、状态 SqlSugarHelper.Db.Updateable(new MachineRecord() { ReturnQuantity1 = MachineRecord.ReturnQuantity1 + ReturnQuantity, Id = MachineRecord.Id, Status = (MachineRecord.CanReturnQuantity - ReturnQuantity) == 0 ? 2 : 1, }).UpdateColumns(it => new { it.ReturnQuantity1, it.Status }).ExecuteCommand(); // 保存数据 还药记录 SqlSugarHelper.Db.Insertable(new MachineRecord() { MachineId = ChannelStock.MachineId, DrawerNo = ChannelStock.DrawerNo, ColNo = ChannelStock.ColNo, DrugId = ChannelStock.DrugId, ManuNo = ChannelStock.ManuNo, EffDate = !String.IsNullOrEmpty(ChannelStock.EffDate) ? DateTime.ParseExact(ChannelStock.EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null, Operator = HomeWindowViewModel.Operator?.Id, OperationTime = DateTime.Now, Quantity = ReturnQuantity, Type = 31, InvoiceId = InvoiceId, GetId = MachineRecord.Id, StockQuantity = nowChannels.Sum(it => it.Quantity) }).ExecuteCommand(); //称重计数或称重+智能显示+管控药盒 类型需要 发26指令 //if (ChannelStock.BoardType == (Int32)BoardTypeEnum.weigh || ChannelStock.BoardType == (Int32)BoardTypeEnum.weighSmartBox) //{ // //计数数量设置,发送称重26指令 // _portUtil.SetNumCount(ChannelStock.DrawerNo, ChannelStock.ColNo, ChannelStock.AddQuantity); // Thread.Sleep(80); //} return true; }); if (f.Data) { // 更新屏显库存 if (ChannelStock.BoardType == (Int32)BoardTypeEnum.smart|| ChannelStock.BoardType == (Int32)BoardTypeEnum.weighSmartBox) { _portUtil.WriteQuantityMethod(ChannelStock.Quantity + ReturnQuantity,ChannelStock.DrawerNo, ChannelStock.ColNo); Thread.Sleep(200); } AlertMsg alertMsg = new AlertMsg { Message = "操作完成,库存已更新", Type = MsgType.SUCCESS, }; _eventAggregator.GetEvent().Publish(alertMsg); } if (!f.IsSuccess) { AlertMsg alertMsg = new AlertMsg { Message = "库存更新失败!", Type = MsgType.ERROR, }; _eventAggregator.GetEvent().Publish(alertMsg); } Status = 0; IsFinishClick = false; RequestClose?.Invoke(new DialogResult(ButtonResult.OK)); }, () => !IsFinishClick && ReturnQuantity > 0).ObservesProperty(() => IsFinishClick).ObservesProperty(() => ReturnQuantity); } public long CurrentTimeMillis() { return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds; } // 取消按钮 public DelegateCommand CancleTake { get => new DelegateCommand(() => { IsFinishClick = false; _portUtil.ResetData(); Status = 0; }); } //检查是否是冰箱抽屉(冰箱抽屉打开时需要发送冰箱延迟报警的指令) public async Task CheckIsFridgeOpen() { if (ChannelStocks != null && ChannelStocks.Count > 0) { if (_portUtil.BoardType == (Int32)BoardTypeEnum.fridge) { _portUtil.FridgeOperate = true; //发送冰箱延迟报警的指令 await _portUtil.FridgeDelayWarm(); _portUtil.FridgeOperate = false; } } } //检查是否是冰箱抽屉(冰箱抽屉关闭时需要查询冰箱温度如温度不在范围则发送冰箱延迟报警的指令) public async Task CheckIsFridgeClose() { if (ChannelStocks != null && ChannelStocks.Count > 0) { if (_portUtil.BoardType == (Int32)BoardTypeEnum.fridge) { string[] iTempertureRange = ConfigurationManager.AppSettings["temperatureRange"].Split('-'); //发送查询冰箱温度的指令 float temperature = await _portUtil.GetFridgeTemperature(); if (temperature > Convert.ToSingle(iTempertureRange[0]) && temperature < Convert.ToSingle(iTempertureRange[1])) { _portUtil.FridgeOperate = true; //发送冰箱延迟报警的指令 await _portUtil.FridgeDelayWarm(); _portUtil.FridgeOperate = false; } } } } public DelegateCommand BtnCloseCommand { get => new DelegateCommand(() => { // 关闭当前窗口 RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel)); }, () => Status == 0).ObservesProperty(() => Status); } public bool KeepAlive => false; } }