XiChang/DM_Weight/ViewModels/BiaoDingWindowViewModel.cs

545 lines
22 KiB
C#
Raw Permalink Normal View History

2024-02-27 09:01:14 +08:00
using DM_Weight.Common;
using DM_Weight.Models;
using DM_Weight.msg;
using DM_Weight.Port;
using DM_Weight.util;
using log4net;
using NetTaste;
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.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace DM_Weight.ViewModels
{
public class BiaoDingWindowViewModel : BindableBase, IConfirmNavigationRequest, IRegionMemberLifetime
{
private readonly ILog logger = LogManager.GetLogger(typeof(BiaoDingWindowViewModel));
private List<int> _drawerNoList = new List<int>();
/// <summary>
/// 抽屉号按钮是否可用
/// </summary>
private string _btnVisibil;
public string BtnVisibil
{
get => _btnVisibil; set
{
SetProperty(ref _btnVisibil, value);
}
}
//状态,抽屉下的库位有库存为0的则可标定否则不可标定
private int _status;
public int Status { get => _status; set => SetProperty(ref _status, value); }
//凭证号
private string _pzh;
public string PZH { get => _pzh; set { SetProperty(ref _pzh, value); } }
private ObservableCollection<ChannelStock>? _channelStocks;
public ObservableCollection<ChannelStock>? ChannelStocks
{
get => _channelStocks;
set => SetProperty(ref _channelStocks, value);
}
private ChannelStock? _channelStock;
public ChannelStock? CStock
{
get => _channelStock;
set => SetProperty(ref _channelStock, value);
}
private static readonly DateTime Jan1st1970 = new DateTime
(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private PortUtil _portUtil;
IEventAggregator _eventAggregator;
IDialogService _dialogService;
public BiaoDingWindowViewModel(IDialogService DialogService, PortUtil portUtil, IEventAggregator eventAggregator)
{
_dialogService = DialogService;
_portUtil = portUtil;
_eventAggregator = eventAggregator;
}
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)
{
CStock = null;
RequestData();
}
//void DoMyPrismEvent(DeviceMsg msg)
//{
// if (msg.WindowName == "DrawerAddDrugWindow")
// {
// 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 == 4)
// // {
// // ChannelStocks.ToList().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 _drawerNo = Convert.ToInt32(ConfigurationManager.AppSettings["WeightDrawerNumber"].Split(',')[0]);
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) =>
{
//BtnStatus = 0;
this.DrawerNo = Convert.ToInt32(DrawerNo);
RequestData();
});
}
public DelegateCommand OpenDrawer
{
get => new DelegateCommand(OpenDrawerMethod
// async () =>
//{
// try
// {
// List<ChannelStock> singleChannels = ChannelStocks.ToList().FindAll(it => it.BoardType == (Int32)BoardTypeEnum.weighBox && it.PosNo == 0 && it.Quantity == 0 && it.AddQuantity > 0);
// if (singleChannels.Count > 0)
// {
// ChannelStocks = new ObservableCollection<ChannelStock> (singleChannels);
// Status = 2;
// _portUtil.SpeakAsync("正在打开" + DrawerNo + "号抽屉");
// //发送称重25指令
// await SendClearCount(singleChannels);
// _portUtil.Operate = true;
// _portUtil.BoardType = singleChannels.Count > 0 ? singleChannels[0].BoardType : (Int32)BoardTypeEnum.separation;
// _portUtil.ColNos = singleChannels.Select(it => it.ColNo).ToArray();
// //_portUtil.Stocks = singleChannels.Select(it => it.Quantity).ToArray();
// _portUtil.DrawerNo = DrawerNo;
// //_portUtil.Start();
// byte[] buffer = await _portUtil.OpenDrawer();
// int[] r = buffer.Select(it => Convert.ToInt32(it)).ToArray();
// logger.Info($"OpenDrawer{string.Join(",", r)}");
// if (DrawerState(r))
// {
// _portUtil.BoxLockLightOn2();
// }
// Status = 3;
// }
// else
// {
// _isFinishClick = false;
// AlertMsg alertMsg = new AlertMsg
// {
// Message = "请填写药品数量",
// Type = MsgType.ERROR
// };
// _eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
// }
// }
// catch (Exception ex)
// {
// _portUtil.ResetData();
// logger.Info($"OpenDrawer异常{ex.Message}");
// _isFinishClick = false;
// AlertMsg alertMsg = new AlertMsg
// {
// Message = $"异常:{ex.Message}",
// Type = MsgType.ERROR
// };
// _eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
// //Status = 1;
// }
// //finally { BiaoDingLoading = false;}
//}
);
}
private void OpenDrawerMethod()
{
_portUtil.Operate = true;
OpenDrawerMethodAction();
}
private async void OpenDrawerMethodAction()
{
try
{
if (_portUtil.Operate)
{
List<ChannelStock> singleChannels = ChannelStocks.ToList().FindAll(it => it.BoardType == (Int32)BoardTypeEnum.weighBox && it.PosNo == 0 && it.Quantity == 0 && it.AddQuantity > 0);
if (singleChannels.Count > 0)
{
ChannelStocks = new ObservableCollection<ChannelStock>(singleChannels);
Status = 2;
_portUtil.SpeakAsync("正在打开" + DrawerNo + "号抽屉");
//发送称重25指令
await SendClearCount(singleChannels);
_portUtil.BoardType = singleChannels.Count > 0 ? singleChannels[0].BoardType : (Int32)BoardTypeEnum.separation;
_portUtil.ColNos = singleChannels.Select(it => it.ColNo).ToArray();
//_portUtil.Stocks = singleChannels.Select(it => it.Quantity).ToArray();
_portUtil.DrawerNo = DrawerNo;
//_portUtil.Start();
byte[] buffer = await _portUtil.OpenDrawer();
int[] r = buffer.Select(it => Convert.ToInt32(it)).ToArray();
logger.Info($"OpenDrawer{string.Join(",", r)}");
if (DrawerState(r))
{
_portUtil.BoxLockLightOn2();
}
Status = 3;
}
else
{
_isFinishClick = false;
AlertMsg alertMsg = new AlertMsg
{
Message = "请填写药品数量",
Type = MsgType.ERROR
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
}
}
catch (Exception ex)
{
_portUtil.ResetData();
logger.Info($"OpenDrawer异常{ex.Message}");
_isFinishClick = false;
AlertMsg alertMsg = new AlertMsg
{
Message = $"异常:{ex.Message}",
Type = MsgType.ERROR
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
//Status = 1;
}
}
//抽屉返回状态
private bool DrawerState(int[] r)
{
int index = DrawerNo > 8 ? DrawerNo - 7 : DrawerNo + 1;
return r[index] == 0;
}
/// <summary>
/// 发送计数清零25指令
/// </summary>
/// <returns></returns>
private async Task SendClearCount(List<ChannelStock> channels)
{
//发送计数清零指令25
if (channels.Count > 0)
{
for (int i = 0; i < channels.Count; i++)
{
ChannelStock it = channels[i];
_portUtil.ClearCount(it.DrawerNo, it.ColNo);
await Task.Delay(50);
}
await Task.Delay(3000);
}
}
private bool _isFinishClick = false;
// 确认按钮
public DelegateCommand TakeFinish
{
get => new DelegateCommand(async () =>
{
Status = 4;
//ConfirmLoading = true;
if (!_isFinishClick)
{
await Task.Delay(5000);
_isFinishClick = true;
List<ChannelStock> record = ChannelStocks.ToList().FindAll(it => it.AddQuantity != 0).ToList();
if (record.Count > 0)
{
string InvoiceId = "BiaoDing_" + CurrentTimeMillis();
//string InvoiceId = PZH;
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;
// 更新数据 库存信息
SqlSugarHelper.Db.Updateable(new ChannelStock()
{
Quantity = it.Quantity + it.AddQuantity,
ManuNo = it.ManuNo,
EffDate = it.EffDate,
Id = it.Id,
PosNo = 1
}).UpdateColumns(it => new { it.Quantity, it.ManuNo, it.EffDate, it.PosNo }).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 == (Int32)DrawerTypeEnum.drawerTypeOne)
.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,
OperationTime = DateTime.Now,
Quantity = it.AddQuantity,
Type = 1,
InvoiceId = InvoiceId,
StockQuantity = nowChannels.Sum(it => it.Quantity),
ManunoQuantity = nowChannels.FindAll(it2 => it2.ManuNo == it.ManuNo).Sum(it => it.Quantity)
}).ExecuteCommand();
//称重计数或称重+智能显示+管控药盒 类型需要 发26指令
if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox || it.BoardType == (Int32)BoardTypeEnum.weighBox)
{
Thread.Sleep(1000);
//计数数量设置发送称重26指令
_portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity);
}
}
return true;
});
if (f.Data)
{
// 更新屏显库存
List<ChannelStock> singleChannels = record.FindAll(it => it.BoardType != (Int32)BoardTypeEnum.separation);
if ((singleChannels.Count > 0 ? singleChannels[0].BoardType : (Int32)BoardTypeEnum.separation) == (Int32)BoardTypeEnum.smart || (singleChannels.Count > 0 ? singleChannels[0].BoardType : (Int32)BoardTypeEnum.separation) == (Int32)BoardTypeEnum.weighSmartBox)
{
singleChannels.ForEach(it =>
{
_portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.Quantity + it.AddQuantity);
});
}
RequestData();
AlertMsg alertMsg = new AlertMsg
{
Message = "抽屉标定完成,请关闭抽屉",
Type = MsgType.SUCCESS,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
else
{
AlertMsg alertMsg = new AlertMsg
{
Message = "标定更新库存失败",
Type = MsgType.SUCCESS,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
//Status = 0;
_isFinishClick = false;
//ConfirmVisibi = Visibility.Collapsed;
//CancelVisibi = Visibility.Collapsed;
}
else
{
_isFinishClick = false;
AlertMsg alertMsg = new AlertMsg
{
Message = "没有填写药品数量",
Type = MsgType.ERROR
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
_portUtil.ResetData();
}
});
}
// 取消按钮
public DelegateCommand CancleTake
{
get => new DelegateCommand(() =>
{
_portUtil.ResetData();
//ConfirmVisibi = Visibility.Collapsed;
//CancelVisibi = Visibility.Collapsed;
RequestData();
//Status = 0;
//BtnStatus = 0;
//BiaoDingBtnFlag = false;
});
}
//选中批次
public DelegateCommand ComboboxSelected
{
get => new DelegateCommand(() =>
{
ChannelStocks.Where(it => it.Location == "").Select(it => it.ManuNo = "12").ToList();
});
}
public long CurrentTimeMillis()
{
return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
}
public bool KeepAlive => false;
public void FindDrawerCount()
{
int count = SqlSugarHelper.Db.Queryable<ChannelStock>().Where(cs => cs.DrawerType != (Int32)DrawerTypeEnum.recyle)
.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<ChannelStock> queryData = SqlSugarHelper.Db.Queryable<ChannelStock>()
.Includes(cs => cs.DrugInfo, di => di.DrugManuNos)
.Where(cs => cs.DrawerNo == DrawerNo)
.Where(cs => cs.DrawerType == (Int32)DrawerTypeEnum.drawerTypeOne)
.Where(cs => cs.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1"))
.Where(cs => cs.DrugId != null)
.OrderBy(cs => cs.ColNo)
.ToList();
ChannelStocks = new ObservableCollection<ChannelStock>(queryData.Select(cs =>
{
cs.drugManuNo = cs.DrugInfo.DrugManuNos.Find(it => it.ManuNo.Equals(cs.ManuNo));
return cs;
}).ToList());
ChannelStock cs = ChannelStocks.FirstOrDefault(cs => cs.Quantity <= 0);
if (cs != null && cs.Id != null && !string.IsNullOrEmpty(cs.Id))
{
//BiaoDingBtnFlag = true;
Status = 0;
}
else
{
Status = 1;
//BiaoDingBtnFlag = false;
//CancelVisibi = Visibility.Visible;
}
//ConfirmVisibi = Visibility.Collapsed;
//obChannelStock = new ObservableCollection<ChannelStock>(ChannelStocks);
}
//接收导航传过来的参数 现在是在此处初始化了表格数据
public void OnNavigatedTo(NavigationContext navigationContext)
{
//_eventAggregator.GetEvent<PortUtilEvent>().Subscribe(DoMyPrismEvent);
FindDrawerCount();
RequestData();
}
//每次导航的时候该实列用不用重新创建true是不重新创建,false是重新创建
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
//这个方法用于拦截请求
public void OnNavigatedFrom(NavigationContext navigationContext)
{
// 取消消息订阅
//_eventAggregator.GetEvent<PortUtilEvent>().Unsubscribe(DoMyPrismEvent);
}
}
}