HuNan_NOSqlSugar/DM_Weight/ViewModels/AddDrugControlViewModel.cs

527 lines
22 KiB
C#
Raw Normal View History

2024-07-06 10:01:30 +08:00
using DM_Weight.Models;
using DM_Weight.msg;
using DM_Weight.Port;
using DM_Weight.Services;
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 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
{
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;
private SqlHelperService _mysqlHelper;
public AddDrugControlViewModel(IDialogService DialogService, PortUtil portUtil, IEventAggregator eventAggregator, SqlHelperService mysqlHelper)
{
_dialogService = DialogService;
_portUtil = portUtil;
_eventAggregator = eventAggregator;
////this.SqlSugarHelper.Db = sqlSugarScope;
vm = this;
_mysqlHelper = mysqlHelper;
}
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); }
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(() =>
{
if (!_isFinishClick)
{
_isFinishClick = true;
foreach (ChannelList lst in ChannelLsts)
{
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>();
bool bResult= false;
stockRepeats=_mysqlHelper.AddDrugSave(record,PZH,ref bResult);
if(!bResult)
{
AlertMsg alertMsg = new AlertMsg
{
Message = $"保存数据失败!",
Type = MsgType.ERROR
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
//ChannelStocks.Clear();
if (stockRepeats.Count == record.Count)
{
AlertMsg alertMsg = new AlertMsg
{
Message = $"该抽屉已存在此药品批次{string.Join(',', stockRepeats.Select(r=>r.ManuNo).ToArray())},请选择其他批次",
Type = MsgType.ERROR
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
else
{
if (bResult)
{
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 ==5&&(it.Quantity>0||it.AddQuantity>0))
.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(500);
//写库存数量
_portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.Quantity + it.AddQuantity);
});
}
RequestData();
AlertMsg alertMsg = new AlertMsg
{
Message = msg,
Type = type,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
else
{
logger.Info($"多批次抽屉加药,库存更新失败!");
AlertMsg alertMsg = new AlertMsg
{
Message = "更新库存失败",
Type = MsgType.SUCCESS,
};
_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
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
}
});
}
// 取消按钮
public DelegateCommand CancleTake
{
get => new DelegateCommand(() =>
{
_portUtil.ResetData();
Status = 0;
});
}
public bool KeepAlive => false;
//添加批次
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;
cls.State = 0;
List<ChannelStock> stockList = new List<ChannelStock>();
stockList.AddRange(channelLS.channelStocks);
stockList.Add(cls);
channelLS.channelStocks = stockList;
}
}
//删除药品下批次库存为0的批次
private void DelManuNO(ChannelStock cstock)
{
//if(cstock != null)
//{
// //删除ChannelStock表中该批次数据
// int isOk = SqlSugarHelper.Db.Deleteable<ChannelStock>().Where(cs => cs.DrugId == cstock.DrugId && cs.ManuNo == cs.ManuNo).ExecuteCommand();
// if (isOk>0 )
// {
// logger.Info($"删除{cstock.DrawerNo}-{cstock.ColNo}抽屉中药品{cstock.DrugId}下的批次{cstock.ManuNo},");
// AlertMsg alertMsg = new AlertMsg
// {
// Message = "该药品批次已删除",
// Type = MsgType.ERROR
// };
// _eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
// }
// else
// {
// AlertMsg alertMsg = new AlertMsg
// {
// Message = "该药品批次删除失败",
// Type = MsgType.ERROR
// };
// _eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
// }
//}
}
public long CurrentTimeMillis()
{
return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
}
public void FindDrawerCount()
{
int count = _mysqlHelper.FindDrawerCount();
//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 = count < 9;
Is16Drawer = count >= 16;
Is17Drawer = 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();
List<ChannelList> queryData = _mysqlHelper.GetAddDrugInfo(DrawerNo);
ChannelLsts = queryData.AsParallel().Select(cl =>
{
cl.channelStocks = cl.channelStocks.Select(cs =>
{
cs.drugManuNo = cl.Drug.DrugManuNos.Find(it => it.ManuNo.Equals(cs.ManuNo));
cs.DrugId=cl.DrugId;
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);
_eventAggregator.GetEvent<DelDrugManoEvent>().Subscribe(DelManuNO);
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);
_eventAggregator.GetEvent<DelDrugManoEvent>().Unsubscribe(DelManuNO);
}
}
}