HuNan_DM/DM_Weight/ViewModels/AddDrugControlViewModel.cs

632 lines
27 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Drawing.Printing;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Documents;
namespace DM_Weight.ViewModels
{
public class AddDrugControlViewModel : BindableBase, IConfirmNavigationRequest, IRegionMemberLifetime
{
public static List<UseFor> SelectUseList = new()
{
new UseFor { UseId = 96, UseName = "不入账册" },
new UseFor{UseId=0,UseName="入账册"}
};
private List<UseFor> _selects = SelectUseList;
public List<UseFor> Selects
{
get { return _selects; }
set
{
SetProperty(ref _selects, value);
}
}
private UseFor _selectedItem = SelectUseList[0];
/// <summary>
/// 取药或加药用途字段
/// </summary>
public UseFor SelectedItem
{
get { return _selectedItem; }
set
{
SetProperty(ref _selectedItem, value);
}
}
private readonly ILog logger = LogManager.GetLogger(typeof(AddDrugControlViewModel));
private List<int> _drawerNoList = new List<int>();
public static AddDrugControlViewModel vm;
//凭证号
private string _pzh;
public string PZH { get => _pzh; set { SetProperty(ref _pzh, value); } }
private List<ChannelList>? _channelLsts;
public List<ChannelList>? ChannelLsts
{
get => _channelLsts;
set => SetProperty(ref _channelLsts, value);
}
private List<ChannelStock> __channelStocks = new List<ChannelStock>();
public List<ChannelStock> ChannelStocks
{
get => __channelStocks;
set => SetProperty(ref __channelStocks, value);
}
private ChannelStock? _channelStock;
public ChannelStock? CStock
{
get => _channelStock;
set => SetProperty(ref _channelStock, value);
}
//private ChannelList? _channelList;
//public ChannelList? ChannelLst
//{
// get => _channelList;
// set => SetProperty(ref _channelList, value);
//}
private static readonly DateTime Jan1st1970 = new DateTime
(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private PortUtil _portUtil;
IEventAggregator _eventAggregator;
IDialogService _dialogService;
////private SqlSugarScope SqlSugarHelper.Db;
public AddDrugControlViewModel(IDialogService DialogService, PortUtil portUtil, IEventAggregator eventAggregator)
{
_dialogService = DialogService;
_portUtil = portUtil;
_eventAggregator = eventAggregator;
////this.SqlSugarHelper.Db = sqlSugarScope;
vm = this;
}
public DelegateCommand SelectionChangedCommand => new DelegateCommand(selectionAction);
private async void selectionAction()
{
if (CStock != null)
{
// 此处延时1毫秒等待页面渲染
await Task.Delay(TimeSpan.FromMilliseconds(1));
DialogParameters dialogParameters = new DialogParameters();
dialogParameters.Add("addManuno", CStock);
DialogServiceExtensions.ShowDialogHost(_dialogService, "AddManunoDialog", dialogParameters, DoDialogResult, "RootDialog");
}
}
private void DoDialogResult(IDialogResult dialogResult)
{
// 委托 被动执行 被子窗口执行
// dialogResult 第一方面可以拿到任意参数 第二方面 可判断关闭状态
//if(dialogResult.Result == ButtonResult.OK)
//{
CStock = null;
RequestData();
//}
//MessageBox.Show("返回值:" + dialogResult.Result.ToString());
}
void DoMyPrismEvent(DeviceMsg msg)
{
if (msg.WindowName == "AddDrugControl")
{
switch (msg.EventType)
{
// 抽屉打开
case EventType.DRAWEROPEN:
if (Status == 1)
{
Status = 2;
}
break;
// 抽屉关闭
case EventType.DRAWERCLOSE:
if (Status == 2)
{
Status = 3;
}
break;
// 数量变化
case EventType.UPDATEQUANTITY:
if (Status == 2)
{
//ChannelStocks.ForEach(it => it.AddQuantity = msg.Quantitys[it.ColNo - 1]);
}
break;
// 打开失败
case EventType.OPENERROR:
AlertMsg alertMsg = new AlertMsg
{
Message = msg.Message,
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
Status = 0;
break;
}
}
}
private int _status;
public int Status { get => _status; set => SetProperty(ref _status, value); }
/// <summary>
/// 操作状态
/// </summary>
private int _OptionStatus = -1;
public int OptionStatus { get => _OptionStatus; set => SetProperty(ref _OptionStatus, value); }
/// <summary>
/// 完成按钮绑定文本(完成;保存中)
/// </summary>
private string _FinishContent = "完成";
public string FinishContent
{ get => _FinishContent; set => SetProperty(ref _FinishContent, value); }
private int _drawerNo = 1;
public int DrawerNo
{
get => _drawerNo;
set => SetProperty(ref _drawerNo, value);
}
private bool _is8Drawer = true;
public bool Is8Drawer { get => _is8Drawer; set => SetProperty(ref _is8Drawer, value); }
private bool _is16Drawer = false;
public bool Is16Drawer { get => _is16Drawer; set => SetProperty(ref _is16Drawer, value); }
private bool _is17Drawer = false;
public bool Is17Drawer { get => _is17Drawer; set => SetProperty(ref _is17Drawer, value); }
public DelegateCommand<string> UpdateDrawerNo
{
get => new DelegateCommand<string>((DrawerNo) =>
{
this.DrawerNo = Convert.ToInt32(DrawerNo);
RequestData();
}, (DrawerNo) => Status == 0
);
}
public DelegateCommand OpenDrawer
{
get => new DelegateCommand(() =>
{
Status = 1;
_portUtil.SpeakAsync("正在打开" + DrawerNo + "号抽屉");
try
{
//List<ChannelStock> singleChannels = ChannelStocks.FindAll(it => it.BoardType != 1);
List<ChannelList> singleChannels = ChannelLsts.FindAll(it => it.BoardType != 1);
_portUtil.WindowName = "AddDrugControl";
_portUtil.Operate = true;
_portUtil.BoardType = singleChannels.Count > 0 ? singleChannels[0].BoardType : 1;
_portUtil.ColNos = new int[] { };// singleChannels.Select(it => it.ColNo).ToArray();
//_portUtil.Stocks = singleChannels.Select(it => it.Quantity).ToArray();
_portUtil.DrawerNo = DrawerNo;
_portUtil.Start();
}
catch (Exception ex)
{
logger.Info($"OpenDrawer异常{ex.Message}");
}
}, () => Status == 0).ObservesProperty(() => Status);
}
private bool _isFinishClick = false;
// 完成按钮
public DelegateCommand TakeFinish
{
get => new DelegateCommand(TakeFinishAction);
}
private void TakeFinishAction()
{
OptionStatus = 4;
FinishContent = "保存中";
Task.Factory.StartNew(() => TakeFinishMethod());
}
private async void TakeFinishMethod()
{
try
{
logger.Info("开始保存数据");
if (!_isFinishClick)
{
_isFinishClick = true;
foreach (ChannelList lst in ChannelLsts)
{
lst.channelStocks.ForEach(it => it.DrugId = lst.DrugId);
ChannelStocks.AddRange(lst.channelStocks);
}
List<ChannelStock> record = ChannelStocks.FindAll(it => it.AddQuantity != 0).ToList();
if (record.Count > 0)
{
//string InvoiceId = "DRAWER_" + CurrentTimeMillis();
string InvoiceId = PZH;
//List<string> repeatList = new List<string>();
List<ChannelStock> stockRepeats = new List<ChannelStock>();
var f = SqlSugarHelper.Db.UseTran(() =>
{
for (int i = 0; i < record.Count; i++)
{
ChannelStock it = record[i];
it.ManuNo = it.drugManuNo.ManuNo;
it.EffDate = it.drugManuNo.EffDate;
if (it.Id != null)
{
// 更新数据 库存信息
SqlSugarHelper.Db.Updateable(new ChannelStock()
{
Quantity = it.Quantity + it.AddQuantity,
ManuNo = it.ManuNo,
EffDate = it.EffDate,
DrugId = it.DrugId,
Id = it.Id,
DrawerNo = it.DrawerNo,
ColNo = it.ColNo,
DrawerType = it.DrawerType,
BoardType = it.BoardType
}).UpdateColumns(it => new { it.Quantity, it.ManuNo, it.EffDate, it.DrugId }).ExecuteCommand();
}
else
{
//如果批号重复则不让添加
List<ChannelStock> csCount = SqlSugarHelper.Db.Queryable<ChannelStock>().Where(cs => cs.DrawerNo == it.DrawerNo && cs.ManuNo == it.ManuNo && cs.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1")).ToList();
if (csCount.Count > 0)
{
//repeatList.Add(it.ManuNo);
stockRepeats.Add(it);
continue;
}
// 更新数据 库存信息
SqlSugarHelper.Db.Insertable(new ChannelStock()
{
Quantity = it.AddQuantity,
Chnguid = it.Chnguid,
ManuNo = it.ManuNo,
EffDate = it.EffDate,
DrawerNo = it.DrawerNo,
ColNo = it.ColNo,
DrugId = it.DrugId,
DrawerType = it.DrawerType,
BoardType = it.BoardType,
Id = Guid.NewGuid().ToString(),
MachineId = ConfigurationManager.AppSettings["machineId"] ?? "DM1"
}).ExecuteCommand();
}
// 获取更新完库存后的药品库存
List<ChannelStock> nowChannels = SqlSugarHelper.Db.Queryable<ChannelStock>()
.Where(cs => cs.MachineId.Equals(it.MachineId))
.Where(cs => cs.DrugId.Equals(it.DrugId))
.Where(cs => cs.DrawerType == 1)
.ToList();
// 保存数据 入库记录
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 = it.AddQuantity,
Type = SelectedItem.UseId == 0 ? 1 : SelectedItem.UseId,
InvoiceId = InvoiceId,
StockQuantity = nowChannels.Sum(it => it.Quantity),
ManunoQuantity = nowChannels.FindAll(it2 => it2.ManuNo == it.ManuNo).Sum(it => it.Quantity)
}).ExecuteCommand();
}
return true;
});
//ChannelStocks.Clear();
if (stockRepeats.Count == record.Count)
{
AlertMsg alertMsg = new AlertMsg
{
Message = $"该抽屉已存在此药品批次{string.Join(',', stockRepeats.Select(r => r.ManuNo).ToArray())},请选择其他批次",
Type = MsgType.ERROR
};
System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}));
}
else
{
if (f.Data)
{
string msg = string.Empty;
MsgType type = MsgType.SUCCESS;
if (stockRepeats.Count > 0)
{
msg = $"该抽屉下批次{string.Join(',', stockRepeats.Select(r => r.ManuNo).ToArray())}已存在,不可重复添加,其他批次加药完成,库存已更新";
foreach (var stockRpt in stockRepeats)
{
//移除重复的信息,以免更新屏显库存时更新了重复数据
record.Remove(stockRpt);
}
type = MsgType.WARING;
}
else
{
msg = "抽屉加药完成,库存已更新";
}
// 更新屏显库存
//List<ChannelStock> singleChannels = record.FindAll(it => it.BoardType != 1);
List<ChannelStock> singleChannels = ChannelStocks.Where(it => it.BoardType != 1)
.GroupBy(it => it.ColNo)
.Select(it =>
{
var ret = it.First();
ret.Quantity = it.Sum(itx => itx.Quantity);
ret.AddQuantity = it.Sum(itx => itx.AddQuantity);
ret.EffDate = it.Min(it => it.EffDate);
ret.ManuNo = it.OrderBy(it => it.ManuNo).Select(it => it.ManuNo).First().ToString();
return ret;
})
.OrderBy(it => it.EffDate)
.ToList();
singleChannels = singleChannels.Where(it => it.AddQuantity > 0).ToList();
if ((singleChannels.Count > 0 ? singleChannels[0].BoardType : 1) == 5)
{
//将库位多批次的总库存数更新标签
//_portUtil.WriteQuantity(singleChannels[0].DrawerNo, singleChannels[0].ColNo, singleChannels.Sum(it => it.Quantity) + singleChannels.Sum(it => it.AddQuantity));
singleChannels.ForEach(it =>
{
_portUtil.WriteChannelInfo(6, it.EffDate == null ? "" : it.EffDate, it.DrawerNo, it.ColNo);
Thread.Sleep(200);
_portUtil.WriteChannelInfo(5, it.ManuNo, it.DrawerNo, it.ColNo);
Thread.Sleep(200);
_portUtil.ShowContent(it.DrawerNo, it.ColNo);
Thread.Sleep(200);
//写库存数量
_portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.Quantity + it.AddQuantity);
Thread.Sleep(200);
});
}
RequestData();
AlertMsg alertMsg = new AlertMsg
{
Message = msg,
Type = type,
};
System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}));
}
else
{
AlertMsg alertMsg = new AlertMsg
{
Message = "更新库存失败",
Type = MsgType.SUCCESS,
};
System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}));
}
}
Status = 0;
_isFinishClick = false;
PZH = string.Empty;
ChannelStocks.Clear();
}
else
{
_isFinishClick = false;
AlertMsg alertMsg = new AlertMsg
{
Message = "没有填写加药数量",
Type = MsgType.ERROR
};
System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}));
}
}
OptionStatus = -1;
logger.Info("结束保存数据");
}
catch (Exception ex)
{
logger.Info($"AddDrugControlViewModel异常{ex.Message}");
_isFinishClick = false;
AlertMsg alertMsg = new AlertMsg
{
Message = $"异常:{ex.Message}",
Type = MsgType.ERROR
};
System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}));
}
}
// 取消按钮
public DelegateCommand CancleTake
{
get => new DelegateCommand(() =>
{
_portUtil.ResetData();
Status = 0;
});
}
public bool KeepAlive => true;
//添加批次
public void AddAction(ChannelList channelLS)
{
if (channelLS != null)
{
ChannelStock cls = new ChannelStock();
DrugManuNo drugManu = new DrugManuNo();
cls.DrugInfo = channelLS.Drug;
if (channelLS.channelStocks.Count > 0)
{
cls.drugManuNo = channelLS.channelStocks[0].drugManuNo;
}
else
{
//drugManu= cls.DrugInfo.DrugManuNos[0];
if (cls.DrugInfo.DrugManuNos.Count > 0)
{
cls.drugManuNo = cls.DrugInfo.DrugManuNos[0];
}
else
{
AlertMsg alertMsg = new AlertMsg
{
Message = "该药品下没有批次,请先添加批次",
Type = MsgType.ERROR
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
return;
}
}
//cls.Id = "";
cls.Chnguid = channelLS.Id;
cls.MachineId = ConfigurationManager.AppSettings["machineId"] ?? "DM1";
cls.DrawerNo = channelLS.DrawerNo;
cls.BoardType = channelLS.BoardType;
cls.DrawerType = channelLS.DrawerType;
cls.ColNo = channelLS.ColNo;
cls.DrugId = channelLS.DrugId;
cls.AddQuantity = 0;
List<ChannelStock> stockList = new List<ChannelStock>();
stockList.AddRange(channelLS.channelStocks);
stockList.Add(cls);
channelLS.channelStocks = stockList;
}
}
public long CurrentTimeMillis()
{
return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
}
public void FindDrawerCount()
{
//int count = SqlSugarHelper.Db.Queryable<ChannelList>().Where(cs => cs.DrawerType != 3)
// .Where(cs => cs.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1")).GroupBy(cs => cs.DrawerNo).Select(cs => SqlFunc.AggregateCount(cs.DrawerNo)).Count();
Is8Drawer = App.SingleModel; //count < 9;
Is16Drawer = !App.SingleModel; //count >= 16;
Is17Drawer = false;//count > 16;
}
//这个方法用于拦截请求,continuationCallback(true)就是不拦截continuationCallback(false)拦截本次操作
public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
{
continuationCallback(true);
}
public void RequestData()
{
List<ChannelList> queryData = SqlSugarHelper.Db.Queryable<ChannelList>()
.Includes(cl => cl.Drug, di => di.DrugManuNos)
.Includes(cl => cl.channelStocks, dr => dr.DrugInfo, d => d.DrugManuNos)
.Where(cl => cl.DrawerNo == DrawerNo)
.Where(cl => cl.DrawerType == 1)
.Where(cl => cl.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1"))
.Where(cl => cl.DrugId != null)
.OrderBy(cl => cl.ColNo)
.ToList();
ChannelLsts = queryData.Select(cl =>
{
cl.channelStocks = cl.channelStocks.Select(cs =>
{
cs.drugManuNo = cl.Drug.DrugManuNos.Find(it => it.ManuNo.Equals(cs.ManuNo));
return cs;
}).ToList();
return cl;
}).ToList();
//ChannelLsts = new ObservableCollection<ChannelList>(queryData);
ChannelLsts.ForEach(cl => cl.channelStocks.ForEach(cs => cs.DrugInfo = cl.Drug));
}
//接收导航传过来的参数 现在是在此处初始化了表格数据
public void OnNavigatedTo(NavigationContext navigationContext)
{
_eventAggregator.GetEvent<PortUtilEvent>().Subscribe(DoMyPrismEvent);
_eventAggregator.GetEvent<AddDrugEvent>().Subscribe(AddAction);
FindDrawerCount();
RequestData();
}
//每次导航的时候该实列用不用重新创建true是不重新创建,false是重新创建
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
//这个方法用于拦截请求
public void OnNavigatedFrom(NavigationContext navigationContext)
{
// 取消消息订阅
_eventAggregator.GetEvent<PortUtilEvent>().Unsubscribe(DoMyPrismEvent);
_eventAggregator.GetEvent<AddDrugEvent>().Unsubscribe(AddAction);
}
}
}