using DM_Weight.Models; using DM_Weight.msg; using DM_Weight.Port; using DM_Weight.util; using log4net; using Prism.Commands; using Prism.Events; using Prism.Mvvm; using Prism.Regions; using Prism.Services.Dialogs; using SqlSugar; using SqlSugar.Extensions; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Configuration; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; namespace DM_Weight.ViewModels { public class MultiOrderTakeDialogViewModel : BindableBase, IDialogAware, IRegionMemberLifetime { private readonly ILog logger = LogManager.GetLogger(typeof(MultiOrderTakeDialogViewModel)); public string Title => "多处方取药"; public event Action RequestClose; private static readonly DateTime Jan1st1970 = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); //取药人(科室) private string receivePerson; public string ReceivePerson { get => receivePerson; set => SetProperty(ref receivePerson, value); } private PortUtil _portUtil; IEventAggregator _eventAggregator; IDialogService _dialogService; public MultiOrderTakeDialogViewModel(PortUtil portUtil, IEventAggregator eventAggregator, IDialogService DialogService) { _dialogService = DialogService; _portUtil = portUtil; _eventAggregator = eventAggregator; } void DoMyPrismEvent(DeviceMsg msg) { if (msg.WindowName == "OrderTakeDrugWindow") { 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); } } 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; } } 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; } } } private int _status = 0; public int Status { get => _status; set => SetProperty(ref _status, value); } //多处方的处方号 private string _multiOrderNo = "处方号:"; public string MultiOrderNo { get => _multiOrderNo; set => SetProperty(ref _multiOrderNo, value); } private ObservableCollection? _orderInfo; public ObservableCollection? OrderInfo { get => _orderInfo; set => SetProperty(ref _orderInfo, value); } private List orderDetails { get; set; } private List _channelStocks; public List ChannelStocks { get => _channelStocks; set => SetProperty(ref _channelStocks, value); } private IEnumerable> enumerable; private IEnumerator> enumerator; public bool CanCloseDialog() { return Status == 0; } public void OnDialogClosed() { // 取消消息订阅 _eventAggregator.GetEvent().Unsubscribe(DoMyPrismEvent); } public void OnDialogOpened(IDialogParameters parameters) { logger.Info("进入MultiOrderTakeDialogViewModel_查询数据"); _eventAggregator.GetEvent().Subscribe(DoMyPrismEvent); OrderInfo = parameters.GetValue>("orderInfo"); MultiOrderNo += string.Join(", ", OrderInfo.Select(o => o.OrderNo)).Length > 60 ? string.Join(", ", OrderInfo.Select(o => o.OrderNo)).Substring(0, 60) + "……" : string.Join(", ", OrderInfo.Select(o => o.OrderNo)); RequestData(); logger.Info($"结束MultiOrderTakeDialogViewModel_查询数据,处理处方{MultiOrderNo}"); } public async void RequestData() { orderDetails = SqlSugarHelper.Db.Queryable() //.Includes(od => od.DrugInfo) .InnerJoin(SqlSugarHelper.Db.Queryable() .Where(cs => cs.DrawerType == 1) .Where(cs => cs.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1")) .GroupBy(cs => cs.DrugId), (od, t) => od.DrugId == t.DrugId) .Where(od => OrderInfo.Select(o => o.OrderNo).Contains(od.OrderNo)).GroupBy(od => od.DrugId) .Select(od => new OrderDetail { DrugId = od.DrugId, SetEffDate = od.SetEffDate, SetManuNo = od.SetManuNo, Quantity = SqlFunc.AggregateSum(od.Quantity) }) //.Where(od => od.OrderNo. OrderInfo.OrderNo) .ToList(); List channelStocks = new List(); List msg = new List(); for (int i = 0; i < orderDetails.Count; i++) { OrderDetail orderDetail = orderDetails[i]; List HasQChannels = SqlSugarHelper.Db.Queryable() .Includes(cs => cs.DrugInfo) .Where(cs => cs.Quantity > 0) .Where(cs => cs.DrawerType == 1) .Where(cs => cs.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1")) .WhereIF(!string.IsNullOrEmpty(orderDetail.SetEffDate), cs => cs.EffDate.Equals(orderDetail.SetEffDate)) .WhereIF(!string.IsNullOrEmpty(orderDetail.SetManuNo), cs => cs.ManuNo.Equals(orderDetail.SetManuNo)) .Where(cs => cs.DrugId == orderDetail.DrugId) .WhereIF(App.SingleModel, cs => cs.DrawerNo <= 2) //单人登录开前2个抽屉,双人登录开后14个抽屉 .WhereIF(!(App.SingleModel), cs => cs.DrawerNo > 2) .OrderBy(cs => cs.EffDate) //.OrderBy(cs => cs.DrawerNo) //.OrderBy(cs => cs.ManuNo) .OrderBy(cs=>cs.FillTime) .ToList(); int total = HasQChannels.Sum(it => it.Quantity); int TakeQ = orderDetail.Quantity; int multiTakeQ = orderDetail.Quantity; List multiTake = new List(); //multiTakeQ = orderDetails.Where(c => c.DrugId == orderDetail.DrugId).Sum(c => c.Quantity); // 说明数量足够 if (total >= multiTakeQ) { for (int j = 0; TakeQ > 0; j++) { ChannelStock stock = HasQChannels[j]; if (TakeQ > stock.Quantity) { //#region 存在该库存且库存数量大于待取数量则把取药数量加上 //var varChannelStock = channelStocks.Where(c => c.Location == stock.Location && c.Quantity > c.TakeQuantity + TakeQ).ToList(); //if (varChannelStock != null && varChannelStock.Count > 0) //{ // channelStocks.Where(c => c.Location == stock.Location).Select(c => c.TakeQuantity += TakeQ).ToList(); // break; //} //#endregion stock.TakeQuantity = stock.Quantity; channelStocks.Add(stock); TakeQ -= stock.Quantity; } else { //#region 存在该库存且库存数量大于待取数量则把取药数量加上 //var varChannelStock = channelStocks.Where(c => c.Location == stock.Location && c.Quantity > c.TakeQuantity + TakeQ).ToList(); //if (varChannelStock != null && varChannelStock.Count > 0) //{ // channelStocks.Where(c => c.Location == stock.Location).Select(c => c.TakeQuantity += TakeQ).ToList(); // break; //} //#endregion stock.TakeQuantity = TakeQ; channelStocks.Add(stock); TakeQ = 0; } } } else { if (HasQChannels != null && HasQChannels.Count > 0 && HasQChannels[0].DrugInfo != null) { //msg.Add($"药品【{orderDetail.DrugInfo.DrugName}】库存不足,应取【{TakeQ}】库存【{total}】"); msg.Add($"药品【{HasQChannels[0].DrugInfo.DrugName}】库存不足,应取【{TakeQ}】库存【{total}】"); } else { msg.Add($"药品【{orderDetail.DrugId}】库存不足,应取【{TakeQ}】库存【{total}】"); } } } if (msg.Count > 0) { RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel)); //MessageBox.Show(string.Join("\n", msg)); DialogParameters dialogParameters = new DialogParameters(); dialogParameters.Add("msgInfo", msg); DialogServiceExtensions.ShowDialogHost(_dialogService, "ShowMessageDialog", dialogParameters, "RootDialog"); } else { channelStocks.Sort((a, b) => { if ((a.DrawerNo - b.DrawerNo) == 0) { return a.ColNo - b.ColNo; } return a.DrawerNo - b.DrawerNo; }); ChannelStocks = channelStocks; } } public DelegateCommand OpenDrawer { get => new DelegateCommand(async () => { if (Status == 0) { enumerable = ChannelStocks.GroupBy(cs => cs.DrawerNo, cs => cs); enumerator = enumerable.GetEnumerator(); enumerator.MoveNext(); Status = 1; OpenOneByOne(); } }); } private void OpenOneByOne() { IGrouping grouping = enumerator.Current; int DrawerNo = grouping.Key; List channelStocks = grouping.ToList(); channelStocks.ForEach(it => it.process = 1); _portUtil.SpeakAsync("正在打开" + DrawerNo + "号抽屉"); List singleChannels = channelStocks.FindAll(it => it.BoardType != 1); // 发送取药数量 singleChannels.ForEach(it => { try { _portUtil.TakeQuantity(DrawerNo, it.ColNo, it.TakeQuantity, it.Quantity - it.TakeQuantity); } catch (Exception ex) { AlertMsg alertMsg = new AlertMsg { Message = $"打开抽屉异常{ex.Message}", Type = MsgType.ERROR, }; _eventAggregator.GetEvent().Publish(alertMsg); } }); _portUtil.WindowName = "OrderTakeDrugWindow"; _portUtil.BoardType = singleChannels.Count > 0 ? singleChannels[0].BoardType : 1; _portUtil.ColNos = singleChannels.Select(it => it.ColNo).ToArray(); _portUtil.DrawerNo = DrawerNo; _portUtil.Start(); } private bool _isFinishClick = false; // 完成按钮 public DelegateCommand TakeFinish { get => new DelegateCommand(() => { if (!_isFinishClick) { _isFinishClick = true; List record = ChannelStocks.FindAll(it => it.TakeQuantity > 0).ToList(); //根据处方单数量分别更新处方状态、写记录信息 if (OrderInfo != null && OrderInfo.Count > 0) { UpdateOrderInfo(OrderInfo, record); } } }); } private void UpdateOrderInfo(ObservableCollection orderInfo, List record) { var f = SqlSugarHelper.Db.UseTran(() => { logger.Info("UseTran"); for (int j = 0; j < OrderInfo.Count; j++) { logger.Info($"OrderInfo j-{j}"); string InvoiceId = OrderInfo[j].OrderNo; for (int i = 0; i < record.Count; i++) { logger.Info($"record j-{i}"); List orderDetails = SqlSugarHelper.Db.Queryable() .Where(od => od.OrderNo == OrderInfo[j].OrderNo && od.DrugId == record[i].DrugId && od.DetailStatus == 0).ToList(); if (orderDetails == null || orderDetails.Count <= 0) { logger.Info($"处方{OrderInfo[j].OrderNo}下无药品{record[i].DrugId},或detail_status字段不为 0"); continue; } logger.Info($"orderDetails"); OrderDetail orderDetail = orderDetails.FirstOrDefault(); orderDetail.Quantity = orderDetails.Sum(it => it.Quantity); //处方中该药品明细 //OrderDetail orderDetail = SqlSugarHelper.Db.Queryable() // .Where(od => od.OrderNo == OrderInfo[j].OrderNo && od.DrugId == record[i].DrugId && od.DetailStatus == 0) // .GroupBy(od => new { od.DrugId, od.OrderId }).Select(od => new OrderDetail // { // OrderId = od.OrderId, // DrugId = od.DrugId, // Quantity = SqlFunc.AggregateSum(od.Quantity) // }).First(); int ordinalNum = SqlSugarHelper.Db.Queryable() .Where(mr => mr.OperationTime.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd")) .Max(mr => mr.OrdinalNum); logger.Info($"ordinalNum{ordinalNum}"); //已取药数量 int hasTakeQuantity = SqlSugarHelper.Db.Queryable() .Where(mr => mr.InvoiceId == InvoiceId && mr.DrugId == record[i].DrugId && mr.GetId == orderDetail.OrderId) .Sum(mr => mr.Quantity); //处方中该药品取药数量 int orderTakeQuantity = orderDetail.Quantity - hasTakeQuantity; logger.Info($"orderTakeQuantity{orderTakeQuantity}"); //当前药品库存 int stockQuantity = SqlSugarHelper.Db.Queryable() .Where(cs => cs.MachineId == (record[i].MachineId) && cs.DrugId == record[i].DrugId && cs.ManuNo == record[i].ManuNo && cs.DrawerNo == record[i].DrawerNo && cs.ColNo == record[i].ColNo).Select(cs => cs.Quantity).First(); logger.Info($"stockQuantity{stockQuantity}"); //该处方没有这个药,跳出循环 if (stockQuantity <= 0 || orderTakeQuantity <= 0) continue; if (!(stockQuantity == orderTakeQuantity)) { if (stockQuantity > orderTakeQuantity) { //record[i].TakeQuantity = record[i].TakeQuantity - orderTakeQuantity; record[i].TakeQuantity = orderTakeQuantity; record[i].Quantity = stockQuantity - orderTakeQuantity; } else if (stockQuantity < orderTakeQuantity) { record[i].TakeQuantity = stockQuantity; record[i].Quantity = 0; } } else { record[i].TakeQuantity = orderTakeQuantity; record[i].Quantity = stockQuantity - record[i].TakeQuantity; } logger.Info($"record{stockQuantity}"); ChannelStock it = record[i]; // 更新数据 库存信息 SqlSugarHelper.Db.Updateable(new ChannelStock() { Quantity = record[i].Quantity, ManuNo = it.ManuNo, EffDate = it.EffDate, Id = it.Id, }).UpdateColumns(it => new { it.Quantity, it.ManuNo, it.EffDate }).ExecuteCommand(); logger.Info("更新数据 库存信息"); // 获取更新完库存后的药品库存 List nowChannels = SqlSugarHelper.Db.Queryable() .Where(cs => cs.MachineId.Equals(it.MachineId)) .Where(cs => cs.DrugId.Equals(it.DrugId)) .Where(cs => cs.DrawerType == 1) .ToList(); logger.Info("查询当前库存"); // 保存数据 出库记录 SqlSugarHelper.Db.Insertable(new MachineRecord() { MachineId = it.MachineId, DrawerNo = it.DrawerNo, ColNo = it.ColNo, DrugId = it.DrugId, ManuNo = it.ManuNo, EffDate = !String.IsNullOrEmpty(it.EffDate) ? DateTime.ParseExact(it.EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null, Operator = HomeWindowViewModel.Operator?.Id, Reviewer = HomeWindowViewModel.Reviewer?.Id, OperationTime = DateTime.Now, Quantity = orderDetail.Quantity,//record[i].TakeQuantity, Type = 2, InvoiceId = InvoiceId, OrdinalNum = ordinalNum + 1, StockQuantity = nowChannels.Sum(it => it.Quantity), ManunoQuantity = nowChannels.FindAll(it2 => it2.ManuNo == it.ManuNo).Sum(it => it.Quantity), SupplierDept = ConfigurationManager.AppSettings["receiveDept"].ToString(), ReceiveDept = OrderInfo[j].DeptName, GetId = orderDetail.OrderId, ReceivePerson= ReceivePerson }).ExecuteCommand(); logger.Info("Insertable MachineRecord"); } //更新处方状态 SqlSugarHelper.Db.Updateable(new OrderInfo() { DmStatus = 1, OrderNo = OrderInfo[j].OrderNo }).UpdateColumns(it => new { it.DmStatus }).WhereColumns(it => new { it.OrderNo }).ExecuteCommand(); logger.Info("更新处方"); //更新处方明细状态为已取药1 List orderDetailLst = SqlSugarHelper.Db.Queryable().Where(od => od.OrderNo == OrderInfo[j].OrderNo && od.DetailStatus == 0).ToList(); if (orderDetailLst != null && orderDetailLst.Count > 0) { orderDetailLst.ForEach(od => od.DetailStatus = 1); SqlSugarHelper.Db.Updateable(orderDetailLst).UpdateColumns(it => new { it.DetailStatus }).ExecuteCommand(); } else { logger.Info($"处方{OrderInfo[j].OrderNo}药品明细状态未更新"); } logger.Info("处方明细状态为已取药1"); } return true; }); if (f.Data) { logger.Info("f.Data"); //}); // 更新屏显库存 List singleChannels = record.FindAll(it => it.BoardType == 5); if (singleChannels.Count > 0) { for (int i = 0; i < singleChannels.Count; i++) { List csList = SqlSugarHelper.Db.Queryable() .Where(cs => cs.MachineId == singleChannels[i].MachineId) .Where(cs => cs.DrawerNo == singleChannels[i].DrawerNo) .Where(cs => cs.ColNo == singleChannels[i].ColNo && cs.Quantity > 0).OrderBy(cs => cs.EffDate).ToList(); if (csList != null && csList.Count > 0) { int totalQuantity = csList.Sum(c => c.Quantity); _portUtil.WriteChannelInfo(5, csList[0].EffDate == null ? "" : csList[0].EffDate, csList[0].DrawerNo, csList[0].ColNo); Thread.Sleep(200); _portUtil.WriteChannelInfo(6, csList[0].ManuNo == null ? "" : csList[0].ManuNo, csList[0].DrawerNo, csList[0].ColNo); Thread.Sleep(200); _portUtil.ShowContent(csList[0].DrawerNo, csList[0].ColNo); Thread.Sleep(200); _portUtil.WriteQuantity(csList[0].DrawerNo, csList[0].ColNo, totalQuantity); Thread.Sleep(200); } // singleChannels.ForEach(it => //{ // _portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.Quantity - it.TakeQuantity); // Thread.Sleep(200); //}); } } AlertMsg alertMsg = new AlertMsg { Message = "抽屉取药完成,库存已更新", Type = MsgType.SUCCESS, }; _eventAggregator.GetEvent().Publish(alertMsg); } if (!f.IsSuccess) { System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() => { AlertMsg alertMsg = new AlertMsg { Message = "抽屉取药完成,库存更新失败!", Type = MsgType.ERROR, }; _eventAggregator.GetEvent().Publish(alertMsg); })); } Status = 0; _isFinishClick = false; //RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel)); RequestClose?.Invoke(new DialogResult(ButtonResult.OK)); } public long CurrentTimeMillis() { return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds; } // 取消按钮 public DelegateCommand CancleTake { get => new DelegateCommand(() => { _portUtil.ResetData(); Status = 0; }); } public DelegateCommand BtnCloseCommand { get => new DelegateCommand(() => { if (Status != 0) { _portUtil.ResetData(); Status = 0; } //DialogParameters parameters = new DialogParameters(); //parameters.Add("",); // 关闭当前窗口 RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel)); }); } public bool KeepAlive => false; } }