using DM_Weight.Common; using DM_Weight.Models; using DM_Weight.msg; using DM_Weight.Port; using DM_Weight.select; using DM_Weight.util; using log4net; using log4net.Repository.Hierarchy; 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.Configuration; using System.Drawing.Printing; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace DM_Weight.ViewModels { public class ReturnWithOrderWindowViewModel : BindableBase, IConfirmNavigationRequest, IRegionMemberLifetime { private int _pageNum = 1; public int PageNum { get => _pageNum; set { SetProperty(ref _pageNum, value); RequestData(); } } private int _pageCount = 1; public int PageCount { get => _pageCount; set { SetProperty(ref _pageCount, value); } } private int _pageSize = 8; public int PageSize { get => _pageSize; set { SetProperty(ref _pageSize, value); } } private int _totalCount = 0; public int TotalCount { get => _totalCount; set { SetProperty(ref _totalCount, value); } } public static List StaticOrderTakeSelects = new() { new OrderTakeSelect { Code = "OrderNo", Name = "处方号" }, new OrderTakeSelect { Code = "PatientId", Name = "患者编号" } }; private List _orderTakeSelects = StaticOrderTakeSelects; public List OrderTakeSelects { get { return _orderTakeSelects; } set { SetProperty(ref _orderTakeSelects, value); } } private OrderTakeSelect _selectedItem = StaticOrderTakeSelects[0]; /// /// 查询条件 查询字段 /// public OrderTakeSelect SelectedItem { get { return _selectedItem; } set { SetProperty(ref _selectedItem, value); RequestData(); } } private OrderInfo? _selectedOrder; public OrderInfo? SelectedOrder { get { return _selectedOrder; } set { SetProperty(ref _selectedOrder, value); //OpenOrderDialog(); } } private List _orderInfos = new(); public List OrderInfos { get { return _orderInfos; } set { SetProperty(ref _orderInfos, value); } } private string _orderDate = DateTime.Now.ToString("yyyy-MM-dd"); /// /// 查询条件 处方日期 /// public string OrderDate { get { return _orderDate; } set { if (!String.IsNullOrEmpty(value)) { SetProperty(ref _orderDate, DateTime.Parse(value).ToString("yyyy-MM-dd")); } else { SetProperty(ref _orderDate, value); } RequestData(); } } private string? _searchValue; /// /// 查询条件 查询字段值 /// public string? SearchValue { get { return _searchValue; } set { SetProperty(ref _searchValue, value); RequestData(); } } /// /// 取药日期 /// private string _optDate; public string OptDate { get { return _optDate; } set { if (!String.IsNullOrEmpty(value)) { SetProperty(ref _optDate, DateTime.Parse(value).ToString("yyyy-MM-dd")); } else { SetProperty(ref _optDate, value); } BindDrugInfo(); } } private int _status = 0; public int Status { get => _status; set => SetProperty(ref _status, value); } private string _detailDrugName; public string DetailDrugName { get => _detailDrugName; set => SetProperty(ref _detailDrugName, value); } private string _detailDrugSpec; public string DetailDrugSpec { get => _detailDrugSpec; set => SetProperty(ref _detailDrugSpec, value); } private string _detailDrugFactory; public string DetailDrugFactory { get => _detailDrugFactory; set => SetProperty(ref _detailDrugFactory, value); } private MachineRecord _machineRecord; public MachineRecord _MachineRecord { get => _machineRecord; set { SetProperty(ref _machineRecord, value); } } private ChannelList? _channelLsts; public ChannelList? ChannelLsts { get => _channelLsts; set => SetProperty(ref _channelLsts, value); } private List __channelStocks = new List(); public List ChannelStocks { get => __channelStocks; set => SetProperty(ref __channelStocks, value); } //回收箱库位 public ChannelStock? CStock; private List? _machineRecords; public List? MachineRecords { get => _machineRecords; set => SetProperty(ref _machineRecords, value); } private List? _ordertails; public List? OrderDetails { get => _ordertails; set => SetProperty(ref _ordertails, value); } /// /// 取药人列表 /// private List? _userLists = new() { new UserList() { UserName = "全部", Id = 0 } }; public List? UserLists { get => _userLists; set => SetProperty(ref _userLists, value); } /// /// 选中取药人 /// private UserList? _userSelects = new UserList(); public UserList? UserSelects { get => _userSelects; set { SetProperty(ref _userSelects, value); BindDrugInfo(); } } private string WindowName = "ReturnWithOrderWindow"; private readonly ILog logger = LogManager.GetLogger(typeof(ReturnWithOrderWindowViewModel)); private bool _isFinishClick = false; private static readonly DateTime Jan1st1970 = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); private IEnumerable> enumerable; private IEnumerator> enumerator; public bool IsFinishClick { get => _isFinishClick; set => SetProperty(ref _isFinishClick, value); } IDialogService _dialogService; private PortUtil _portUtil; IEventAggregator _eventAggregator; public ReturnWithOrderWindowViewModel(IDialogService dialogService, PortUtil portUtil, IEventAggregator eventAggregator) { _dialogService = dialogService; _portUtil = portUtil; _eventAggregator = eventAggregator; } public DelegateCommand RowSelected { get => new DelegateCommand(() => { BindDrugInfo(); }); } private void DoDialogResult(IDialogResult dialogResult) { //dialogResult 第一方面可以拿到任意参数 第二方面 可判断关闭状态 //if (dialogResult.Result == ButtonResult.OK) //{ // MachineRecords.ForEach(mr => mr.ManuNo = "123"); // _MachineRecord = dialogResult.Parameters.GetValue("MachineRecord"); //} // 委托 被动执行 被子窗口执行 // dialogResult 第一方面可以拿到任意参数 第二方面 可判断关闭状态 RequestData(); } public bool KeepAlive => false; public void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback) { continuationCallback(true); } public bool IsNavigationTarget(NavigationContext navigationContext) { return true; } /// /// 还空瓶按钮--打开抽屉 /// public DelegateCommand OpenDrawer { get => new DelegateCommand(() => { if (Status == 0) { if (OrderDetails != null && OrderDetails.Count > 0) { List records = OrderDetails[0].MachineRecords.Where(rd => rd.CurrentReturn > 0).ToList(); if (records != null && records.Count > 0) { CStock = SqlSugarHelper.Db.Queryable() .Where(c => c.DrawerType != 1 && c.DrugId == records[0].DrugId && c.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1")).First(); if (CStock != null) { Status = 1; _portUtil.SpeakAsync("正在打开" + CStock.DrawerNo + "号抽屉"); _portUtil.WindowName = "ReturnWithOrderWindow"; _portUtil.Operate = true; _portUtil.BoardType = CStock.BoardType; _portUtil.ColNos = new int[] { };// singleChannels.Select(it => it.ColNo).ToArray(); _portUtil.DrawerNo = CStock.DrawerNo; _portUtil.Start(); } else { //药品未绑定回收药箱 AlertMsg alertMsg = new AlertMsg { Message = "药品未绑定回收药箱", Type = MsgType.ERROR, }; _eventAggregator.GetEvent().Publish(alertMsg); } } else { //未输入还空瓶数量 AlertMsg alertMsg = new AlertMsg { Message = "没有与之对应的取药记录或没有填写空瓶数量", Type = MsgType.ERROR, }; _eventAggregator.GetEvent().Publish(alertMsg); } } else { AlertMsg alert = new AlertMsg { Message = "该处方下无药品明细", Type = MsgType.ERROR }; _eventAggregator.GetEvent().Publish(alert); } } }); } // 完成按钮 public DelegateCommand SaveCommand { get => new DelegateCommand(() => { if (!_isFinishClick) { _isFinishClick = true; var f = SqlSugarHelper.Db.UseTran(() => { //0)检查处方中药品数量是否与还空瓶数量相等 if (OrderDetails != null && OrderDetails.Count > 0) { if (OrderDetails[0].Quantity != OrderDetails.Sum(it => it.MachineRecords.Sum(m => m.CurrentReturn))) { AlertMsg alert = new AlertMsg { Message = "处方用药数量与还空瓶数量不一致", Type = MsgType.ERROR }; _eventAggregator.GetEvent().Publish(alert); return false; } } if (OrderDetails[0].MachineRecords != null && OrderDetails[0].MachineRecords.Count > 0) { List recordList = OrderDetails[0].MachineRecords.Where(mr=>mr.CanReturnQuantity>0).ToList(); for (int i = 0; i < recordList.Count; i++) { if (recordList[i].CanReturnQuantity < recordList[i].CurrentReturn) { AlertMsg alert = new AlertMsg { Message = "还空瓶数量不能大于可还空瓶数量", Type = MsgType.ERROR }; _eventAggregator.GetEvent().Publish(alert); break; } //1) 写一条还空瓶记录 SqlSugarHelper.Db.Insertable(new MachineRecord() { MachineId = recordList[i].MachineId, DrawerNo = CStock.DrawerNo, ColNo = CStock.ColNo, DrugId = recordList[i].DrugId, ManuNo = recordList[i].ManuNo, EffDate = recordList[i].EffDate.HasValue ? recordList[i].EffDate.Value.Date : null, Operator = HomeWindowViewModel.Operator?.Id, Reviewer = HomeWindowViewModel.Reviewer?.Id, OperationTime = DateTime.Now, Quantity = recordList[i].CurrentReturn, Type = 32, InvoiceId = OrderDetails[0].OrderNo, GetId = recordList[i].Id, StockQuantity = recordList[i].ReturnQuantity2 }).ExecuteCommand(); //2)更改当前取药记录的状态 SqlSugarHelper.Db.Updateable(new MachineRecord() { ReturnQuantity2 = recordList[i].CurrentReturn + recordList[i].ReturnQuantity2, Id = recordList[i].Id, Status = recordList[i].ReturnQuantity2 + recordList[i].ReturnQuantity1+ recordList[i].CurrentReturn == recordList[i].Quantity ? 2 : 1, }).UpdateColumns(it => new { it.ReturnQuantity2, it.Status }).ExecuteCommand(); ////3)写hkc_order_finished数据供his反查 //SqlSugarHelper.Db.Insertable(new OrderFinish() //{ // OrderNo = OrderDetails[0].OrderNo, // PatientId = SelectedOrder.PatientId, // Pharmacy = SelectedOrder.Pharmacy, // State = 1, // Operator = HomeWindowViewModel.Operator?.Nickname, // DrugId = OrderDetails[0].DrugId, // Quantity = recordList[i].CurrentReturn, // //ManuNo = recordList[i].ManuNo.ToString(), // //EffDate =recordList[i].EffDate.HasValue ? recordList[i].EffDate.Value.ToString("yyyy-MM-dd") : null, //}).ExecuteCommand(); } //4)加回收箱的库存数 if (CStock != null) { CStock.Quantity = CStock.Quantity + OrderDetails[0].MachineRecords.Sum(m => m.CurrentReturn); SqlSugarHelper.Db.Updateable(CStock).ExecuteCommand(); } //5) 更新处方状态 SqlSugarHelper.Db.Updateable(new OrderInfo() { DmStatus = 1, OrderNo = OrderDetails[0].OrderNo }).UpdateColumns(it => new { it.DmStatus }).WhereColumns(it => new { it.OrderNo }).ExecuteCommand(); } return true; }); if (f.Data) { 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; } RequestData(); }); } public long CurrentTimeMillis() { return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds; } // 取消按钮 public DelegateCommand CancleTake { get => new DelegateCommand(() => { IsFinishClick = false; _portUtil.ResetData(); Status = 0; }); } 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) { //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($"抽屉【{CStock.DrawerNo}】库位还空瓶数量【{msg.Quantitys}】"); //channelStocks.ForEach(it => it.ReturnQuantity = msg.Quantitys[it.ColNo - 1]); } break; // 打开失败 case EventType.OPENERROR: AlertMsg alertMsg = new AlertMsg { Message = msg.Message, Type = MsgType.ERROR, }; _eventAggregator.GetEvent().Publish(alertMsg); Status = 0; break; } } } public void OnNavigatedFrom(NavigationContext navigationContext) { // 取消消息订阅 _eventAggregator.GetEvent().Unsubscribe(DoMyPrismEvent); } public void OnNavigatedTo(NavigationContext navigationContext) { //查询表格数据 RequestData(); BindUserList(); _eventAggregator.GetEvent().Subscribe(DoMyPrismEvent); } private void RequestData() { OrderInfos.Clear(); int totalCount = 0; List queryData = SqlSugarHelper.Db.Queryable() .InnerJoin((oi, od) => oi.OrderNo == od.OrderNo) // .InnerJoin(SqlSugarHelper.Db.Queryable().Where(cs => cs.DrawerType == 1).Where(cs => cs.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1")).GroupBy(cs => cs.DrugId), (oi, od, t) => od.DrugId == t.DrugId) .WhereIF(OrderDate != null, oi => oi.RecvDate.ToString("yyyy-MM-dd") == OrderDate) .WhereIF(!String.IsNullOrEmpty(SearchValue) && SelectedItem.Code.Equals("OrderNo"), oi => oi.OrderNo == SearchValue) .WhereIF(!String.IsNullOrEmpty(SearchValue) && SelectedItem.Code.Equals("PatientId"), oi => oi.PatientId == SearchValue) .WhereIF(!String.IsNullOrEmpty(ConfigurationManager.AppSettings["storage"]), oi => oi.Pharmacy == ConfigurationManager.AppSettings["storage"]) .Where(oi => oi.DmStatus == 0) .Where(oi => oi.HisDispFlag == 0) .Where(oi => oi.CancelFlag == 0) .GroupBy(oi => oi.ChargeDate) .Select(oi => new OrderInfo() { PatientId= oi.PatientId, IdNumber = oi.IdNumber, PName=oi.PName, Sex=oi.Sex, ChargeDate=oi.ChargeDate, OrderNo = oi.OrderNo, orderDetail =SqlFunc.Subqueryable().Where(od => od.OrderNo == oi.OrderNo).First(), }) .ToPageList(PageNum, PageSize, ref totalCount); OrderInfos = queryData; TotalCount = totalCount; PageCount = (int)Math.Ceiling((double)TotalCount / PageSize); } private void BindUserList() { UserLists = SqlSugarHelper.Db.Queryable().Distinct() .InnerJoin((ul, mr) => ul.Id == mr.Operator) .Where(ul => ul.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1")) .Where((ul, mr) => mr.Type == 2 && mr.Status != 2 && mr.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1")) .ToList(); } private void BindDrugInfo() { if (SelectedOrder != null) { OrderDetails = SqlSugarHelper.Db.Queryable() .Includes(cl => cl.DrugInfo, di => di.DrugManuNos) .Where(od => od.OrderNo == SelectedOrder.OrderNo).ToList(); if (OrderDetails != null && OrderDetails.Count > 0) { for (int i = 0; i < OrderDetails.Count; i++) { List machineRecords = new List(); machineRecords = SqlSugarHelper.Db.Queryable() .Where(mr => mr.DrugId == OrderDetails[i].DrugId && mr.Type == 2 && mr.Status != 2 && mr.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1")) .WhereIF(!String.IsNullOrEmpty(OptDate), mr => mr.OperationTime.ToString("yyyy-MM-dd") == OptDate) .WhereIF(!String.IsNullOrEmpty(UserSelects.UserName), mr => mr.Reviewer == UserSelects.Id) .WhereIF(String.IsNullOrEmpty(UserSelects.UserName) && HomeWindowViewModel.Reviewer != null, mr => mr.Reviewer == HomeWindowViewModel.Reviewer.Id) .ToList(); if (machineRecords != null && machineRecords.Count > 0) { machineRecords.ForEach(mr => { mr.DrugInfo = OrderDetails[i].DrugInfo; mr.drugManuNo = OrderDetails[i].DrugInfo.DrugManuNos.Find(it => it.ManuNo.Equals(mr.ManuNo)); }); //处方中取药数量大于第一个取药的可还空瓶数,需要将处方中数据平均分配到取药列表中的还空瓶数量中 if (OrderDetails[i].Quantity > machineRecords[0].CanReturnQuantity) { int orderQuantity = OrderDetails[i].Quantity; for (int j = 0; j < machineRecords.Count; j++) { if (orderQuantity > machineRecords[j].CanReturnQuantity) { machineRecords[j].CurrentReturn = machineRecords[j].CanReturnQuantity; orderQuantity = orderQuantity - machineRecords[j].CanReturnQuantity; } else { machineRecords[j].CurrentReturn = orderQuantity; break; } } } else { machineRecords[0].CurrentReturn = OrderDetails[i].Quantity; } } OrderDetails[i].MachineRecords = machineRecords; } } //ChannelList queryData = SqlSugarHelper.Db.Queryable() // .Includes(cl => cl.Drug, di => di.DrugManuNos) // .Includes(cl => cl.channelStocks, dr => dr.DrugInfo, d => d.DrugManuNos) // .Where(cl => cl.DrawerType == 2&&cl.DrugId== od.DrugId) // .Where(cl => cl.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1")).First(); //queryData.channelStocks = queryData.channelStocks.Select(cs => { // cs.drugManuNo = queryData.Drug.DrugManuNos.Find(it => it.ManuNo.Equals(cs.ManuNo)); // return cs; //}).ToList(); //ChannelLsts = queryData; //if (Ordetails != null) //{ // DetailDrugName = Ordetails[0].DrugInfo.DrugName; // DetailDrugSpec = Ordetails[0].DrugInfo.DrugSpec; // DetailDrugFactory = Ordetails[0].DrugInfo.Manufactory; //} //ChannelLsts.channelStocks.ForEach(cs => cs.DrugInfo = ChannelLsts.Drug); } else { OrderDetails = null; } } } }