Compare commits

...

11 Commits

62 changed files with 4117 additions and 1151 deletions

View File

@ -3,7 +3,7 @@
<connectionStrings> <connectionStrings>
<!-- 数据库连接字符串 --> <!-- 数据库连接字符串 -->
<!--<add name="database" connectionString="server=127.0.0.1;database=wpf_dm_program;userid=root;password=qq1223" />--> <!--<add name="database" connectionString="server=127.0.0.1;database=wpf_dm_program;userid=root;password=qq1223" />-->
<add name="database" connectionString="server=127.0.0.1;port=3306;database=xichang_db_xianchang;userid=root;password=root" /> <add name="database" connectionString="server=127.0.0.1;port=3306;database=xichang_db;userid=root;password=root" />
</connectionStrings> </connectionStrings>
<!--<runtime> <!--<runtime>
--><!--配置之后Appdomain.CurrentDomain.UnhandledException 事件的 IsTerminating 就变成了 false 啦!也就是说,程序并不会因为这次的异常而崩溃退出。--><!-- --><!--配置之后Appdomain.CurrentDomain.UnhandledException 事件的 IsTerminating 就变成了 false 啦!也就是说,程序并不会因为这次的异常而崩溃退出。--><!--
@ -20,7 +20,9 @@
<!-- 登录顺序,指定先登录的人的名称有效值只有在登录模式等于2时才会生效 发药人【operator】审核人【reviewer】 --> <!-- 登录顺序,指定先登录的人的名称有效值只有在登录模式等于2时才会生效 发药人【operator】审核人【reviewer】 -->
<add key="firstLogin" value="operator" /> <add key="firstLogin" value="operator" />
<!-- 按处方还药或者按取药记录还药 1:处方ReturnDrugWindow22药品ReturnDrugWindow--> <!-- 按处方还药或者按取药记录还药 1:处方ReturnDrugWindow22药品ReturnDrugWindow-->
<add key="returnDrugMode" value="1" /> <add key="returnDrugMode" value="2" />
<!-- 1:多处方取药 0:无多处方取药-->
<add key="manyOrder" value="1" />
<!-- 自动退出时间单位秒为0时不自动退出 --> <!-- 自动退出时间单位秒为0时不自动退出 -->
<add key="autoExit" value="0"/> <add key="autoExit" value="0"/>
@ -36,9 +38,9 @@
<!-- 抽屉串口使用的协议232或者485 --> <!-- 抽屉串口使用的协议232或者485 -->
<add key="DrawerProtocol" value="485" /> <add key="DrawerProtocol" value="485" />
<!-- 抽屉串口的串口号 --> <!-- 抽屉串口的串口号 -->
<add key="DrawerPortPath" value="COM6" /> <add key="DrawerPortPath" value="COM1" />
<!-- can总线串口的串口号 --> <!-- can总线串口的串口号 -->
<add key="CanBusPortPath" value="COM17" /> <add key="CanBusPortPath" value="COM30" />
<!-- 条码枪串口的串口号 --> <!-- 条码枪串口的串口号 -->
<add key="ScanCodePortPath" value="COM8" /> <add key="ScanCodePortPath" value="COM8" />
<!-- 冰箱的串口号 --> <!-- 冰箱的串口号 -->
@ -56,7 +58,7 @@
<!-- 指纹机号码 --> <!-- 指纹机号码 -->
<add key="machineNumber" value="1"/> <add key="machineNumber" value="1"/>
<!-- 指纹机ip --> <!-- 指纹机ip -->
<add key="fingerIp" value="192.168.1.201"/> <add key="fingerIp" value="192.168.50.201"/>
<!-- 多处方取药 0:不启用 1启用--> <!-- 多处方取药 0:不启用 1启用-->
<add key="MultiOrder" value="0"/> <add key="MultiOrder" value="0"/>
@ -71,11 +73,14 @@
<add key="temperatureValue" value="3.2"/> <add key="temperatureValue" value="3.2"/>
<!--温度查询定时执行时间--> <!--温度查询定时执行时间-->
<add key="Interval" value="60000"/> <add key="Interval" value="0"/>
<!--冰箱状态1关闭0打开--> <!--冰箱状态1关闭0打开-->
<add key="FridgeState" value="0"/> <add key="FridgeState" value="1"/>
<!--报警状态1关闭0打开--> <!--报警状态1关闭0打开-->
<add key="AlarmState" value="0"/> <add key="AlarmState" value="0"/>
<!--冰箱不在区间超时时间(超过指定的时间仍不在区间则提示)单位分-->
<add key="OutRangeTime" value="20"/>
<!--获取冰箱温度定时 单位秒-->
<add key="TemperatureTimer" value="10"/>
</appSettings> </appSettings>
</configuration> </configuration>

View File

@ -177,6 +177,7 @@ namespace DM_Weight
containerRegistry.RegisterForNavigation<OrderReturnDialog, OrderReturnDialogViewModel>(); containerRegistry.RegisterForNavigation<OrderReturnDialog, OrderReturnDialogViewModel>();
// 还空瓶页面 // 还空瓶页面
containerRegistry.RegisterForNavigation<ReturnEmptyWindow, ReturnEmptyWindowViewModel>(); containerRegistry.RegisterForNavigation<ReturnEmptyWindow, ReturnEmptyWindowViewModel>();
containerRegistry.RegisterForNavigation<ReturnWithOrderWindow, ReturnWithOrderWindowViewModel>();
// 归还空瓶模态框 // 归还空瓶模态框
containerRegistry.RegisterDialog<ReturnEmptyDialog>(); containerRegistry.RegisterDialog<ReturnEmptyDialog>();
containerRegistry.RegisterForNavigation<ReturnEmptyDialog, ReturnEmptyDialogViewModel>(); containerRegistry.RegisterForNavigation<ReturnEmptyDialog, ReturnEmptyDialogViewModel>();
@ -223,6 +224,10 @@ namespace DM_Weight
containerRegistry.RegisterForNavigation<ShowMessageDialog, ShowMessageDialogViewModel>(); containerRegistry.RegisterForNavigation<ShowMessageDialog, ShowMessageDialogViewModel>();
containerRegistry.RegisterForNavigation<WarnDialog, WarnDialogViewModel>();
containerRegistry.RegisterForNavigation<BiaoDingDialog, BiaoDingDialogViewModel>();
} }
private void PrismApplication_Startup(object sender, StartupEventArgs e) private void PrismApplication_Startup(object sender, StartupEventArgs e)
{ {

View File

@ -23,11 +23,18 @@ namespace DM_Weight.Common
string[] rang = value.ToString().Split('-'); string[] rang = value.ToString().Split('-');
if (rang.Length >= 2) if (rang.Length >= 2)
{ {
bool bSRange = int.TryParse(rang[0], out int sRange); bool bSRange = float.TryParse(rang[0], out float sRange);
bool bERange = int.TryParse(rang[1], out int eRange); bool bERange = float.TryParse(rang[1], out float eRange);
if (bSRange && bERange) if (bSRange && bERange)
{ {
if (sRange < 2 || eRange > 8) string[] sList = sRange.ToString().Split('.');
string[] eList = eRange.ToString().Split(".");
if ((sList.Length > 1 && sList[1].Length > 1) || (eList.Length > 1 && eList[1].Length > 1))
{
tips = "小数点后保留1位";
return new ValidationResult(flag, tips);
}
if ((sRange < 2 || eRange > 8 || sRange > 8 || eRange < 2))
{ {
tips = "温度区间设置2-8度请检查输入"; tips = "温度区间设置2-8度请检查输入";
return new ValidationResult(flag, tips); return new ValidationResult(flag, tips);

View File

@ -16,6 +16,8 @@ namespace DM_Weight.Converter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{ {
bool bFlag = int.Parse(value.ToString()) == (Int32)BoardTypeEnum.single || int.Parse(value.ToString()) == (Int32)BoardTypeEnum.weigh || int.Parse(value.ToString()) == (Int32)BoardTypeEnum.weighBox || int.Parse(value.ToString()) == (Int32)BoardTypeEnum.weighSmartBox ? ReadOnlyValue : NotReadOnlyValue;
return bFlag;
return int.Parse(value.ToString()) == (Int32)BoardTypeEnum.single || int.Parse(value.ToString()) == (Int32)BoardTypeEnum.weigh || int.Parse(value.ToString()) == (Int32)BoardTypeEnum.weighSmartBox ? ReadOnlyValue : NotReadOnlyValue; return int.Parse(value.ToString()) == (Int32)BoardTypeEnum.single || int.Parse(value.ToString()) == (Int32)BoardTypeEnum.weigh || int.Parse(value.ToString()) == (Int32)BoardTypeEnum.weighSmartBox ? ReadOnlyValue : NotReadOnlyValue;
} }

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace DM_Weight.Converter
{
internal class OpenBoxConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool status = bool.Parse(value.ToString());
if(status)
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}

View File

@ -73,6 +73,42 @@ namespace DM_Weight.Converter
return Visibility.Collapsed; return Visibility.Collapsed;
} }
} }
//清空按钮的显示与隐藏
if(parameter.ToString().Equals("clearVisuability"))
{
if (status <= 1)
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
//清空按钮的操作状态
if(parameter.ToString().Equals("clearBtnLoading"))
{
if (status == 1)
{
return true;
}
else
{
return false;
}
}
//标定按钮的操作状态
if(parameter.ToString().Equals("biaoDingBtnLoading"))
{
if (status >3)
{
return true;
}
else
{
return false;
}
}
return Visibility.Collapsed; return Visibility.Collapsed;
} }

View File

@ -70,6 +70,7 @@
<PackageReference Include="MaterialDesignThemes" Version="4.8.0" /> <PackageReference Include="MaterialDesignThemes" Version="4.8.0" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.39" /> <PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.39" />
<PackageReference Include="Prism.Unity" Version="8.1.97" /> <PackageReference Include="Prism.Unity" Version="8.1.97" />
<PackageReference Include="SharpPromise" Version="1.7.0" />
<PackageReference Include="SqlSugarCore" Version="5.1.4.67" /> <PackageReference Include="SqlSugarCore" Version="5.1.4.67" />
<PackageReference Include="SuperSimpleTcp" Version="3.0.10" /> <PackageReference Include="SuperSimpleTcp" Version="3.0.10" />
<PackageReference Include="System.Drawing.Common" Version="7.0.0" /> <PackageReference Include="System.Drawing.Common" Version="7.0.0" />
@ -94,6 +95,9 @@
<None Update="App.config"> <None Update="App.config">
<CopyToOutputDirectory>Never</CopyToOutputDirectory> <CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None> </None>
<None Update="favicon.ico">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="log4net.config"> <None Update="log4net.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>

View File

@ -1,4 +1,5 @@
using SqlSugar; using Prism.Mvvm;
using SqlSugar;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -9,7 +10,7 @@ using System.Threading.Tasks;
namespace DM_Weight.Models namespace DM_Weight.Models
{ {
[SugarTable("dm_machine_record")] [SugarTable("dm_machine_record")]
public class MachineRecord public class MachineRecord:BindableBase
{ {
/// <summary> /// <summary>
/// 主键 /// 主键
@ -114,6 +115,27 @@ namespace DM_Weight.Models
///</summary> ///</summary>
[SugarColumn(ColumnName = "return_quantity2", IsOnlyIgnoreInsert = true)] [SugarColumn(ColumnName = "return_quantity2", IsOnlyIgnoreInsert = true)]
public int ReturnQuantity2 { get; set; } public int ReturnQuantity2 { get; set; }
/// <summary>
/// 当前还空瓶量
/// 默认值: 0
///</summary>
private int _currentReturn;
[SugarColumn(IsIgnore = true)]
public int CurrentReturn
{
get=>_currentReturn;
set
{
if (value > CanReturnQuantity)
{
throw new ArgumentException("");
}
SetProperty(ref _currentReturn, value);
}
}
/// <summary> /// <summary>
/// 取药记录id /// 取药记录id
///</summary> ///</summary>
@ -143,5 +165,10 @@ namespace DM_Weight.Models
/// </summary> /// </summary>
[SugarColumn(ColumnName = "manunoQuantity")] [SugarColumn(ColumnName = "manunoQuantity")]
public int? ManunoQuantity { get; set; } public int? ManunoQuantity { get; set; }
private DrugManuNo? _drugManuNo;
[SugarColumn(IsIgnore = true)]
public DrugManuNo? drugManuNo { get => _drugManuNo; set => SetProperty(ref _drugManuNo, value); }
} }
} }

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Prism.Mvvm;
using SqlSugar; using SqlSugar;
namespace DM_Weight.Models namespace DM_Weight.Models
{ {
@ -8,12 +9,12 @@ namespace DM_Weight.Models
/// ///
///</summary> ///</summary>
[SugarTable("order_detail")] [SugarTable("order_detail")]
public class OrderDetail public class OrderDetail: BindableBase
{ {
/// <summary> /// <summary>
/// ///
///</summary> ///</summary>
[SugarColumn(ColumnName = "id", IsPrimaryKey = true, IsIdentity = true)] [SugarColumn(ColumnName = "id", IsIdentity = true, IsPrimaryKey = true)]
public int Id { get; set; } public int Id { get; set; }
/// <summary> /// <summary>
/// ///
@ -29,6 +30,11 @@ namespace DM_Weight.Models
/// <summary> /// <summary>
/// ///
///</summary> ///</summary>
[SugarColumn(ColumnName = "order_id")]
public string OrderId { get; set; }
/// <summary>
///
///</summary>
[SugarColumn(ColumnName = "order_no")] [SugarColumn(ColumnName = "order_no")]
public string OrderNo { get; set; } public string OrderNo { get; set; }
/// <summary> /// <summary>
@ -50,6 +56,12 @@ namespace DM_Weight.Models
[Navigate(NavigateType.ManyToOne, nameof(DrugId))] [Navigate(NavigateType.ManyToOne, nameof(DrugId))]
public DrugInfo DrugInfo { get; set; } public DrugInfo DrugInfo { get; set; }
[Navigate(NavigateType.ManyToMany, nameof(DrugId))]
public List<DrugInfo> DrugInfos { get; set; }
[Navigate(NavigateType.ManyToMany, nameof(DrugId))]
public List<MachineRecord> MachineRecords { get; set; }
/// <summary> /// <summary>
/// ///
///</summary> ///</summary>
@ -127,5 +139,33 @@ namespace DM_Weight.Models
///</summary> ///</summary>
[SugarColumn(ColumnName = "use_dosage")] [SugarColumn(ColumnName = "use_dosage")]
public string UseDosage { get; set; } public string UseDosage { get; set; }
/// <summary>
/// 已还药数
/// </summary>
private int _returnQuantity = 0;
[SugarColumn(ColumnName = "return_quantity")]
public int ReturnQuantity
{
get;
set;
}
//当前还药数
private int currentReturnQuantity;
[SugarColumn(IsIgnore =true)]
public int CurrentReturnQuantity
{
get => currentReturnQuantity;
set
{
//if (value > Quantity - ReturnQuantity)
// throw new ArgumentException("数量有误");
SetProperty(ref currentReturnQuantity, value);
}
}
private OrderInfo? _orderInfo;
[Navigate(NavigateType.OneToOne,nameof(OrderNo))]
public OrderInfo orderInfo { get => _orderInfo; set => SetProperty(ref _orderInfo, value); }
} }
} }

View File

@ -28,5 +28,18 @@ namespace DM_Weight.Models
[SugarColumn(ColumnName = "operator")] [SugarColumn(ColumnName = "operator")]
public string Operator { get; set; } public string Operator { get; set; }
[SugarColumn(ColumnName = "drug_id")]
public string DrugId { get; set; }
[SugarColumn(ColumnName = "quantity")]
public int Quantity { get; set; }
//[SugarColumn(ColumnName = "manu_no")]
//public string ManuNo { get; set; }
//[SugarColumn(ColumnName = "eff_date")]
//public string EffDate { get; set; }
} }
} }

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Prism.Mvvm;
using SqlSugar; using SqlSugar;
namespace DM_Weight.Models namespace DM_Weight.Models
{ {
@ -8,7 +9,7 @@ namespace DM_Weight.Models
/// ///
///</summary> ///</summary>
[SugarTable("order_info")] [SugarTable("order_info")]
public class OrderInfo public class OrderInfo:BindableBase
{ {
@ -16,7 +17,7 @@ namespace DM_Weight.Models
/// 是否选中 /// 是否选中
/// </summary> /// </summary>
[SugarColumn(IsIgnore = true)] [SugarColumn(IsIgnore = true)]
public bool ItemIsChecked { get; set; } public bool ItemIsChecked { get; set; } = false;
/// <summary> /// <summary>
/// ///
@ -197,6 +198,10 @@ namespace DM_Weight.Models
//[SugarColumn(ColumnName = "identity")] //[SugarColumn(ColumnName = "identity")]
//public string Identity { get; set; } //public string Identity { get; set; }
private OrderDetail? _orderDetail;
[Navigate(NavigateType.OneToOne, nameof(OrderDetail.OrderNo))]
public OrderDetail orderDetail { get=> _orderDetail; set=>SetProperty(ref _orderDetail, value); }
} }
} }

View File

@ -25,6 +25,7 @@ using DM_Weight.Views;
using System.Reflection; using System.Reflection;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using DM_Weight.Common; using DM_Weight.Common;
using System.Threading;
namespace DM_Weight.Port namespace DM_Weight.Port
{ {
@ -57,6 +58,10 @@ namespace DM_Weight.Port
public int DrawerNo { get; set; } public int DrawerNo { get; set; }
// 当前操作的库位号列表 // 当前操作的库位号列表
public int[] ColNos { get; set; } = new int[] { }; public int[] ColNos { get; set; } = new int[] { };
// 当前操作查数的库位号列表
public List<int> ColNoLst { get; set; } = new List<int>();
// 当前操作开药盒的库位号
public int OpenBoxColNo { get; set; } = 0;
// 当前操作的窗口 // 当前操作的窗口
public string WindowName { get; set; } public string WindowName { get; set; }
@ -72,7 +77,7 @@ namespace DM_Weight.Port
public int BoardType { get; set; } = (Int32)BoardTypeEnum.separation; public int BoardType { get; set; } = (Int32)BoardTypeEnum.separation;
public int DrawerType { get; set; } = (Int32)DrawerTypeEnum.drawerTypeOne; public int DrawerType { get; set; } = (Int32)DrawerTypeEnum.drawerTypeOne;
private int[] BeforeQuantity { get; set; } = new int[] { }; private int[] BeforeQuantity { get; set; } = new int[9];
private int[] AfterQuantity { get; set; } = new int[] { }; private int[] AfterQuantity { get; set; } = new int[] { };
// 整体流程状态 // 整体流程状态
@ -108,18 +113,18 @@ namespace DM_Weight.Port
// 失能 // 失能
CloseStorage(); CloseStorage();
} }
if (BoardType == (Int32)BoardTypeEnum.weigh) //if (BoardType == (Int32)BoardTypeEnum.weigh)
{ //{
// 失能 // // 失能
await BoxLockLightOff2(); // await BoxLockLightOff2();
} //}
if (BoardType == (Int32)BoardTypeEnum.weighSmartBox || BoardType == (Int32)BoardTypeEnum.weighBox) //if (BoardType == (Int32)BoardTypeEnum.weighSmartBox || BoardType == (Int32)BoardTypeEnum.weighBox)
{ //{
// 失能 // // 失能
await BoxLockLightOff(); // await BoxLockLightOff();
// 失能 // // 失能
await BoxLockLightOff2(); // await BoxLockLightOff2();
} //}
} }
Operate = false; Operate = false;
dateTime = DateTime.Now; dateTime = DateTime.Now;
@ -218,11 +223,18 @@ namespace DM_Weight.Port
logger.Info($"BeforeQuantity{string.Join(",", BeforeQuantity)}"); logger.Info($"BeforeQuantity{string.Join(",", BeforeQuantity)}");
} }
if (BoardType == (Int32)BoardTypeEnum.weigh || BoardType == (Int32)BoardTypeEnum.weighSmartBox || BoardType == (Int32)BoardTypeEnum.weighBox) if (BoardType == (Int32)BoardTypeEnum.weigh || BoardType == (Int32)BoardTypeEnum.weighSmartBox || BoardType == (Int32)BoardTypeEnum.weighBox)
{
if (WindowName != "DrawerTakeDrugWindow" && WindowName != "DrawerAddDrugWindow")
{ {
int[] quantity = await CheckQuantityByAddr2(); int[] quantity = await CheckQuantityByAddr2();
BeforeQuantity = quantity.Select(it => Convert.ToInt32(it)).ToArray(); BeforeQuantity = quantity.Select(it => Convert.ToInt32(it)).ToArray();
logger.Info($"BeforeQuantity{string.Join(",", BeforeQuantity)}"); logger.Info($"BeforeQuantity{string.Join(",", BeforeQuantity)}");
} }
else
{
logger.Info($"{WindowName}开锁前先不查数");
}
}
byte[] buffer = await OpenDrawer(); byte[] buffer = await OpenDrawer();
int[] r = buffer.Select(it => Convert.ToInt32(it)).ToArray(); int[] r = buffer.Select(it => Convert.ToInt32(it)).ToArray();
@ -259,15 +271,38 @@ namespace DM_Weight.Port
} }
} }
// 药盒 // 药盒
if (BoardType == (Int32)BoardTypeEnum.box) //if (BoardType == (Int32)BoardTypeEnum.box)
//{
// //抽屉加药和抽屉取药不开药盒锁(单独开)
// if (WindowName != "DrawerTakeDrugWindow" || WindowName != "DrawerAddDrugWindow")
// {
// logger.Info("开锁后药盒自动打开");
// //// 药盒指示灯使能
// //await BoxLockLightOn();
// await OpenBox();
// }
// else
// {
// logger.Info("开锁后先不开药盒");
// //抽屉加药和抽屉取药根据点的开药盒按钮的库位查数
// ColNos = null;
// }
//}
if (BoardType == (Int32)BoardTypeEnum.box || BoardType == (Int32)BoardTypeEnum.weighSmartBox || BoardType == (Int32)BoardTypeEnum.weighBox)
{ {
//抽屉加药和抽屉取药不开药盒锁(单独开)
if (WindowName != "DrawerTakeDrugWindow" && WindowName != "DrawerAddDrugWindow")
{
logger.Info($"开锁后药盒自动打开{WindowName}");
// 药盒指示灯使能 // 药盒指示灯使能
await BoxLockLightOn(); await OpenBox();
} }
if (BoardType == (Int32)BoardTypeEnum.weigh || BoardType == (Int32)BoardTypeEnum.weighSmartBox || BoardType == (Int32)BoardTypeEnum.weighBox) else
{ {
// 药盒指示灯使能 logger.Info($"{WindowName}开锁后先不开药盒");
await BoxLockLightOn2(); //抽屉加药和抽屉取药根据点的开药盒按钮的库位查数
ColNos = null;
}
} }
// 返回消息 抽屉已经打开 // 返回消息 抽屉已经打开
_eventAggregator.GetEvent<PortUtilEvent>().Publish(new util.DeviceMsg() _eventAggregator.GetEvent<PortUtilEvent>().Publish(new util.DeviceMsg()
@ -378,6 +413,19 @@ namespace DM_Weight.Port
{ {
// 继续查询抽屉药品数量 // 继续查询抽屉药品数量
// 查询抽屉药品数量 // 查询抽屉药品数量
if (ColNos != null && ColNos.Length > 0 || OpenBoxColNo > 0)
{
//开药盒锁
if (OpenBoxColNo > 0 && (WindowName == "DrawerTakeDrugWindow" || WindowName == "DrawerAddDrugWindow"))
{
//开药盒锁前先查数
int beforeQuantity = await CheckQuantityForSingle(OpenBoxColNo);
BeforeQuantity[OpenBoxColNo - 1] = beforeQuantity;
logger.Info($"BeforeQuantity:{OpenBoxColNo}-{beforeQuantity}数量{string.Join(",", BeforeQuantity)}");
OpenBoxByColNo(OpenBoxColNo);
OpenBoxColNo = 0;
await Task.Delay(TimeSpan.FromMilliseconds(20));
}
int[] quantity = await CheckQuantityByAddr2(); int[] quantity = await CheckQuantityByAddr2();
AfterQuantity = quantity.Select(it => Convert.ToInt32(it)).ToArray(); AfterQuantity = quantity.Select(it => Convert.ToInt32(it)).ToArray();
logger.Info($"AfterQuantity{string.Join(",", AfterQuantity)}"); logger.Info($"AfterQuantity{string.Join(",", AfterQuantity)}");
@ -414,6 +462,11 @@ namespace DM_Weight.Port
Quantitys = Quantitys Quantitys = Quantitys
}); });
logger.Info($"数量变化【{string.Join(",", Quantitys)}】"); logger.Info($"数量变化【{string.Join(",", Quantitys)}】");
}
else
{
logger.Info("无库位,不查数");
}
} }
// 继续监听抽屉状态 // 继续监听抽屉状态
@ -430,16 +483,16 @@ namespace DM_Weight.Port
} }
// 药盒 // 药盒
if (BoardType == (Int32)BoardTypeEnum.box) //if (BoardType == (Int32)BoardTypeEnum.box)
{ //{
// 药盒指示灯失能 // // 药盒指示灯失能
await BoxLockLightOff(); // await BoxLockLightOff();
} //}
if (BoardType == (Int32)BoardTypeEnum.weigh || BoardType == (Int32)BoardTypeEnum.weighSmartBox) //if (BoardType == (Int32)BoardTypeEnum.weigh || BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{ //{
// 药盒指示灯使能 // // 药盒指示灯使能
await BoxLockLightOff2(); // await BoxLockLightOff2();
} //}
string _WindowName = WindowName; string _WindowName = WindowName;
logger.Info($"抽屉【{DrawerNo}】已关闭"); logger.Info($"抽屉【{DrawerNo}】已关闭");
// 重新初始化数据 // 重新初始化数据
@ -706,6 +759,7 @@ namespace DM_Weight.Port
} }
if (_length != length) if (_length != length)
{ {
logger.Info($"串口【{serialPort.PortName}】交互超时;{_length}-{length};{end.Subtract(start).TotalMilliseconds}-{timeout}");
throw new TimeoutException($"串口【{serialPort.PortName}】交互超时"); throw new TimeoutException($"串口【{serialPort.PortName}】交互超时");
} }
serialPort.Read(buffer, 0, length); serialPort.Read(buffer, 0, length);
@ -735,6 +789,9 @@ namespace DM_Weight.Port
// 打开抽屉 // 打开抽屉
public async Task<byte[]> OpenDrawer() public async Task<byte[]> OpenDrawer()
{ {
try
{
logger.Info($"开抽屉");
drawerSerial.DiscardInBuffer(); drawerSerial.DiscardInBuffer();
byte[] buffer = new byte[] { 0xaa, 0x41, (byte)DrawerNo, 0xee }; byte[] buffer = new byte[] { 0xaa, 0x41, (byte)DrawerNo, 0xee };
if (_drawerProtocol == 485) if (_drawerProtocol == 485)
@ -754,8 +811,23 @@ namespace DM_Weight.Port
return await GetBufferByPort(drawerSerial, 11); return await GetBufferByPort(drawerSerial, 11);
} }
catch (Exception ex)
{
logger.Info($"抽屉【{DrawerNo}】打开失败");
// 返回消息 抽屉打开失败
_eventAggregator.GetEvent<PortUtilEvent>().Publish(new util.DeviceMsg()
{
EventType = util.EventType.OPENERROR,
WindowName = WindowName,
Message = $"抽屉【{DrawerNo}】打开失败"
});
// 重新初始化数据
ResetData();
return null;
}
}
private bool DrawerState(int[] r) public bool DrawerState(int[] r)
{ {
int index = DrawerNo > 8 ? DrawerNo - 7 : DrawerNo + 1; int index = DrawerNo > 8 ? DrawerNo - 7 : DrawerNo + 1;
return r[index] == 0; return r[index] == 0;
@ -947,6 +1019,65 @@ namespace DM_Weight.Port
#endregion #endregion
#region #region
//无按钮开药盒
/// <summary>
/// 开指定库位的药盒
/// </summary>
/// <param name="ColNo"></param>
/// <returns></returns>
public async Task<bool> OpenBoxByColNo(int colNo)
{
if (colNo > 0)
{
canBusSerial.DiscardInBuffer();
int ColNo = colNo;
int[] iNum = new int[] { 4, 2, 1 };
var colNo2 = ColNo % 3 > 0 ? (ColNo % 3) - 1 : 2;
var bColNo = iNum[colNo2];
decimal decolNO = (decimal)ColNo;
var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);
byte[] buffer = new byte[] { 0xaa, (byte)channel, 5, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };
//byte[] buffer = new byte[] { 0xaa, 0x11, 0x05,0x01, 0x00,0x00,0x00,0xee};
logger.Info($"开药盒{ColNo}【{Convert.ToHexString(buffer)}】");
canBusSerial.Write(buffer, 0, 8);
byte[] retBuffer = await GetBufferByPort(canBusSerial, 8);
logger.Info($"开药盒返回{ColNo}【{Convert.ToHexString(retBuffer)}】");
int[] r = retBuffer.Select(it => Convert.ToInt32(it)).ToArray();
if (r[4] > 0)
{
return true;
}
else
{
return false;
}
}
return false;
}
/// <summary>
/// 打开药盒
/// </summary>
/// <param name="ColNo"></param>
/// <returns></returns>
public async Task OpenBox()
{
for (int i = 0; i < ColNos.Length; i++)
{
canBusSerial.DiscardInBuffer();
int ColNo = ColNos[i];
int[] iNum = new int[] { 4, 2, 1 };
var colNo2 = ColNo % 3 > 0 ? (ColNo % 3) - 1 : 2;
var bColNo = iNum[colNo2];
decimal decolNO = (decimal)ColNo;
var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);
byte[] buffer = new byte[] { 0xaa, (byte)channel, 5, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };
//byte[] buffer = new byte[] { 0xaa, 0x11, 0x05,0x01, 0x00,0x00,0x00,0xee};
logger.Info($"{Convert.ToHexString(buffer)}");
canBusSerial.Write(buffer, 0, 8);
await Task.Delay(800);
}
}
// 指定药盒指示灯开启使能开锁 // 指定药盒指示灯开启使能开锁
public async Task BoxLockLightOn() public async Task BoxLockLightOn()
{ {
@ -961,6 +1092,8 @@ namespace DM_Weight.Port
} }
// 指定药盒指示灯开启失能开锁 // 指定药盒指示灯开启失能开锁
public async Task BoxLockLightOff() public async Task BoxLockLightOff()
{
if (ColNos != null)
{ {
for (int i = 0; i < ColNos.Length; i++) for (int i = 0; i < ColNos.Length; i++)
{ {
@ -970,6 +1103,7 @@ namespace DM_Weight.Port
await Task.Delay(TimeSpan.FromMilliseconds(20)); await Task.Delay(TimeSpan.FromMilliseconds(20));
} }
} }
}
// 指定药盒状态查询 // 指定药盒状态查询
public async Task<byte[]> BoxLockState(int ColNo) public async Task<byte[]> BoxLockState(int ColNo)
{ {
@ -995,6 +1129,10 @@ namespace DM_Weight.Port
byte[] buffer = new byte[] { 0xaa, (byte)(0xf0 + DrawerNo), 0x05, 0x00, 0x00, 0x00, 0x00, 0xee }; byte[] buffer = new byte[] { 0xaa, (byte)(0xf0 + DrawerNo), 0x05, 0x00, 0x00, 0x00, 0x00, 0xee };
canBusSerial.Write(buffer, 0, 8); canBusSerial.Write(buffer, 0, 8);
} }
#endregion #endregion
private string trim(string text) private string trim(string text)
@ -1048,7 +1186,7 @@ namespace DM_Weight.Port
} }
// 清除显示内容 // 清除显示内容
public void ClearContent(int drawerNo, int colNo) public async Task ClearContent(int drawerNo, int colNo)
{ {
canBusSerial.DiscardInBuffer(); canBusSerial.DiscardInBuffer();
int channel = (drawerNo * 10 + colNo); int channel = (drawerNo * 10 + colNo);
@ -1056,7 +1194,7 @@ namespace DM_Weight.Port
canBusSerial.Write(buffer, 0, 8); canBusSerial.Write(buffer, 0, 8);
} }
// 刷新显示内容 // 刷新显示内容
public void ShowContent(int drawerNo, int colNo) public async Task ShowContent(int drawerNo, int colNo)
{ {
try try
{ {
@ -1129,6 +1267,128 @@ namespace DM_Weight.Port
#endregion
#region
//清屏
public void ClearContentMethod(int drawerNo, int colNo)
{
decimal deColNo = colNo;
//var channel = drawerNo * 10 + Math.Ceiling(deColNo / 3);
int[] iNum = new int[] { 3, 2, 1 };
var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
var bColNo = Convert.ToInt32((iNum[colNo2] + 10).ToString(), 16);
//var index = Convert.ToInt32(((colNo % 3 == 0 ? 3 : colNo % 3)+10).ToString(),16);
int channel = Convert.ToInt32((drawerNo * 10 + Math.Ceiling((decimal)colNo / 3)).ToString(), 16);
byte[] buffer = new byte[] { 0xaa, (byte)channel, 0x09, (byte)bColNo, 0, 0, 0, 0xee };
canBusSerial.Write(buffer, 0, 8);
logger.Info($"清屏指令:{Convert.ToHexString(buffer)}");
}
//刷新内容
public async Task ShowContentMethod(int drawerNo, int colNo)
{
int channel = Convert.ToInt32((drawerNo * 10 + Math.Ceiling((decimal)colNo / 3)).ToString(), 16);
byte[] buffer = new byte[] { 0xaa, (byte)channel, 0x0c, 0x00, 0x00, 0x00, 0x00, 0xee };
logger.Info($"刷新内容指令:{Convert.ToHexString(buffer)}");
canBusSerial.Write(buffer, 0, 8);
}
// 基础数据写入方法
public async Task WriteChannelInfoMethod(int type, string content, int drawerNo, int colNo)
{
try
{
canBusSerial.DiscardInBuffer();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
if (content.Length > 10)
{
content = content.Substring(0, 10);
}
byte[] contentBuf = Encoding.GetEncoding("gb2312").GetBytes(trim(content));
int channel = Convert.ToInt32((drawerNo * 10 + Math.Ceiling((decimal)colNo / 3)).ToString(), 16);
int[] iNum = new int[] { 3, 2, 1 };
var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
var bColNo = iNum[colNo2] + 160;
//var index = (colNo % 3 == 0 ? 3 : colNo % 3)+160;
if (contentBuf.Length % 2 != 0)
{
Array.Resize(ref contentBuf, contentBuf.Length + 1);
}
byte[] buffer = new byte[] { 0xaa, (byte)channel, (byte)bColNo, (byte)type, 0, 0, 0, 0xee };
canBusSerial.Write(buffer, 0, 8);
logger.Info($"开始写标签指令:{Convert.ToHexString(buffer)}");
Thread.Sleep(20);
buffer[4] = 1;
for (int i = 0; i < contentBuf.Length; i += 2)
{
buffer[5] = contentBuf[i];
buffer[6] = contentBuf[i + 1];
canBusSerial.Write(buffer, 0, 8);
logger.Info($"写标签指令:{Convert.ToHexString(buffer)}");
Thread.Sleep(50);
}
buffer[4] = 2;
buffer[5] = 0;
buffer[6] = 0;
canBusSerial.Write(buffer, 0, 8);
logger.Info($"结束写标签指令:{Convert.ToHexString(buffer)}");
Thread.Sleep(20);
}
catch (Exception ex)
{
_eventAggregator.GetEvent<PortUtilEvent>().Publish(new util.DeviceMsg()
{
EventType = util.EventType.OPENERROR,
WindowName = WindowName,
Message = $"2.4寸汉显屏异常{ex.Message}"
});
logger.Info($"2.4寸汉显屏异常ex:{ex.Message}");
}
}
public async Task WriteQuantityMethod(int quantity, int drawerNo, int colNo)
{
try
{
logger.Info($"写数量:{drawerNo}-{colNo}{quantity}");
canBusSerial.DiscardInBuffer();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
string strQuantity = quantity.ToString("X");
if (strQuantity.Length % 2 != 0)
{
strQuantity = "0" + strQuantity;
}
int channel = Convert.ToInt32((drawerNo * 10 + Math.Ceiling((decimal)colNo / 3)).ToString(), 16);
int[] iNum = new int[] { 3, 2, 1 };
var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
var bColNo = iNum[colNo2] + 160;
byte[] buffer = new byte[] { 0xaa, (byte)channel, (byte)bColNo, 0xf2, 01, 0, 0, 0xee };
if (strQuantity.Length >= 4)
{
buffer[5] = Convert.ToByte(strQuantity.Substring(0, 2), 16);
buffer[6] = Convert.ToByte(strQuantity.Substring(2, 2), 16);
}
else
{
buffer[6] = Convert.ToByte(strQuantity.Substring(0, 2), 16);
}
canBusSerial.Write(buffer, 0, 8);
logger.Info($"写标签指令:{Convert.ToHexString(buffer)}");
}
catch (Exception ex)
{
_eventAggregator.GetEvent<PortUtilEvent>().Publish(new util.DeviceMsg()
{
EventType = util.EventType.OPENERROR,
WindowName = WindowName,
Message = $"写标签数量异常{ex.Message}"
});
logger.Info($"写标签数量异常ex:{ex.Message}");
}
}
#endregion #endregion
#region #region
@ -1249,7 +1509,121 @@ namespace DM_Weight.Port
return res; return res;
} }
// 以板子为单位获取抽屉内所有库位的药品数量
public async Task<int[]> CheckQuantityByAddrForMulti()
{
int[] res = new int[9];
for (int i = 0; i < ColNoLst.Count; i++)
{
Thread.Sleep(200);
canBusSerial.DiscardInBuffer();
int colNo = ColNoLst[i];
int[] iNum = new int[] { 3, 2, 1 };
var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
var bColNo = iNum[colNo2];
decimal decolNO = (decimal)colNo;
var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);
byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x27, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };
logger.Info($"称重发送库位数量查询{ColNoLst[i]}【{Convert.ToHexString(buffer)}】");
canBusSerial.Write(buffer, 0, 8);
byte[] result = await GetBufferByPort(canBusSerial, 8);
logger.Info($"称重发送库位数量查询返回结果【{Convert.ToHexString(result)}】");
byte[] hl = result.Skip(4).Take(2).ToArray();
var r = Convert.ToHexString(result).Substring(8, 1);
int quantity = 0;
if (r == "8")
{
hl[0] -= 0x80;
quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
logger.Info($"获取值为负数{quantity}");
quantity = 0 - quantity;
}
else
{
quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
logger.Info($"获取值为正数{quantity}");
}
res[ColNoLst[i] - 1] = quantity;
}
return res;
}
//获取单个称重药合的药品数量 --查数
public async Task<int> CheckQuantityForSingle(int colNo)
{
//await Task.Delay(300);
//canBusSerial.DiscardInBuffer();
//var index = colNo % 3 == 0 ? 3 : colNo % 3;
//var lock1 = colNo <= 3 ? 3 : colNo >= 7 ? 1 : 2;
//var channel = Convert.ToInt32((DrawerNo * 10 + index).ToString(), 16);
canBusSerial.DiscardInBuffer();
int[] iNum = new int[] { 3, 2, 1 };
var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
var bColNo = iNum[colNo2];
decimal decolNO = (decimal)colNo;
var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);
byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x27, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };
logger.Info($"称重发送库位数量查询{colNo}【{Convert.ToHexString(buffer)}】");
canBusSerial.Write(buffer, 0, 8);
byte[] result = await GetBufferByPort(canBusSerial, 8);
byte[] hl = result.Skip(4).Take(2).ToArray();
var r = Convert.ToHexString(result).Substring(8, 1);
logger.Info($"称重发送库位数量查询返回结果【{Convert.ToHexString(result)}】");
if (r == "8")
{
hl[0] -= 0x80;
int quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
logger.Info($"获取值为负数{quantity}");
return 0 - quantity;
}
else
{
int quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
logger.Info($"获取值为正数{quantity}");
return quantity;
}
}
//获取单个称重药合的药品数量---标定
public async Task<int> CheckQuantityForBiaoDing(int colNo)
{
//await Task.Delay(300);
//canBusSerial.DiscardInBuffer();
//var index = colNo % 3 == 0 ? 3 : colNo % 3;
//var lock1 = colNo <= 3 ? 3 : colNo >= 7 ? 1 : 2;
//var channel = Convert.ToInt32((DrawerNo * 10 + index).ToString(), 16);
canBusSerial.DiscardInBuffer();
int[] iNum = new int[] { 3, 2, 1 };
var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
var bColNo = iNum[colNo2];
decimal decolNO = (decimal)colNo;
var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);
byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x27, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };
logger.Info($"称重发送库位数量查询{colNo}【{Convert.ToHexString(buffer)}】");
canBusSerial.Write(buffer, 0, 8);
byte[] result = await GetBufferByPort(canBusSerial, 8);
logger.Info($"称重发送库位数量查询返回结果【{Convert.ToHexString(result)}】");
byte[] hl = result.Skip(4).Take(2).ToArray();
int quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
return quantity;
}
// 以板子为单位获取抽屉内所有库位的药品数量 // 以板子为单位获取抽屉内所有库位的药品数量
public async Task<int[]> CheckQuantityByAddr2() public async Task<int[]> CheckQuantityByAddr2()
{ {
@ -1258,20 +1632,39 @@ namespace DM_Weight.Port
int[] res = new int[9]; int[] res = new int[9];
for (int i = 0; i < ColNos.Length; i++) for (int i = 0; i < ColNos.Length; i++)
{ {
await Task.Delay(300);
canBusSerial.DiscardInBuffer(); canBusSerial.DiscardInBuffer();
//var index = (int)Math.Ceiling(Convert.ToDecimal(ColNos[i]) / 3); // > 3 ? 2 : 1; int colNo = ColNos[i];
//var lock1 = ColNos[i] % 3 == 0 ? 3 : ColNos[i] % 3; int[] iNum = new int[] { 3, 2, 1 };
var index = ColNos[i] % 3 == 0 ? 3 : ColNos[i] % 3; var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
var lock1 = ColNos[i] <= 3 ? 3 : ColNos[i] >= 7 ? 1 : 2; var bColNo = iNum[colNo2];
var channel = Convert.ToInt32((DrawerNo * 10 + index).ToString(), 16); decimal decolNO = (decimal)colNo;
byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x27, (byte)lock1, 0x00, 0x00, 0x00, 0xee }; var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);
logger.Info($"称重发送库位数量查询1【{Convert.ToHexString(buffer)}】"); byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x27, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };
logger.Info($"称重发送库位数量查询{ColNos[i]}【{Convert.ToHexString(buffer)}】");
canBusSerial.Write(buffer, 0, 8); canBusSerial.Write(buffer, 0, 8);
byte[] result = await GetBufferByPort(canBusSerial, 8); byte[] result = await GetBufferByPort(canBusSerial, 8);
logger.Info($"称重发送库位数量查询1返回结果【{Convert.ToHexString(result)}】"); logger.Info($"称重发送库位数量查询返回结果【{Convert.ToHexString(result)}】");
byte[] hl = result.Skip(4).Take(2).ToArray(); byte[] hl = result.Skip(4).Take(2).ToArray();
int quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0); //int quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
var r = Convert.ToHexString(result).Substring(8, 1);
int quantity = 0;
if (r == "8")
{
hl[0] -= 0x80;
quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
logger.Info($"获取值为负数{quantity}");
quantity = 0 - quantity;
}
else
{
quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
logger.Info($"获取值为正数{quantity}");
}
res[ColNos[i] - 1] = quantity; res[ColNos[i] - 1] = quantity;
} }
@ -1284,13 +1677,13 @@ namespace DM_Weight.Port
{ {
for (int i = 0; i < ColNos.Length; i++) for (int i = 0; i < ColNos.Length; i++)
{ {
//var index = ColNos[i] > 3 ? 2 : 1; int colNo = ColNos[i];
//var lock1 = ColNos[i] % 3 == 0 ? 3 : ColNos[i] % 3; int[] iNum = new int[] { 3, 2, 1 };
//var index = (int)Math.Ceiling(Convert.ToDecimal(ColNos[i]) / 3); var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
var index = ColNos[i] % 3 == 0 ? 3 : ColNos[i] % 3; var bColNo = iNum[colNo2];
var lock1 = ColNos[i] <= 3 ? 4 : ColNos[i] >= 7 ? 1 : 2; decimal decolNO = (decimal)colNo;
var channel = Convert.ToInt32((DrawerNo * 10 + index).ToString(), 16); var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);
byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x03, (byte)lock1, 0x00, 0x00, 0x00, 0xee }; byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x03, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };
logger.Info($"称重发送药盒使能【{Convert.ToHexString(buffer)}】"); logger.Info($"称重发送药盒使能【{Convert.ToHexString(buffer)}】");
canBusSerial.Write(buffer, 0, 8); canBusSerial.Write(buffer, 0, 8);
await Task.Delay(TimeSpan.FromMilliseconds(500)); await Task.Delay(TimeSpan.FromMilliseconds(500));
@ -1302,31 +1695,30 @@ namespace DM_Weight.Port
canBusSerial.DiscardInBuffer(); canBusSerial.DiscardInBuffer();
for (int i = 0; i < ColNos.Length; i++) for (int i = 0; i < ColNos.Length; i++)
{ {
//var index = ColNos[i] > 3 ? 2 : 1; int colNo = ColNos[i];
//var lock1 = ColNos[i] % 3 == 0 ? 3 : ColNos[i] % 3; int[] iNum = new int[] { 3, 2, 1 };
//var index = (int)Math.Ceiling(Convert.ToDecimal(ColNos[i]) / 3); var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
var index = ColNos[i] % 3 == 0 ? 3 : ColNos[i] % 3; var bColNo = iNum[colNo2];
var lock1 = ColNos[i] <= 3 ? 4 : ColNos[i] >= 7 ? 1 : 2; decimal decolNO = (decimal)colNo;
var channel = Convert.ToInt32((DrawerNo * 10 + index).ToString(), 16); var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);
byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x04, (byte)lock1, 0x00, 0x00, 0x00, 0xee }; byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x04, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };
logger.Info($"称重发送药盒失能【{Convert.ToHexString(buffer)}】"); logger.Info($"称重发送药盒失能【{Convert.ToHexString(buffer)}】");
canBusSerial.Write(buffer, 0, 8); canBusSerial.Write(buffer, 0, 8);
await Task.Delay(TimeSpan.FromMilliseconds(50)); await Task.Delay(TimeSpan.FromMilliseconds(50));
} }
} }
//计数请零 //计数请零
public async void ClearCount(int DrawerNo, int ColNo) public async Task ClearCount(int DrawerNo, int ColNo)
{ {
try try
{ {
canBusSerial.DiscardInBuffer(); canBusSerial.DiscardInBuffer();
//var index = ColNo > 3 ? 2 : 1; int[] iNum = new int[] { 3, 2, 1 };
//var lock1 = ColNo % 3 == 0 ? 3 : ColNo % 3; var colNo2 = ColNo % 3 > 0 ? (ColNo % 3) - 1 : 2;
//var index = (int)Math.Ceiling(Convert.ToDecimal(ColNo) / 3); var bColNo = iNum[colNo2];
var index = ColNo % 3 == 0 ? 3 : ColNo % 3; decimal decolNO = (decimal)ColNo;
var lock1 = ColNo <= 3 ? 3 : ColNo >= 7 ? 1 : 2; var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);
var channel = Convert.ToInt32((DrawerNo * 10 + index).ToString(), 16); byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x25, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };
byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x25, (byte)lock1, 0x00, 0x00, 0x00, 0xee };
logger.Info($"称重发送清空计数【{Convert.ToHexString(buffer)}】"); logger.Info($"称重发送清空计数【{Convert.ToHexString(buffer)}】");
canBusSerial.Write(buffer, 0, 8); canBusSerial.Write(buffer, 0, 8);
@ -1344,18 +1736,17 @@ namespace DM_Weight.Port
} }
public async void SetNumCount(int DrawerNo, int ColNo, int Quantity) public async Task SetNumCount(int DrawerNo, int ColNo, int Quantity)
{ {
try try
{ {
canBusSerial.DiscardInBuffer(); canBusSerial.DiscardInBuffer();
//var index = ColNo > 3 ? 2 : 1; int[] iNum = new int[] { 3, 2, 1 };
//var lock1 = ColNo % 3 == 0 ? 3 : ColNo % 3; var colNo2 = ColNo % 3 > 0 ? (ColNo % 3) - 1 : 2;
//var index = (int)Math.Ceiling(Convert.ToDecimal(ColNo) / 3); var bColNo = iNum[colNo2];
var index = ColNo % 3 == 0 ? 3 : ColNo % 3; decimal decolNO = (decimal)ColNo;
var lock1 = ColNo <= 3 ? 3 : ColNo >= 7 ? 1 : 2; var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);
var channel = Convert.ToInt32((DrawerNo * 10 + index).ToString(), 16); byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x26, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };
byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x26, (byte)lock1, 0x00, 0x00, 0x00, 0xee };
buffer[4] = (byte)(Quantity & 0xff); buffer[4] = (byte)(Quantity & 0xff);
//buffer[4] = (byte)(Quantity >> 8); //buffer[4] = (byte)(Quantity >> 8);
@ -1606,6 +1997,44 @@ namespace DM_Weight.Port
} }
return temperature; return temperature;
} }
//读制冷片温度
public async Task<float> GetFridgeTemperature2()
{
float temperature = 0.0f;
try
{
fridgeSerial.DiscardInBuffer();
byte bAddress;
byte[] buffer = new byte[] { 0x01, 0x03, 0x10, 0x0C, 0x00, 0x01, 0x40, 0xC9 };
//byte[] buffer = new byte[] { 0x01, 0x03, 0x10, 0x02, 0x00, 0x01 };
////获取数组CRC校验码
//byte[] byteDate = CRC16MODBUS.CrcModBus(buffer);
////Array.Reverse(byteDate);
//int dataLength = buffer.Length;
//Array.Resize(ref buffer, dataLength + byteDate.Length);
//for (int i = 0; i < byteDate.Length; i++)
//{
// buffer[dataLength + i] = byteDate[i];
//}
logger.Info($"获制冷片温度【{Convert.ToHexString(buffer)}】");
fridgeSerial.Write(buffer, 0, 8);
byte[] retByte = await GetBufferByPort(fridgeSerial, 7);
logger.Info($"获取制冷片温度返回【{Convert.ToHexString(retByte)}】");
if (retByte != null && retByte.Length >= 7)
{
var hight = retByte[3];
var low = retByte[4];
int iHight = Convert.ToInt32(hight << 8);
int iLow = Convert.ToInt32(retByte[4]);
temperature = Convert.ToSingle(iHight + iLow) / 10;
}
}
catch (Exception ex)
{
logger.Info($"获取制冷片温度发生异常ex:{ex.Message}");
}
return temperature;
}
/// <summary> /// <summary>
/// 设置冰箱温度 /// 设置冰箱温度
/// </summary> /// </summary>
@ -1681,5 +2110,28 @@ namespace DM_Weight.Port
#endregion #endregion
#endregion #endregion
//标定获取药盒数量
private byte[] GetBufferByPortForBiaoDing(SerialPort serialPort, int length, int timeout)
{
byte[] buffer = new byte[length];
int _length = 0;
DateTime start = DateTime.Now;
DateTime end = DateTime.Now;
while (_length != length && end.Subtract(start).TotalMilliseconds < timeout)
{
_length = serialPort.BytesToRead;
end = DateTime.Now;
}
if (_length != length)
{
//throw new TimeoutException($"串口【{serialPort.PortName}】交互超时");
//_length = serialPort.BytesToRead;
//end = DateTime.Now;
//logger.Info($"读到数据{}");
}
serialPort.Read(buffer, 0, length);
return buffer;
}
} }
} }

View File

@ -1,5 +1,5 @@
{ {
"Version":"6.3.0.1", "Version":"6.8.1.1",
"Font":{ "Font":{
"Name":"宋体", "Name":"宋体",
"Size":105000, "Size":105000,
@ -116,14 +116,6 @@
"Name":"操作类型", "Name":"操作类型",
"Width":2.19604 "Width":2.19604
}, },
{
"Name":"批号",
"Width":3.99521
},
{
"Name":"有效期",
"Width":2.43417
},
{ {
"Name":"入库数量", "Name":"入库数量",
"Width":1.79917 "Width":1.79917
@ -173,16 +165,6 @@
} }
] ]
}, },
{
"Column":"批号",
"TextAlign":"MiddleCenter",
"DataField":"批号"
},
{
"Column":"有效期",
"TextAlign":"MiddleCenter",
"DataField":"有效期"
},
{ {
"Column":"入库数量", "Column":"入库数量",
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
@ -280,30 +262,6 @@
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"Text":"凭证号" "Text":"凭证号"
}, },
{
"GroupTitle":false,
"Column":"批号",
"Font":{
"Name":"宋体",
"Size":105000,
"Bold":true,
"Charset":134
},
"TextAlign":"MiddleCenter",
"Text":"批号"
},
{
"GroupTitle":false,
"Column":"有效期",
"Font":{
"Name":"宋体",
"Size":105000,
"Bold":true,
"Charset":134
},
"TextAlign":"MiddleCenter",
"Text":"有效\r\n期"
},
{ {
"GroupTitle":false, "GroupTitle":false,
"Column":"入库数量", "Column":"入库数量",

View File

@ -1,5 +1,5 @@
{ {
"Version":"6.3.0.1", "Version":"6.8.1.1",
"Font":{ "Font":{
"Name":"宋体", "Name":"宋体",
"Size":105000, "Size":105000,
@ -76,14 +76,6 @@
"Name":"数量", "Name":"数量",
"Width":1.98438 "Width":1.98438
}, },
{
"Name":"批次",
"Width":2.61938
},
{
"Name":"效期",
"Width":2.38125
},
{ {
"Name":"库位", "Name":"库位",
"Width":2.59292 "Width":2.59292
@ -112,16 +104,6 @@
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"DataField":"数量" "DataField":"数量"
}, },
{
"Column":"批次",
"TextAlign":"MiddleCenter",
"DataField":"批次"
},
{
"Column":"效期",
"TextAlign":"MiddleCenter",
"DataField":"效期"
},
{ {
"Column":"库位", "Column":"库位",
"FreeCell":true, "FreeCell":true,
@ -198,30 +180,6 @@
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"Text":"数量" "Text":"数量"
}, },
{
"GroupTitle":false,
"Column":"批次",
"Font":{
"Name":"宋体",
"Size":120000,
"Bold":true,
"Charset":134
},
"TextAlign":"MiddleCenter",
"Text":"批次"
},
{
"GroupTitle":false,
"Column":"效期",
"Font":{
"Name":"宋体",
"Size":120000,
"Bold":true,
"Charset":134
},
"TextAlign":"MiddleCenter",
"Text":"效期"
},
{ {
"GroupTitle":false, "GroupTitle":false,
"Column":"库位", "Column":"库位",

View File

@ -1,5 +1,5 @@
{ {
"Version":"6.3.0.1", "Version":"6.8.1.1",
"Font":{ "Font":{
"Name":"宋体", "Name":"宋体",
"Size":105000, "Size":105000,
@ -76,14 +76,6 @@
"Name":"数量", "Name":"数量",
"Width":1.98438 "Width":1.98438
}, },
{
"Name":"批次",
"Width":2.61938
},
{
"Name":"效期",
"Width":2.38125
},
{ {
"Name":"库位", "Name":"库位",
"Width":2.59292 "Width":2.59292
@ -112,16 +104,6 @@
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"DataField":"数量" "DataField":"数量"
}, },
{
"Column":"批次",
"TextAlign":"MiddleCenter",
"DataField":"批次"
},
{
"Column":"效期",
"TextAlign":"MiddleCenter",
"DataField":"效期"
},
{ {
"Column":"库位", "Column":"库位",
"FreeCell":true, "FreeCell":true,
@ -198,30 +180,6 @@
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"Text":"数量" "Text":"数量"
}, },
{
"GroupTitle":false,
"Column":"批次",
"Font":{
"Name":"宋体",
"Size":120000,
"Bold":true,
"Charset":134
},
"TextAlign":"MiddleCenter",
"Text":"批次"
},
{
"GroupTitle":false,
"Column":"效期",
"Font":{
"Name":"宋体",
"Size":120000,
"Bold":true,
"Charset":134
},
"TextAlign":"MiddleCenter",
"Text":"效期"
},
{ {
"GroupTitle":false, "GroupTitle":false,
"Column":"库位", "Column":"库位",

View File

@ -1,5 +1,5 @@
{ {
"Version":"6.3.0.1", "Version":"6.8.1.1",
"Font":{ "Font":{
"Name":"宋体", "Name":"宋体",
"Size":105000, "Size":105000,
@ -76,14 +76,6 @@
"Name":"数量", "Name":"数量",
"Width":1.98438 "Width":1.98438
}, },
{
"Name":"批次",
"Width":2.61938
},
{
"Name":"效期",
"Width":2.38125
},
{ {
"Name":"库位", "Name":"库位",
"Width":2.59292 "Width":2.59292
@ -112,16 +104,6 @@
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"DataField":"数量" "DataField":"数量"
}, },
{
"Column":"批次",
"TextAlign":"MiddleCenter",
"DataField":"批次"
},
{
"Column":"效期",
"TextAlign":"MiddleCenter",
"DataField":"效期"
},
{ {
"Column":"库位", "Column":"库位",
"FreeCell":true, "FreeCell":true,
@ -198,30 +180,6 @@
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"Text":"数量" "Text":"数量"
}, },
{
"GroupTitle":false,
"Column":"批次",
"Font":{
"Name":"宋体",
"Size":120000,
"Bold":true,
"Charset":134
},
"TextAlign":"MiddleCenter",
"Text":"批次"
},
{
"GroupTitle":false,
"Column":"效期",
"Font":{
"Name":"宋体",
"Size":120000,
"Bold":true,
"Charset":134
},
"TextAlign":"MiddleCenter",
"Text":"效期"
},
{ {
"GroupTitle":false, "GroupTitle":false,
"Column":"库位", "Column":"库位",

View File

@ -1,5 +1,5 @@
{ {
"Version":"6.3.0.1", "Version":"6.8.1.1",
"Font":{ "Font":{
"Name":"宋体", "Name":"宋体",
"Size":105000, "Size":105000,
@ -76,14 +76,6 @@
"Name":"数量", "Name":"数量",
"Width":1.98438 "Width":1.98438
}, },
{
"Name":"批次",
"Width":2.61938
},
{
"Name":"效期",
"Width":2.38125
},
{ {
"Name":"库位", "Name":"库位",
"Width":2.59292 "Width":2.59292
@ -112,16 +104,6 @@
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"DataField":"数量" "DataField":"数量"
}, },
{
"Column":"批次",
"TextAlign":"MiddleCenter",
"DataField":"批次"
},
{
"Column":"效期",
"TextAlign":"MiddleCenter",
"DataField":"效期"
},
{ {
"Column":"库位", "Column":"库位",
"FreeCell":true, "FreeCell":true,
@ -198,30 +180,6 @@
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"Text":"数量" "Text":"数量"
}, },
{
"GroupTitle":false,
"Column":"批次",
"Font":{
"Name":"宋体",
"Size":120000,
"Bold":true,
"Charset":134
},
"TextAlign":"MiddleCenter",
"Text":"批次"
},
{
"GroupTitle":false,
"Column":"效期",
"Font":{
"Name":"宋体",
"Size":120000,
"Bold":true,
"Charset":134
},
"TextAlign":"MiddleCenter",
"Text":"效期"
},
{ {
"GroupTitle":false, "GroupTitle":false,
"Column":"库位", "Column":"库位",

View File

@ -1,5 +1,5 @@
{ {
"Version":"6.3.0.1", "Version":"6.8.1.1",
"Font":{ "Font":{
"Name":"宋体", "Name":"宋体",
"Size":105000, "Size":105000,
@ -70,12 +70,6 @@
"Name":"quantityCount", "Name":"quantityCount",
"Width":2.59292 "Width":2.59292
}, },
{
"Name":"manuNo"
},
{
"Name":"effDate"
},
{ {
"Name":"quantity", "Name":"quantity",
"Width":2.43417 "Width":2.43417
@ -107,16 +101,6 @@
"Column":"quantityCount", "Column":"quantityCount",
"FreeCell":true "FreeCell":true
}, },
{
"Column":"manuNo",
"TextAlign":"MiddleCenter",
"DataField":"manuNo"
},
{
"Column":"effDate",
"TextAlign":"MiddleCenter",
"DataField":"effDate"
},
{ {
"Column":"quantity", "Column":"quantity",
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
@ -188,30 +172,6 @@
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"Text":"总库存" "Text":"总库存"
}, },
{
"GroupTitle":false,
"Column":"manuNo",
"Font":{
"Name":"宋体",
"Size":142500,
"Bold":true,
"Charset":134
},
"TextAlign":"MiddleCenter",
"Text":"批次"
},
{
"GroupTitle":false,
"Column":"effDate",
"Font":{
"Name":"宋体",
"Size":142500,
"Bold":true,
"Charset":134
},
"TextAlign":"MiddleCenter",
"Text":"效期"
},
{ {
"GroupTitle":false, "GroupTitle":false,
"Column":"quantity", "Column":"quantity",
@ -253,7 +213,7 @@
"Type":"MemoBox", "Type":"MemoBox",
"Name":"MemoBox3", "Name":"MemoBox3",
"AlignColumn":"drugName", "AlignColumn":"drugName",
"Width":5.3975, "Width":5.34458,
"Height":1.19063, "Height":1.19063,
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"Text":"[#drugName#]" "Text":"[#drugName#]"
@ -263,7 +223,7 @@
"Name":"MemoBox4", "Name":"MemoBox4",
"AlignColumn":"drugSpec", "AlignColumn":"drugSpec",
"Left":5.37104, "Left":5.37104,
"Width":3.01625, "Width":2.96333,
"Height":1.19063, "Height":1.19063,
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"Text":"[#drugSpec#]" "Text":"[#drugSpec#]"
@ -273,7 +233,7 @@
"Name":"MemoBox5", "Name":"MemoBox5",
"AlignColumn":"manuFactory", "AlignColumn":"manuFactory",
"Left":8.36083, "Left":8.36083,
"Width":4.63021, "Width":4.57729,
"Height":1.19063, "Height":1.19063,
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"Text":"[#manuFactory#]" "Text":"[#manuFactory#]"
@ -283,7 +243,7 @@
"Name":"MemoBox6", "Name":"MemoBox6",
"AlignColumn":"Column1", "AlignColumn":"Column1",
"Left":12.9646, "Left":12.9646,
"Width":3.01625, "Width":2.96333,
"Height":1.19063, "Height":1.19063,
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"Text":"[#baseQuantity#]" "Text":"[#baseQuantity#]"
@ -293,7 +253,7 @@
"Name":"SummaryBox1", "Name":"SummaryBox1",
"AlignColumn":"quantityCount", "AlignColumn":"quantityCount",
"Left":15.9544, "Left":15.9544,
"Width":2.61938, "Width":2.56646,
"Height":1.19063, "Height":1.19063,
"TextAlign":"MiddleCenter", "TextAlign":"MiddleCenter",
"DataField":"quantity", "DataField":"quantity",
@ -326,7 +286,7 @@
"Type":"StaticBox", "Type":"StaticBox",
"Name":"StaticBox1", "Name":"StaticBox1",
"Center":"Horizontal", "Center":"Horizontal",
"Left":8.89, "Left":7.77875,
"Top":0.608542, "Top":0.608542,
"Width":9.18104, "Width":9.18104,
"Height":1.21708, "Height":1.21708,

View File

@ -18,6 +18,7 @@ using System.Drawing.Printing;
using System.Linq; using System.Linq;
using System.Reflection.PortableExecutable; using System.Reflection.PortableExecutable;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Documents; using System.Windows.Documents;
@ -356,7 +357,8 @@ namespace DM_Weight.ViewModels
{ {
singleChannels.ForEach(it => singleChannels.ForEach(it =>
{ {
_portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.Quantity + it.AddQuantity); _portUtil.WriteQuantityMethod( it.Quantity + it.AddQuantity,it.DrawerNo, it.ColNo);
Thread.Sleep(200);
}); });
} }
RequestData(); RequestData();

View File

@ -0,0 +1,426 @@
using DM_Weight.Common;
using DM_Weight.Models;
using DM_Weight.msg;
using DM_Weight.Port;
using DM_Weight.util;
using log4net;
using log4net.Repository.Hierarchy;
using MaterialDesignThemes.Wpf;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
namespace DM_Weight.ViewModels
{
public class BiaoDingDialogViewModel : BindableBase, IDialogAware, IRegionMemberLifetime
{
private readonly ILog logger = LogManager.GetLogger(typeof(BiaoDingWindowViewModel));
public string Title => "标定";
public bool KeepAlive => false;
private string titleStr;
public string TitleStr
{
get => titleStr;
set { SetProperty(ref titleStr, value); }
}
private ChannelStock channelStock;
private string WindowName = "BiaoDingDialog";
private string strMessage;
public string StrMessage
{
get => strMessage;
set => SetProperty(ref strMessage, value);
}
private int _status = 0;
public int Status { get => _status; set => SetProperty(ref _status, value); }
private SolidColorBrush _colorBrush;
public SolidColorBrush SnackbarBackground
{
get => _colorBrush;
set => SetProperty(ref _colorBrush, value);
}
private ISnackbarMessageQueue _snackbarMessageQueue = new SnackbarMessageQueue(TimeSpan.FromSeconds(3));
public ISnackbarMessageQueue SnackbarMessageQueue
{
get => _snackbarMessageQueue;
set => SetProperty(ref _snackbarMessageQueue, value);
}
//标定数量
private int _bdQuantity = 0;
public int BDQuantity
{
get => _bdQuantity;
set => SetProperty(ref _bdQuantity, value);
}
/// <summary>
/// 标定按钮是否可用
/// </summary>
private bool _biaoDingEnable = true;
public bool BiaoDingEnable
{
get => _biaoDingEnable; set
{
SetProperty(ref _biaoDingEnable, value);
}
}
//关闭按钮是否可用
private bool _closeIsEnable = true;
public bool CloseIsEnable
{
get => _closeIsEnable;
set
{
SetProperty(ref _closeIsEnable, value);
}
}
public event Action<IDialogResult> RequestClose;
public bool CanCloseDialog()
{
return true;
}
public void OnDialogClosed()
{
// 取消消息订阅
//_eventAggregator.GetEvent<PortUtilEvent>().Unsubscribe(DoMyPrismEvent);
}
public void OnDialogOpened(IDialogParameters parameters)
{
//_eventAggregator.GetEvent<PortUtilEvent>().Subscribe(DoMyPrismEvent);
channelStock = parameters.GetValue<ChannelStock>("channelStock");
if (channelStock != null)
{
TitleStr = $"正在标定{channelStock.ColNo}号库位";
BiaoDingEnable = false;
if (channelStock.Quantity > 0)
{
StrMessage = "库位库存不为零,请取出药品后点击【清空】按钮,清空完成后输入标定数量并放入对应数量药品并根据下一步提示操作";
_portUtil.SpeakAsync("请取出药品后点击【清空】按钮,清空完成后放入药品输入标定数量点击标定按钮");
}
else
{
Status = 1;
StrMessage = "正在清零,清零完成后输入标定数量并放入对应数量药品后点击【标定】按钮";
_portUtil.SpeakAsync("清零完成后输入数量并放入对应数量药品后点击【标定】按钮");
ClearMethod();
}
}
}
private PortUtil _portUtil;
IEventAggregator _eventAggregator;
public BiaoDingDialogViewModel(PortUtil portUtil, IEventAggregator eventAggregator)
{
_portUtil = portUtil;
_eventAggregator = eventAggregator;
}
//void DoMyPrismEvent(DeviceMsg msg)
//{
// if (msg.WindowName.Equals(WindowName))
// {
// IGrouping<int, ChannelStock> grouping = enumerator.Current;
// int DrawerNo = grouping.Key;
// List<ChannelStock> channelStocks = grouping.ToList();
// switch (msg.EventType)
// {
// // 抽屉打开
// case EventType.DRAWEROPEN:
// if (Status == 1)
// {
// if (channelStocks[0].process == 1)
// {
// channelStocks.ForEach(it => it.process = 2);
// }
// }
// //是冰箱抽屉则开冰箱抽屉时发送延迟报警指令
// CheckIsFridgeOpen();
// break;
// // 抽屉关闭
// case EventType.DRAWERCLOSE:
// if (Status == 1)
// {
// if (channelStocks[0].process == 2)
// {
// channelStocks.ForEach(it => it.process = 3);
// }
// IGrouping<int, ChannelStock> groupingBefore = enumerator.Current;
// int DrawerNoBefore = groupingBefore.Key;
// if (enumerator.MoveNext())
// {
// IGrouping<int, ChannelStock> 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($"抽屉【{DrawerNo}】库位药品数量【{msg.Quantitys}】");
// }
// break;
// // 打开失败
// case EventType.OPENERROR:
// AlertMsg alertMsg = new AlertMsg
// {
// Message = msg.Message,
// Type = MsgType.ERROR
// };
// _eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
// Status = 0;
// break;
// }
// }
//}
//标定
public DelegateCommand BiaoDingCommand
{
get => new DelegateCommand(async () =>
{
if (BDQuantity <= 0)
{
AlertMsg alertMsg = new AlertMsg
{
Message = "请输入标定数量",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
return;
}
try
{
if (Status == 3)
{
CloseIsEnable = false;
//提示输入标定数量发26指令
await _portUtil.SetNumCount(channelStock.DrawerNo, channelStock.ColNo, BDQuantity);
Status = 4;
Thread.Sleep(200);
_portUtil.DrawerNo = channelStock.DrawerNo;
//发27指令查询数量是否写标定时写入的数量一致一致则标定成功不一致则标定失败
int stock = await _portUtil.CheckQuantityForBiaoDing(channelStock.ColNo);
if (!(stock == BDQuantity))
{
int i = 1;
while (i <= 50 && i > 0 && Status > 0)
{
try
{
Thread.Sleep(200);
stock = await _portUtil.CheckQuantityForBiaoDing(channelStock.ColNo);
if (stock == BDQuantity)
{
logger.Info($"标定完成{stock}{BDQuantity},次数{i}"); //标定成功
AlertMsg alertMsg = new AlertMsg
{
Message = "标定成功",
Type = MsgType.SUCCESS,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
i = 0;
// 更新数据 标定状态
channelStock.PosNo = 1;
SqlSugarHelper.Db.Updateable<ChannelStock>(channelStock).UpdateColumns(it => it.PosNo).ExecuteCommand();
}
else
{
i++;
logger.Info($"标定数量不一致{stock}{BDQuantity},次数{i}");
}
}
catch (Exception ex)
{
logger.Error($"标定存在异常{ex.Message}");
continue;
}
}
RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel));
if (i == 51)
{
AlertMsg alertMsg = new AlertMsg
{
Message = "标定失败",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
}
else
{
//标定成功
AlertMsg alertMsg = new AlertMsg
{
Message = "标定成功",
Type = MsgType.SUCCESS,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
logger.Info($"标定完成{stock}{BDQuantity}");
}
CloseIsEnable = true;
}
}
catch (Exception e)
{
logger.Error($"标定异常{e.Message}");
AlertMsg alertMsg = new AlertMsg
{
Message = "标定失败",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
});
}
//清零
public DelegateCommand ClearCommand
{
get => new DelegateCommand(async () =>
{
////发计数请零指令
//await _portUtil.ClearCount(channelStock.DrawerNo, channelStock.ColNo);
//Status = 3;
//Thread.Sleep(300);
////发查数指令
//_portUtil.DrawerNo = channelStock.DrawerNo;
//int stock = await _portUtil.CheckQuantityForBiaoDing(channelStock.ColNo);
//if (stock != 0)
//{
// SnackbarBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#00e676"));
// SnackbarMessageQueue.Enqueue("清零成功");
// BiaoDingEnable = true;
//}
//else
//{
// SnackbarBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#f44336"));
// SnackbarMessageQueue.Enqueue("清零失败");
//}
//_portUtil.ResetData();
Status = 1;
ClearMethod();
});
}
//取消
public DelegateCommand CancelCommand
{
get => new DelegateCommand(() =>
{
logger.Info("取消");
Status = 0;
});
}
//关闭
public DelegateCommand BtnCloseCommand
{
get => new DelegateCommand(() =>
{
logger.Info("关闭窗口");
Status = 0;
RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel));
});
}
private void ClearMethod()
{
int i = 0;
int iClear = 0;
new PromiseUtil<int>().taskAsyncLoop(200, 0, async (options, next, stop) =>
{
i++;
if (Status == 0 || i > 20)
{
System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{
SnackbarBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#f44336"));
SnackbarMessageQueue.Enqueue("清零失败,请重试操作");
}));
stop();
}
else
{
try
{
if (iClear == 0)
{
logger.Info($"清零操作{i}");
//无库存发送计数清零指令
await _portUtil.ClearCount(channelStock.DrawerNo, channelStock.ColNo);
iClear += 1;
next();
}
else
{
logger.Info($"查数操作{i}");
//发查数指令
_portUtil.DrawerNo = channelStock.DrawerNo;
_portUtil.Operate = true;
int stock = await _portUtil.CheckQuantityForBiaoDing(channelStock.ColNo);
if (stock != 0)
{
stop();
System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{
SnackbarBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#00e676"));
SnackbarMessageQueue.Enqueue("清零成功");
}));
BiaoDingEnable = true;
_portUtil.ResetData();
Status = 3;
}
else
{
next();
}
}
}
catch (Exception e)
{
logger.Error($"清零异常{e.Message}");
next();
}
}
});
}
}
}

View File

@ -39,7 +39,7 @@ namespace DM_Weight.ViewModels
} }
} }
//状态,抽屉下的库位有库存为0的则可标定否则不可标定 //状态,抽屉下的库位有库存为0的则可标定否则不可标定
private int _status; private int _status=0;
public int Status { get => _status; set => SetProperty(ref _status, value); } public int Status { get => _status; set => SetProperty(ref _status, value); }
//凭证号 //凭证号
private string _pzh; private string _pzh;
@ -65,6 +65,13 @@ namespace DM_Weight.ViewModels
private static readonly DateTime Jan1st1970 = new DateTime private static readonly DateTime Jan1st1970 = new DateTime
(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private bool _openBoxVisibility = false;
public bool OpenBoxVisibility
{
get => _openBoxVisibility;
set => SetProperty(ref _openBoxVisibility, value);
}
private PortUtil _portUtil; private PortUtil _portUtil;
IEventAggregator _eventAggregator; IEventAggregator _eventAggregator;
IDialogService _dialogService; IDialogService _dialogService;
@ -74,68 +81,12 @@ namespace DM_Weight.ViewModels
_portUtil = portUtil; _portUtil = portUtil;
_eventAggregator = eventAggregator; _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) private void DoDialogResult(IDialogResult dialogResult)
{ {
CStock = null; CStock = null;
Status = 0;
RequestData(); 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]); private int _drawerNo = Convert.ToInt32(ConfigurationManager.AppSettings["WeightDrawerNumber"].Split(',')[0]);
@ -157,316 +108,164 @@ namespace DM_Weight.ViewModels
private bool _is17Drawer = false; private bool _is17Drawer = false;
public bool Is17Drawer { get => _is17Drawer; set => SetProperty(ref _is17Drawer, value); } public bool Is17Drawer { get => _is17Drawer; set => SetProperty(ref _is17Drawer, value); }
public DelegateCommand<string> UpdateDrawerNo public DelegateCommand<string> UpdateDrawerNo
{ {
get => new DelegateCommand<string>((DrawerNo) => get => new DelegateCommand<string>((DrawerNo) =>
{ {
//BtnStatus = 0;
this.DrawerNo = Convert.ToInt32(DrawerNo); this.DrawerNo = Convert.ToInt32(DrawerNo);
RequestData(); RequestData();
}); }, (DrawerNo) => Status == 0
}
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() //打开抽屉
public DelegateCommand OpenDrawer
{ {
_portUtil.Operate = true; get => new DelegateCommand(async () =>
OpenDrawerMethodAction();
}
private async void OpenDrawerMethodAction()
{ {
try try
{ {
if (_portUtil.Operate) if (Status == 0)
{ {
List<ChannelStock> singleChannels = ChannelStocks.ToList().FindAll(it => it.BoardType == (Int32)BoardTypeEnum.weighBox && it.PosNo == 0 && it.Quantity == 0 && it.AddQuantity > 0); _portUtil.Operate = true;
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.DrawerNo = DrawerNo;
//_portUtil.Start(); _portUtil.SpeakAsync("正在打开" + DrawerNo + "号抽屉");
byte[] buffer = await _portUtil.OpenDrawer(); byte[] buffer = await _portUtil.OpenDrawer();
int[] r = buffer.Select(it => Convert.ToInt32(it)).ToArray(); int[] r = buffer.Select(it => Convert.ToInt32(it)).ToArray();
logger.Info($"OpenDrawer{string.Join(",", r)}"); logger.Info($"OpenDrawer{string.Join(",", r)}");
if (DrawerState(r)) if (DrawerState(r))
{ {
_portUtil.BoxLockLightOn2(); new PromiseUtil<int>().taskAsyncLoop(200, 0, async (options, next, stop) =>
{
Status = 1;
// 查询抽屉状态
_portUtil.Operate = true;
byte[] buffer = await _portUtil.CheckDrawerStatus();
int[] r = buffer.Select(it => Convert.ToInt32(it)).ToArray();
if (DrawerState(r))
{
Status = 2;
next();
} }
Status = 3;
}
else else
{ {
_isFinishClick = false; Status = 0;
//关闭抽屉
logger.Info($"抽屉【{DrawerNo}】已关闭");
// 重新初始化数据
_portUtil.ResetData();
stop();
}
});
}
else
{
logger.Info($"抽屉【{DrawerNo}】打开失败");
// 重新初始化数据
_portUtil.ResetData();
AlertMsg alertMsg = new AlertMsg AlertMsg alertMsg = new AlertMsg
{ {
Message = "请填写药品数量", Message = "抽屉打开失败",
Type = MsgType.ERROR Type = MsgType.ERROR,
}; };
// 返回消息 抽屉打开失败
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg); _eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_portUtil.ResetData();
logger.Info($"OpenDrawer异常{ex.Message}");
_isFinishClick = false;
AlertMsg alertMsg = new AlertMsg AlertMsg alertMsg = new AlertMsg
{ {
Message = $"异常:{ex.Message}", Message = $"操作异常{ex.Message}",
Type = MsgType.ERROR Type = MsgType.ERROR,
};
// 返回消息 抽屉打开失败
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
});
}
//开药盒
public DelegateCommand<object> OpenBoxCommand
{
get => new DelegateCommand<object>(async (param) =>
{
try
{
if (Status >= 1)
{
//开药盒
logger.Info("打开药盒");
_portUtil.DrawerNo = DrawerNo;
if (await _portUtil.OpenBoxByColNo(CStock.ColNo))
{
// 此处延时1毫秒等待页面渲染
await Task.Delay(TimeSpan.FromMilliseconds(1));
DialogParameters dialogParameters = new DialogParameters();
dialogParameters.Add("channelStock", CStock);
DialogServiceExtensions.ShowDialogHost(_dialogService, "BiaoDingDialog", dialogParameters, DoDialogResult, "RootDialog");
}
else
{
AlertMsg alertMsg = new AlertMsg
{
Message = "打开药盒失败",
Type = MsgType.ERROR,
}; };
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg); _eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
//Status = 1; await Task.Delay(200);
} }
} }
else
{
//if (Status >= 2)
//{
// AlertMsg alertMsg = new AlertMsg
// {
// Message = "请先关闭药盒后再打开",
// Type = MsgType.ERROR,
// };
// _eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
//}
if(Status<1)
{
AlertMsg alertMsg = new AlertMsg
{
Message = "请先开抽屉后再打开药盒",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
}
}
catch(Exception ex)
{
AlertMsg alertMsg = new AlertMsg
{
Message = $"开药盒异常{ex.Message}",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
});
}
//抽屉返回状态 //抽屉返回状态
private bool DrawerState(int[] r) private bool DrawerState(int[] r)
{ {
int index = DrawerNo > 8 ? DrawerNo - 7 : DrawerNo + 1; int index = DrawerNo > 8 ? DrawerNo - 7 : DrawerNo + 1;
return r[index] == 0; 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 bool KeepAlive => false;
public void FindDrawerCount() public void FindDrawerCount()
@ -503,26 +302,11 @@ namespace DM_Weight.ViewModels
return cs; return cs;
}).ToList()); }).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) public void OnNavigatedTo(NavigationContext navigationContext)
{ {
//_eventAggregator.GetEvent<PortUtilEvent>().Subscribe(DoMyPrismEvent);
FindDrawerCount(); FindDrawerCount();
RequestData(); RequestData();
} }
@ -537,8 +321,6 @@ namespace DM_Weight.ViewModels
//这个方法用于拦截请求 //这个方法用于拦截请求
public void OnNavigatedFrom(NavigationContext navigationContext) public void OnNavigatedFrom(NavigationContext navigationContext)
{ {
// 取消消息订阅
//_eventAggregator.GetEvent<PortUtilEvent>().Unsubscribe(DoMyPrismEvent);
} }
} }
} }

View File

@ -18,6 +18,7 @@ using DM_Weight.Port;
using DM_Weight.util; using DM_Weight.util;
using log4net; using log4net;
using DM_Weight.Common; using DM_Weight.Common;
using System.Threading;
namespace DM_Weight.ViewModels namespace DM_Weight.ViewModels
{ {
@ -101,6 +102,7 @@ namespace DM_Weight.ViewModels
get => _drugManuNo; get => _drugManuNo;
set => SetProperty(ref _drugManuNo, value); set => SetProperty(ref _drugManuNo, value);
} }
private List<DrugManuNo>? _drugManuNos; private List<DrugManuNo>? _drugManuNos;
public List<DrugManuNo>? DrugManuNos public List<DrugManuNo>? DrugManuNos
@ -166,8 +168,13 @@ namespace DM_Weight.ViewModels
private void GetAllDrugInfos() private void GetAllDrugInfos()
{ {
var list = SqlSugarHelper.Db.Queryable<DrugInfo>().Includes<DrugManuNo>(di => di.DrugManuNos).OrderBy(di => di.DrugId).ToList(); string str = @"SELECT d.drug_id,d.py_code,d.drug_barcode,d.drug_brand_name,d.drug_spec,d.dosage,d.pack_unit,
DrugInfos = list; d.manufactory,d.max_stock,CONCAT(drug_name,' ',drug_spec)as drug_name FROM `drug_info` d";
DrugInfos = SqlSugarHelper.Db.SqlQueryable<DrugInfo>(str).OrderBy(di => di.DrugName).OrderBy(di => di.DrugId).ToList();
//var list = SqlSugarHelper.Db.Queryable<DrugInfo>().Includes<DrugManuNo>(di => di.DrugManuNos).OrderBy(di => di.DrugId).ToList();
//DrugInfos = list;
} }
private void GetChannelsByDrawerNo() private void GetChannelsByDrawerNo()
@ -209,6 +216,12 @@ namespace DM_Weight.ViewModels
{ {
var SelectChannels = Channels.FindAll(item => item.IsSelected && item.Quantity == 0); var SelectChannels = Channels.FindAll(item => item.IsSelected && item.Quantity == 0);
if (SelectChannels is null || SelectChannels.Count <= 0)
{
SnackbarBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#b71c1c"));
SnackbarMessageQueue.Enqueue("未选中库位或库位还存在药品无法绑定");
return;
}
if (SelectChannels.All(it => it.DrawerType != (Int32)DrawerTypeEnum.drawerTypeOne)) if (SelectChannels.All(it => it.DrawerType != (Int32)DrawerTypeEnum.drawerTypeOne))
{ {
@ -229,7 +242,7 @@ namespace DM_Weight.ViewModels
SqlSugarHelper.Db.Updateable(item).UpdateColumns(it => new { it.DrugId, it.PosNo }).ExecuteCommand(); SqlSugarHelper.Db.Updateable(item).UpdateColumns(it => new { it.DrugId, it.PosNo }).ExecuteCommand();
GetChannelsByDrawerNo(); GetChannelsByDrawerNo();
if (item.BoardType == (Int32)BoardTypeEnum.smart|| item.BoardType == (Int32)BoardTypeEnum.weighSmartBox) if (item.BoardType == (Int32)BoardTypeEnum.smart)
{ {
_portUtil.WindowName = "BindingChannelDialog"; _portUtil.WindowName = "BindingChannelDialog";
// 向显示屏写入库位信息 // 向显示屏写入库位信息
@ -241,6 +254,22 @@ namespace DM_Weight.ViewModels
await Task.Delay(200); await Task.Delay(200);
_portUtil.ShowContent(item.DrawerNo, item.ColNo); _portUtil.ShowContent(item.DrawerNo, item.ColNo);
} }
if (item.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{
_portUtil.WindowName = "BindingChannelDialog";
_portUtil.WriteChannelInfoMethod(1, DrugInfo.DrugName, item.DrawerNo, item.ColNo);
await Task.Delay(200);
_portUtil.WriteChannelInfoMethod(3, DrugInfo.DrugSpec, item.DrawerNo, item.ColNo);
await Task.Delay(200);
_portUtil.WriteChannelInfoMethod(4, DrugInfo.Manufactory, item.DrawerNo, item.ColNo);
await Task.Delay(200);
_portUtil.WriteChannelInfoMethod(5, item.EffDate, item.DrawerNo, item.ColNo);
await Task.Delay(200);
_portUtil.WriteChannelInfoMethod(6, item.ManuNo, item.DrawerNo, item.ColNo);
await Task.Delay(200);
_portUtil.ShowContentMethod(item.DrawerNo, item.ColNo);
Task.Delay(200);
}
//_screenUtil.SetStockInfo(item, 1); //_screenUtil.SetStockInfo(item, 1);
} }
@ -277,30 +306,56 @@ namespace DM_Weight.ViewModels
{ {
item.PosNo = 0; item.PosNo = 0;
} }
if (DrugManuNo.EffDate != null && DrugManuNo.EffDate.Length >= 10)
{
DrugManuNo.EffDate = DrugManuNo.EffDate.Substring(0, 10);
}
item.DrugId = DrugInfo.DrugId.ToString(); item.DrugId = DrugInfo.DrugId.ToString();
item.ManuNo = DrugManuNo.ManuNo; item.ManuNo = DrugManuNo.ManuNo;
item.DrugInfo = DrugInfo; item.DrugInfo = DrugInfo;
item.EffDate = String.Format("{0:yyyy-MM-dd}", DrugManuNo.EffDate); item.EffDate = String.Format("{0:yyyy-MM-dd}", DrugManuNo.EffDate.Length >= 10 ? DrugManuNo.EffDate.Substring(0, 10) : DrugManuNo.EffDate);
SqlSugarHelper.Db.Updateable(item).UpdateColumns(it => new { it.DrugId, it.ManuNo, it.EffDate, it.PosNo }).ExecuteCommand(); SqlSugarHelper.Db.Updateable(item).UpdateColumns(it => new { it.DrugId, it.ManuNo, it.EffDate, it.PosNo }).ExecuteCommand();
if (item.BoardType == (Int32)BoardTypeEnum.smart || item.BoardType == (Int32)BoardTypeEnum.weighSmartBox) });
Task.Factory.StartNew(() =>
{
SelectChannels.ForEach((item) =>
{
if (item.BoardType == (Int32)BoardTypeEnum.smart)
{ {
_portUtil.WindowName = "BindingChannelDialog"; _portUtil.WindowName = "BindingChannelDialog";
// 向显示屏写入库位信息 // 向显示屏写入库位信息
_portUtil.WriteChannelInfo(1, DrugInfo.DrugName, item.DrawerNo, item.ColNo); _portUtil.WriteChannelInfo(1, DrugInfo.DrugName, item.DrawerNo, item.ColNo);
await Task.Delay(200); Thread.Sleep(200);
_portUtil.WriteChannelInfo(2, DrugInfo.DrugSpec, item.DrawerNo, item.ColNo); _portUtil.WriteChannelInfo(2, DrugInfo.DrugSpec, item.DrawerNo, item.ColNo);
await Task.Delay(200); Thread.Sleep(200);
_portUtil.WriteChannelInfo(8, DrugInfo.Manufactory, item.DrawerNo, item.ColNo); _portUtil.WriteChannelInfo(8, DrugInfo.Manufactory, item.DrawerNo, item.ColNo);
await Task.Delay(200); Thread.Sleep(200);
_portUtil.WriteChannelInfo(6, DrugManuNo.ManuNo, item.DrawerNo, item.ColNo); _portUtil.WriteChannelInfo(5, DrugManuNo.ManuNo, item.DrawerNo, item.ColNo);
await Task.Delay(200); Thread.Sleep(200);
_portUtil.WriteChannelInfo(5, String.Format("{0:yyyy-MM-dd}", DrugManuNo.EffDate), item.DrawerNo, item.ColNo); _portUtil.WriteChannelInfo(6, String.Format("{0:yyyy-MM-dd}", DrugManuNo.EffDate.Length >= 10 ? DrugManuNo.EffDate.Substring(0, 10) : DrugManuNo.EffDate), item.DrawerNo, item.ColNo);
await Task.Delay(200); Thread.Sleep(200);
_portUtil.ShowContent(item.DrawerNo, item.ColNo); _portUtil.ShowContent(item.DrawerNo, item.ColNo);
} }
//_screenUtil.SetStockInfo(item, 1); if (item.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{
_portUtil.WindowName = "BindingChannelDialog";
Thread.Sleep(200);
_portUtil.WriteChannelInfoMethod(1, DrugInfo.DrugName, item.DrawerNo, item.ColNo);
Thread.Sleep(200);
_portUtil.WriteChannelInfoMethod(3, DrugInfo.DrugSpec, item.DrawerNo, item.ColNo);
Thread.Sleep(200);
_portUtil.WriteChannelInfoMethod(4, DrugInfo.Manufactory, item.DrawerNo, item.ColNo);
Thread.Sleep(200);
_portUtil.WriteChannelInfoMethod(5, item.EffDate, item.DrawerNo, item.ColNo);
Thread.Sleep(200);
_portUtil.WriteChannelInfoMethod(6, item.ManuNo, item.DrawerNo, item.ColNo);
Thread.Sleep(200);
_portUtil.ShowContentMethod(item.DrawerNo, item.ColNo);
}
});
}); });
GetChannelsByDrawerNo(); GetChannelsByDrawerNo();
} }
@ -334,16 +389,30 @@ namespace DM_Weight.ViewModels
item.EffDate = null; item.EffDate = null;
item.DrugInfo = null; item.DrugInfo = null;
SqlSugarHelper.Db.Updateable(item).UpdateColumns(it => new { it.DrugId, it.ManuNo, it.EffDate }).ExecuteCommand(); SqlSugarHelper.Db.Updateable(item).UpdateColumns(it => new { it.DrugId, it.ManuNo, it.EffDate }).ExecuteCommand();
if (item.BoardType == (Int32)BoardTypeEnum.smart || item.BoardType == (Int32)BoardTypeEnum.weighSmartBox) //_screenUtil.SetStockInfo(item, 1);
});
Task.Factory.StartNew(() =>
{
SelectChannels.ForEach(item =>
{
if (item.BoardType == (Int32)BoardTypeEnum.smart)
{ {
// 清除显示屏库位信息 // 清除显示屏库位信息
_portUtil.ClearContent(item.DrawerNo, item.ColNo); _portUtil.ClearContent(item.DrawerNo, item.ColNo);
await Task.Delay(200); Thread.Sleep(200);
_portUtil.ShowContent(item.DrawerNo, item.ColNo); _portUtil.ShowContent(item.DrawerNo, item.ColNo);
} }
if (item.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{
Thread.Sleep(200);
_portUtil.ClearContentMethod(item.DrawerNo, item.ColNo);
Thread.Sleep(200);
_portUtil.ShowContentMethod(item.DrawerNo, item.ColNo);
}
//_screenUtil.SetStockInfo(item, 1); //_screenUtil.SetStockInfo(item, 1);
}); });
});
GetChannelsByDrawerNo(); GetChannelsByDrawerNo();
} }
else else
@ -391,8 +460,8 @@ namespace DM_Weight.ViewModels
public void UpdateComboBoxItems(string text) public void UpdateComboBoxItems(string text)
{ {
string str = @"SELECT d.drug_id,d.py_code,d.drug_barcode,d.drug_name,d.drug_brand_name,d.drug_spec,d.dosage,d.pack_unit, string str = @"SELECT d.drug_id,d.py_code,d.drug_barcode,d.drug_brand_name,d.drug_spec,d.dosage,d.pack_unit,
d.manufactory,d.max_stock,CONCAT(drug_name,' ',drug_spec)as drug_name_spec FROM `drug_info` d"; d.manufactory,d.max_stock,CONCAT(drug_name,' ',drug_spec)as d.drug_name FROM `drug_info` d";
if(string.IsNullOrEmpty(text)) if(string.IsNullOrEmpty(text))
{ {
DrugInfos = SqlSugarHelper.Db.SqlQueryable<DrugInfo>(str).OrderBy(di => di.DrugName).OrderBy(di => di.DrugId).ToList(); DrugInfos = SqlSugarHelper.Db.SqlQueryable<DrugInfo>(str).OrderBy(di => di.DrugName).OrderBy(di => di.DrugId).ToList();

View File

@ -273,6 +273,18 @@ namespace DM_Weight.ViewModels
item.DrugId = DrugInfo.DrugId.ToString(); item.DrugId = DrugInfo.DrugId.ToString();
item.DrugSpec= DrugInfo.DrugSpec.ToString(); item.DrugSpec= DrugInfo.DrugSpec.ToString();
SqlSugarHelper.Db.Updateable(item).UpdateColumns(it => new { it.DrugId, it.PosNo,it.DrugSpec }).ExecuteCommand(); SqlSugarHelper.Db.Updateable(item).UpdateColumns(it => new { it.DrugId, it.PosNo,it.DrugSpec }).ExecuteCommand();
//绑定回收箱无批次写入一条ChannelStock 库存信息
SqlSugarHelper.Db.Insertable(new ChannelStock()
{
Chnguid = item.Id,
DrawerNo = item.DrawerNo,
ColNo = item.ColNo,
DrugId = item.DrugId,
DrawerType = item.DrawerType,
BoardType = item.BoardType,
Id = Guid.NewGuid().ToString(),
MachineId = ConfigurationManager.AppSettings["machineId"] ?? "DM1"
}).ExecuteCommand();
GetChannelsByDrawerNo(); GetChannelsByDrawerNo();
if (item.BoardType == (Int32)BoardTypeEnum.smart) if (item.BoardType == (Int32)BoardTypeEnum.smart)
@ -291,6 +303,18 @@ namespace DM_Weight.ViewModels
//await Task.Delay(200); //await Task.Delay(200);
_portUtil.ShowContent(item.DrawerNo, item.ColNo); _portUtil.ShowContent(item.DrawerNo, item.ColNo);
} }
if(item.BoardType==(Int32)BoardTypeEnum.weighSmartBox)
{
_portUtil.WindowName = "BindingChannelDialog";
await _portUtil.WriteChannelInfoMethod(1, DrugInfo.DrugName, item.DrawerNo, item.ColNo);
Task.Delay(200);
await _portUtil.WriteChannelInfoMethod(3, DrugInfo.DrugSpec, item.DrawerNo, item.ColNo);
Task.Delay(200);
await _portUtil.WriteChannelInfoMethod(4, DrugInfo.Manufactory, item.DrawerNo, item.ColNo);
Task.Delay(200);
await _portUtil.ShowContentMethod(item.DrawerNo, item.ColNo);
Task.Delay(200);
}
//_screenUtil.SetStockInfo(item, 1); //_screenUtil.SetStockInfo(item, 1);
} }
@ -345,7 +369,7 @@ namespace DM_Weight.ViewModels
//item.EffDate = String.Format("{0:yyyy-MM-dd}", DrugManuNo.EffDate); //item.EffDate = String.Format("{0:yyyy-MM-dd}", DrugManuNo.EffDate);
SqlSugarHelper.Db.Updateable(item).UpdateColumns(it => new { it.DrugId, it.PosNo,it.DrugSpec }).ExecuteCommand(); SqlSugarHelper.Db.Updateable(item).UpdateColumns(it => new { it.DrugId, it.PosNo,it.DrugSpec }).ExecuteCommand();
if (item.BoardType == (Int32)BoardTypeEnum.smart || item.BoardType == (Int32)BoardTypeEnum.weighSmartBox) if (item.BoardType == (Int32)BoardTypeEnum.smart )
{ {
_portUtil.WindowName = "BindingChannelDialog"; _portUtil.WindowName = "BindingChannelDialog";
// 向显示屏写入库位信息 // 向显示屏写入库位信息
@ -366,6 +390,18 @@ namespace DM_Weight.ViewModels
//Thread.Sleep(200); //Thread.Sleep(200);
_portUtil.ShowContent(item.DrawerNo, item.ColNo); _portUtil.ShowContent(item.DrawerNo, item.ColNo);
} }
if(item.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{
_portUtil.WindowName = "BindingChannelDialog";
await _portUtil.WriteChannelInfoMethod(1, DrugInfo.DrugName, item.DrawerNo, item.ColNo);
Task.Delay(200);
await _portUtil.WriteChannelInfoMethod(3, DrugInfo.DrugSpec, item.DrawerNo, item.ColNo);
Task.Delay(200);
await _portUtil.WriteChannelInfoMethod(4, DrugInfo.Manufactory, item.DrawerNo, item.ColNo);
Task.Delay(200);
await _portUtil.ShowContentMethod(item.DrawerNo, item.ColNo);
Task.Delay(200);
}
} }
@ -415,9 +451,9 @@ namespace DM_Weight.ViewModels
if (item.BoardType == (Int32)BoardTypeEnum.smart || item.BoardType == (Int32)BoardTypeEnum.weighSmartBox) if (item.BoardType == (Int32)BoardTypeEnum.smart || item.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{ {
// 清除显示屏库位信息 // 清除显示屏库位信息
_portUtil.ClearContent(item.DrawerNo, item.ColNo); await _portUtil.ClearContent(item.DrawerNo, item.ColNo);
await Task.Delay(200); await Task.Delay(200);
_portUtil.ShowContent(item.DrawerNo, item.ColNo); await _portUtil.ShowContent(item.DrawerNo, item.ColNo);
} }
//_screenUtil.SetStockInfo(item, 1); //_screenUtil.SetStockInfo(item, 1);

View File

@ -16,6 +16,7 @@ using DM_Weight.msg;
using DM_Weight.Port; using DM_Weight.Port;
using DM_Weight.util; using DM_Weight.util;
using DM_Weight.Common; using DM_Weight.Common;
using System.Threading;
namespace DM_Weight.ViewModels namespace DM_Weight.ViewModels
{ {
@ -69,7 +70,7 @@ namespace DM_Weight.ViewModels
case EventType.UPDATEQUANTITY: case EventType.UPDATEQUANTITY:
if (Status == 2) if (Status == 2)
{ {
logger.Info($"抽屉【{DrawerNo}】库位药品数量【{msg.Quantitys}】"); logger.Info($"抽屉【{DrawerNo}】库位药品数量【{string.Join(',',msg.Quantitys)}】");
} }
break; break;
// 打开失败 // 打开失败
@ -164,9 +165,9 @@ namespace DM_Weight.ViewModels
SqlSugarHelper.Db.Updateable(new ChannelStock() SqlSugarHelper.Db.Updateable(new ChannelStock()
{ {
Quantity = it.CheckQuantity, Quantity = it.CheckQuantity,
Id = it.Id,
ManuNo = it.ManuNo, ManuNo = it.ManuNo,
EffDate = it.EffDate, EffDate = it.EffDate,
Id = it.Id,
}).UpdateColumns(it => new { it.Quantity, it.ManuNo, it.EffDate }).ExecuteCommand(); }).UpdateColumns(it => new { it.Quantity, it.ManuNo, it.EffDate }).ExecuteCommand();
// 获取更新完库存后的药品库存 // 获取更新完库存后的药品库存
List<ChannelStock> nowChannels = SqlSugarHelper.Db.Queryable<ChannelStock>() List<ChannelStock> nowChannels = SqlSugarHelper.Db.Queryable<ChannelStock>()
@ -207,7 +208,8 @@ namespace DM_Weight.ViewModels
{ {
singleChannels.ForEach(it => singleChannels.ForEach(it =>
{ {
_portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.CheckQuantity); _portUtil.WriteQuantityMethod(it.CheckQuantity,it.DrawerNo, it.ColNo);
Thread.Sleep(200);
}); });
} }

View File

@ -38,6 +38,12 @@ namespace DM_Weight.ViewModels
private static readonly DateTime Jan1st1970 = new DateTime private static readonly DateTime Jan1st1970 = new DateTime
(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private bool _openBoxVisibility = false;
public bool OpenBoxVisibility
{
get => _openBoxVisibility;
set => SetProperty(ref _openBoxVisibility, value);
}
private PortUtil _portUtil; private PortUtil _portUtil;
IEventAggregator _eventAggregator; IEventAggregator _eventAggregator;
@ -71,12 +77,15 @@ namespace DM_Weight.ViewModels
} }
//是冰箱抽屉则开冰箱抽屉时发送延迟报警指令 //是冰箱抽屉则开冰箱抽屉时发送延迟报警指令
CheckIsFridgeClose(); CheckIsFridgeClose();
//抽屉关闭查询称重稳定数据
CompleteIsEnable = true;
break; break;
// 数量变化 // 数量变化
case EventType.UPDATEQUANTITY: case EventType.UPDATEQUANTITY:
if (Status == 2) if (Status == 2 || Status == 3)
{ {
ChannelStocks.ForEach(it => it.AddQuantity = msg.Quantitys[it.ColNo - 1]); ChannelStocks.Where(cs => _portUtil.ColNoLst.Contains(cs.ColNo)).ToList().ForEach(it => it.AddQuantity = msg.Quantitys[it.ColNo - 1]);
} }
break; break;
// 打开失败 // 打开失败
@ -127,17 +136,190 @@ namespace DM_Weight.ViewModels
}, (DrawerNo) => Status == 0 }, (DrawerNo) => Status == 0
); );
} }
/// <summary>
/// 完成按钮是否可用
/// </summary>
private bool _completeIsEnable = false;
public bool CompleteIsEnable
{
get => _completeIsEnable;
set
{
SetProperty(ref _completeIsEnable, value);
}
}
/// <summary>
/// 取消按钮是否可用
/// </summary>
private bool _cancleIsEnable = true;
public bool CancleIsEnable
{
get => _cancleIsEnable;
set
{
SetProperty(ref _cancleIsEnable, value);
}
}
int currentCol = 0;
private int[] BeforeQuantity { get; set; } = new int[9];
private int[] AfterQuantity { get; set; } = new int[9];
public DelegateCommand OpenDrawer public DelegateCommand OpenDrawer
{ {
get => new DelegateCommand(() => get => new DelegateCommand(async () =>
{ {
if (Status > 0 || _portUtil.Operate)
{
return;
}
Status = 1; Status = 1;
_portUtil.SpeakAsync("正在打开" + DrawerNo + "号抽屉"); _portUtil.SpeakAsync("正在打开" + DrawerNo + "号抽屉");
if (ChannelStocks != null && ChannelStocks.Count > 0 && (ChannelStocks[0].BoardType == (Int32)BoardTypeEnum.weighSmartBox))
{
try try
{ {
List<ChannelStock> singleChannels = ChannelStocks.FindAll(it => it.BoardType != (Int32)BoardTypeEnum.separation); _portUtil.DrawerNo = DrawerNo;
_portUtil.Operate = true;
_portUtil.WindowName = "DrawerAddDrugWindow";
byte[] buffer = await _portUtil.OpenDrawer();
CancleIsEnable = false;
if (buffer == null)
{
logger.Info("抽屉打开返回空");
Status = 0;
return;
}
int[] r = buffer.Select(it => Convert.ToInt32(it)).ToArray();
logger.Info($"OpenDrawer{string.Join(",", r)}");
if (_portUtil.DrawerState(r))
{
_portUtil.ColNoLst.Clear();
new PromiseUtil<int>().taskAsyncLoop(200, 0, async (options, next, stop) =>
{
logger.Info("循环查抽屉状态药盒数量");
if (Status == 3 || Status == 0)
{
stop();
}
else
{
try
{
// 查询抽屉状态
byte[] buffer = await _portUtil.CheckDrawerStatus();
int[] r = buffer.Select(it => Convert.ToInt32(it)).ToArray();
logger.Info($"抽屉状态返回{Convert.ToHexString(buffer)}");
if (_portUtil.DrawerState(r))
{
Status = 2;
if (_portUtil.ColNoLst != null && _portUtil.ColNoLst.Count > 0 || currentCol > 0)
{
//库位列表不为空查数
if (currentCol > 0)
{
if (!_portUtil.ColNoLst.Contains(currentCol)) //已经开过一次药盒则不再查开药合前的数量
{
CancleIsEnable = false;
//开药盒锁前先查数
int beforeQuantity = await _portUtil.CheckQuantityForSingle(currentCol);
Thread.Sleep(200);
BeforeQuantity[currentCol - 1] = beforeQuantity;
logger.Info($"BeforeQuantity:{currentCol}-{beforeQuantity}数量{string.Join(",", BeforeQuantity)}");
_portUtil.ColNoLst.Add(currentCol);
}
await _portUtil.OpenBoxByColNo(currentCol);
Thread.Sleep(200);
currentCol = 0;
}
// 继续查询抽屉药品数量
// 查询抽屉药品数量
int[] quantity = await _portUtil.CheckQuantityByAddrForMulti();
AfterQuantity = quantity;
logger.Info($"AfterQuantity{string.Join(",", AfterQuantity)}");
int[] Quantitys = new int[BeforeQuantity.Length];
for (int i = 0; i < BeforeQuantity.Length; i++)
{
Quantitys[i] = AfterQuantity[i] - BeforeQuantity[i];
}
// 告诉前台数据变化
_eventAggregator.GetEvent<PortUtilEvent>().Publish(new util.DeviceMsg()
{
EventType = util.EventType.UPDATEQUANTITY,
WindowName = "DrawerAddDrugWindow",
Quantitys = Quantitys
});
logger.Info($"数量变化【{string.Join(",", Quantitys)}】");
}
next();
}
else
{
stop();
//关闭抽屉
logger.Info($"抽屉【{DrawerNo}】已关闭");
// 重新初始化数据
//_portUtil.ResetData();
if (_portUtil.ColNoLst != null && _portUtil.ColNoLst.Count > 0)
{
Thread.Sleep(200);
//关闭抽屉后获取称重稳定数量
GetWeightQuantity();
//_portUtil.ColNoLst.Clear();
Status = 3;
//CancleIsEnable = true;
}
else
{
Status = 0;
_portUtil.ResetData();
}
CompleteIsEnable = false;
}
}
catch (Exception ex)
{
logger.Info($"异常{ex.Message}");
//AlertMsg alertMsg = new AlertMsg
//{
// Message = $"异常{ex.Message}",
// Type = MsgType.ERROR,
//};
//_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
next();
}
}
});
}
else
{
Status = 0;
AlertMsg alertMsg = new AlertMsg
{
Message = "抽屉打开失败",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
}
catch (Exception ex)
{
logger.Info($"抽屉操作异常:{ex.Message}");
AlertMsg alertMsg = new AlertMsg
{
Message = $"抽屉操作异常{ex.Message}",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
}
else
{
List<ChannelStock> singleChannels = ChannelStocks.FindAll(it => it.BoardType != (Int32)BoardTypeEnum.separation);
_portUtil.WindowName = "DrawerAddDrugWindow"; _portUtil.WindowName = "DrawerAddDrugWindow";
_portUtil.Operate = true; _portUtil.Operate = true;
_portUtil.BoardType = singleChannels.Count > 0 ? singleChannels[0].BoardType : (Int32)BoardTypeEnum.separation; _portUtil.BoardType = singleChannels.Count > 0 ? singleChannels[0].BoardType : (Int32)BoardTypeEnum.separation;
@ -146,15 +328,32 @@ namespace DM_Weight.ViewModels
_portUtil.Start(); _portUtil.Start();
} }
catch (Exception ex)
{
logger.Info($"OpenDrawer异常{ex.Message}");
}
}, () => Status == 0).ObservesProperty(() => Status); }, () => Status == 0).ObservesProperty(() => Status);
} }
//开药盒
public DelegateCommand<object> OpenBoxCommand
{
get => new DelegateCommand<object>((param) =>
{
if (Status == 2)
{
ChannelStock cs = param as ChannelStock;
currentCol = cs.ColNo;
logger.Info($"开药盒{cs.ColNo}");
}
else
{
AlertMsg alertMsg = new AlertMsg
{
Message = "请先开抽屉后再打开药盒",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
logger.Info($"请先开抽屉后再打开药盒");
}
});
}
private bool _isFinishClick = false; private bool _isFinishClick = false;
// 完成按钮 // 完成按钮
@ -175,8 +374,8 @@ namespace DM_Weight.ViewModels
for (int i = 0; i < record.Count; i++) for (int i = 0; i < record.Count; i++)
{ {
ChannelStock it = record[i]; ChannelStock it = record[i];
it.ManuNo = it.drugManuNo==null?it.ManuNo: it.drugManuNo.ManuNo; it.ManuNo = it.drugManuNo == null ? it.ManuNo : it.drugManuNo.ManuNo;
it.EffDate = it.drugManuNo == null? it.EffDate: it.drugManuNo.EffDate; it.EffDate = it.drugManuNo == null ? it.EffDate : it.drugManuNo.EffDate;
// 更新数据 库存信息 // 更新数据 库存信息
@ -212,12 +411,12 @@ namespace DM_Weight.ViewModels
StockQuantity = nowChannels.Sum(it => it.Quantity) StockQuantity = nowChannels.Sum(it => it.Quantity)
}).ExecuteCommand(); }).ExecuteCommand();
//称重计数或称重+智能显示+管控药盒 类型需要 发26指令 //称重计数或称重+智能显示+管控药盒 类型需要 发26指令
if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox) //if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{ //{
//计数数量设置发送称重26指令 // //计数数量设置发送称重26指令
_portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity); // _portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity);
Thread.Sleep(80); // Thread.Sleep(80);
} //}
} }
return true; return true;
}); });
@ -230,7 +429,8 @@ namespace DM_Weight.ViewModels
{ {
singleChannels.ForEach(it => singleChannels.ForEach(it =>
{ {
_portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.Quantity + it.AddQuantity); _portUtil.WriteQuantityMethod(it.Quantity + it.AddQuantity, it.DrawerNo, it.ColNo);
Thread.Sleep(200);
}); });
} }
RequestData(); RequestData();
@ -252,6 +452,7 @@ namespace DM_Weight.ViewModels
} }
Status = 0; Status = 0;
_isFinishClick = false; _isFinishClick = false;
_portUtil.ColNoLst = new List<int>();
} }
else else
{ {
@ -358,12 +559,10 @@ namespace DM_Weight.ViewModels
.ToList(); .ToList();
if (queryData != null && queryData.Count > 0) if (queryData != null && queryData.Count > 0)
{ {
ChannelStocks = queryData.Select(cs => OpenBoxVisibility = (queryData[0].BoardType == (Int32)BoardTypeEnum.box || queryData[0].BoardType == (Int32)BoardTypeEnum.weighBox || queryData[0].BoardType == (Int32)BoardTypeEnum.weighSmartBox) ? true : false;
{
cs.drugManuNo = cs.DrugInfo.DrugManuNos.Find(it => it.ManuNo.Equals(cs.ManuNo));
return cs;
}).ToList();
} }
ChannelStocks = queryData;
} }
//接收导航传过来的参数 现在是在此处初始化了表格数据 //接收导航传过来的参数 现在是在此处初始化了表格数据
@ -387,5 +586,99 @@ namespace DM_Weight.ViewModels
// 取消消息订阅 // 取消消息订阅
_eventAggregator.GetEvent<PortUtilEvent>().Unsubscribe(DoMyPrismEvent); _eventAggregator.GetEvent<PortUtilEvent>().Unsubscribe(DoMyPrismEvent);
} }
//关闭抽屉后获取称重稳定数量
public void GetWeightQuantity()
{
List<int[]> finalyQuantity = new List<int[]>();
new PromiseUtil<int>().taskAsyncLoop(200, 0, async (options, next, stop) =>
{
if (!_portUtil.Operate|| Status==0)
{
stop();
}
else
{
try
{
logger.Info("关闭抽屉后获取称重稳定数量");
if (finalyQuantity.Count >= 10)
{
for (int i = 0; i < finalyQuantity.Count; i++)
{
logger.Info($"finalyQuantity{i} {string.Join(",", finalyQuantity[i])}");
}
if (AreAllArraysEqual(finalyQuantity))
{
stop();
// 告诉前台数据变化
_eventAggregator.GetEvent<PortUtilEvent>().Publish(new util.DeviceMsg()
{
EventType = util.EventType.UPDATEQUANTITY,
WindowName = "DrawerTakeDrugWindow",
Quantitys = finalyQuantity[0]
});
logger.Info($"数量变化【{string.Join(",", finalyQuantity[0])}】");
// 重新初始化数据
_portUtil.ResetData();
CompleteIsEnable = true;
CancleIsEnable = true;
}
else
{
finalyQuantity.RemoveAt(0);
CancleIsEnable = true;
next();
}
}
else
{
if(finalyQuantity.Count>=9)
{
CancleIsEnable = true;
}
else
{
CancleIsEnable = false;
}
CompleteIsEnable = false;
_portUtil.DrawerNo = DrawerNo;
_portUtil.Operate = true;
int[] quantity = await _portUtil.CheckQuantityByAddrForMulti();
AfterQuantity = quantity;
int[] Quantitys = new int[BeforeQuantity.Length];
for (int i = 0; i < BeforeQuantity.Length; i++)
{
Quantitys[i] = AfterQuantity[i] - BeforeQuantity[i];
}
finalyQuantity.Add(Quantitys);
logger.Info($"Quantity{string.Join(",", Quantitys)}");
// 告诉前台数据变化
_eventAggregator.GetEvent<PortUtilEvent>().Publish(new util.DeviceMsg()
{
EventType = util.EventType.UPDATEQUANTITY,
WindowName = "DrawerAddDrugWindow",
Quantitys = finalyQuantity[0]
});
next();
}
}
catch (Exception ex)
{
logger.Info($"关抽屉后获取称重稳定数量异常{ex.Message}");
next();
}
}
});
}
public bool AreAllArraysEqual(List<int[]> arrays)
{
if (arrays == null || arrays.Count == 0) return false;
// 取第一个数组作为参照进行比较
var referenceArray = arrays[0];
// 检查列表中除了第一个数组外的所有数组是否与第一个数组相等
return arrays.Skip(1).All(array => array.SequenceEqual(referenceArray));
}
} }
} }

View File

@ -22,6 +22,8 @@ using Newtonsoft.Json;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Windows.Controls; using System.Windows.Controls;
using DM_Weight.Common; using DM_Weight.Common;
using System.Reflection.Metadata;
using System.Windows.Documents;
namespace DM_Weight.ViewModels namespace DM_Weight.ViewModels
{ {
@ -40,7 +42,12 @@ namespace DM_Weight.ViewModels
private static readonly DateTime Jan1st1970 = new DateTime private static readonly DateTime Jan1st1970 = new DateTime
(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private bool _openBoxVisibility = false;
public bool OpenBoxVisibility
{
get => _openBoxVisibility;
set => SetProperty(ref _openBoxVisibility, value);
}
private PortUtil _portUtil; private PortUtil _portUtil;
IEventAggregator _eventAggregator; IEventAggregator _eventAggregator;
@ -73,14 +80,23 @@ namespace DM_Weight.ViewModels
{ {
Status = 3; Status = 3;
} }
//if (ChannelStocks != null && ChannelStocks.Count > 0 && (ChannelStocks[0].BoardType == (Int32)BoardTypeEnum.weighSmartBox))
//{
// //关闭抽屉后获取称重稳定数量
// GetWeightQuantity();
//}
//else
//{
//是冰箱抽屉则开冰箱抽屉时发送延迟报警指令 //是冰箱抽屉则开冰箱抽屉时发送延迟报警指令
CheckIsFridgeClose(); CheckIsFridgeClose();
CompleteIsEnable = true;
//}
break; break;
// 数量变化 // 数量变化
case EventType.UPDATEQUANTITY: case EventType.UPDATEQUANTITY:
if (Status == 2) if (Status == 2 || Status == 3)
{ {
ChannelStocks.ForEach(it => it.TakeQuantity = msg.Quantitys[it.ColNo - 1]); ChannelStocks.Where(cs => _portUtil.ColNoLst.Contains(cs.ColNo)).ToList().ForEach(it => it.TakeQuantity = msg.Quantitys[it.ColNo - 1]);
} }
break; break;
// 打开失败 // 打开失败
@ -132,27 +148,218 @@ namespace DM_Weight.ViewModels
); );
} }
/// <summary>
/// 完成按钮是否可用
/// </summary>
private bool _completeIsEnable = false;
public bool CompleteIsEnable
{
get => _completeIsEnable;
set
{
SetProperty(ref _completeIsEnable, value);
}
}
/// <summary>
/// 取消按钮是否可用
/// </summary>
private bool _cancleIsEnable = true;
public bool CancleIsEnable
{
get => _cancleIsEnable;
set
{
SetProperty(ref _cancleIsEnable, value);
}
}
List<int> ColLst = new List<int>();
int currentCol = 0;
private int[] BeforeQuantity { get; set; } = new int[9];
private int[] AfterQuantity { get; set; } = new int[9];
public DelegateCommand OpenDrawer public DelegateCommand OpenDrawer
{ {
get => new DelegateCommand(() => get => new DelegateCommand(async () =>
{ {
if (Status == 0) if (Status > 0 || _portUtil.Operate)
{ {
return;
}
Status = 1; Status = 1;
_portUtil.SpeakAsync("正在打开" + DrawerNo + "号抽屉"); _portUtil.SpeakAsync("正在打开" + DrawerNo + "号抽屉");
if (ChannelStocks != null && ChannelStocks.Count > 0 && (ChannelStocks[0].BoardType == (Int32)BoardTypeEnum.weighSmartBox))
{
try
{
_portUtil.DrawerNo = DrawerNo;
_portUtil.Operate = true;
_portUtil.WindowName = "DrawerTakeDrugWindow";
byte[] buffer = await _portUtil.OpenDrawer();
CancleIsEnable = false;
if (buffer == null)
{
logger.Info("抽屉打开返回空");
Status = 0;
return;
}
int[] r = buffer.Select(it => Convert.ToInt32(it)).ToArray();
logger.Info($"OpenDrawer{string.Join(",", r)}");
if (_portUtil.DrawerState(r))
{
_portUtil.ColNoLst.Clear();
new PromiseUtil<int>().taskAsyncLoop(200, 0, async (options, next, stop) =>
{
logger.Info("循环查抽屉状态药盒数量");
if (Status == 3 || Status == 0)
{
stop();
}
else
{
try
{
// 查询抽屉状态
byte[] buffer = await _portUtil.CheckDrawerStatus();
int[] r = buffer.Select(it => Convert.ToInt32(it)).ToArray();
logger.Info($"抽屉状态返回{Convert.ToHexString(buffer)}");
if (_portUtil.DrawerState(r))
{
Status = 2;
if (_portUtil.ColNoLst != null && _portUtil.ColNoLst.Count > 0 || currentCol > 0)
{
//库位列表不为空查数
if (currentCol > 0)
{
if (!_portUtil.ColNoLst.Contains(currentCol))
{
CancleIsEnable = false;
//开药盒锁前先查数
//Thread.Sleep(200);
int beforeQuantity = await _portUtil.CheckQuantityForSingle(currentCol);
BeforeQuantity[currentCol - 1] = beforeQuantity;
logger.Info($"BeforeQuantity:{currentCol}-{beforeQuantity}数量{string.Join(",", BeforeQuantity)}");
_portUtil.ColNoLst.Add(currentCol);
}
await _portUtil.OpenBoxByColNo(currentCol);
currentCol = 0;
}
// 继续查询抽屉药品数量
// 查询抽屉药品数量
//Thread.Sleep(200);
int[] quantity = await _portUtil.CheckQuantityByAddrForMulti();
AfterQuantity = quantity;
logger.Info($"AfterQuantity{string.Join(",", AfterQuantity)}");
int[] Quantitys = new int[BeforeQuantity.Length];
for (int i = 0; i < BeforeQuantity.Length; i++)
{
Quantitys[i] = BeforeQuantity[i] - AfterQuantity[i];
}
// 告诉前台数据变化
_eventAggregator.GetEvent<PortUtilEvent>().Publish(new util.DeviceMsg()
{
EventType = util.EventType.UPDATEQUANTITY,
WindowName = "DrawerTakeDrugWindow",
Quantitys = Quantitys
});
logger.Info($"数量变化【{string.Join(",", Quantitys)}】");
}
next();
}
else
{
stop();
//关闭抽屉
logger.Info($"抽屉【{DrawerNo}】已关闭");
if (_portUtil.ColNoLst.Count > 0)
{
// 重新初始化数据
//_portUtil.ResetData();
//关闭抽屉后获取称重稳定数量
Thread.Sleep(200);
GetWeightQuantity();
//_portUtil.ColNoLst.Clear();
Status = 3;
}
else
{
Status = 0;
CancleIsEnable = true;
_portUtil.ResetData();
}
CompleteIsEnable = false;
}
}
catch (Exception ex)
{
logger.Info($"异常{ex.Message}");
next();
}
}
});
}
else
{
Status = 0;
AlertMsg alertMsg = new AlertMsg
{
Message = "抽屉打开失败",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
}
catch (Exception ex)
{
logger.Info($"抽屉操作异常:{ex.Message}");
AlertMsg alertMsg = new AlertMsg
{
Message = $"抽屉操作异常{ex.Message}",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
}
else
{
List<ChannelStock> singleChannels = ChannelStocks.FindAll(it => it.BoardType != (Int32)BoardTypeEnum.separation); List<ChannelStock> singleChannels = ChannelStocks.FindAll(it => it.BoardType != (Int32)BoardTypeEnum.separation);
_portUtil.WindowName = "DrawerTakeDrugWindow"; _portUtil.WindowName = "DrawerTakeDrugWindow";
_portUtil.BoardType = singleChannels.Count > 0 ? singleChannels[0].BoardType : (Int32)BoardTypeEnum.separation; _portUtil.BoardType = singleChannels.Count > 0 ? singleChannels[0].BoardType : (Int32)BoardTypeEnum.separation;
_portUtil.ColNos = singleChannels.Select(it => it.ColNo).ToArray(); _portUtil.ColNos = singleChannels.Select(it => it.ColNo).ToArray();
_portUtil.DrawerNo = DrawerNo; _portUtil.DrawerNo = DrawerNo;
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Normal, () => _portUtil.Start()) Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Normal, () => _portUtil.Start());
; }
});
}
List<int> openBoxColNOs = new List<int>();
//开药盒
public DelegateCommand<object> OpenBoxCommand
{
get => new DelegateCommand<object>((param) =>
{
if (Status == 2)
{
ChannelStock cs = param as ChannelStock;
currentCol = cs.ColNo;
logger.Info($"开药盒{cs.ColNo}");
}
else
{
AlertMsg alertMsg = new AlertMsg
{
Message = "请先开抽屉后再打开药盒",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
} }
}); });
} }
@ -220,11 +427,13 @@ namespace DM_Weight.ViewModels
{ {
// 更新屏显库存 // 更新屏显库存
List<ChannelStock> singleChannels = record.FindAll(it => it.BoardType != 1); List<ChannelStock> singleChannels = record.FindAll(it => it.BoardType != 1);
if ((singleChannels.Count > 0 ? singleChannels[0].BoardType : 1) == (Int32)BoardTypeEnum.smart|| (singleChannels.Count > 0 ? singleChannels[0].BoardType : 1) == (Int32)BoardTypeEnum.weighSmartBox) if ((singleChannels.Count > 0 ? singleChannels[0].BoardType : 1) == (Int32)BoardTypeEnum.smart || (singleChannels.Count > 0 ? singleChannels[0].BoardType : 1) == (Int32)BoardTypeEnum.weighSmartBox)
{ {
singleChannels.ForEach(it => singleChannels.ForEach(it =>
{ {
_portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.Quantity - it.TakeQuantity); _portUtil.WriteQuantityMethod(it.Quantity - it.TakeQuantity, it.DrawerNo, it.ColNo);
Thread.Sleep(200);
}); });
} }
RequestData(); RequestData();
@ -246,6 +455,7 @@ namespace DM_Weight.ViewModels
} }
Status = 0; Status = 0;
_isFinishClick = false; _isFinishClick = false;
_portUtil.ColNoLst = new List<int>();
} }
else else
{ {
@ -275,9 +485,9 @@ namespace DM_Weight.ViewModels
//检查是否是冰箱抽屉(冰箱抽屉打开时需要发送冰箱延迟报警的指令) //检查是否是冰箱抽屉(冰箱抽屉打开时需要发送冰箱延迟报警的指令)
public async Task CheckIsFridgeOpen() public async Task CheckIsFridgeOpen()
{ {
if(ChannelStocks!=null&& ChannelStocks.Count>0) if (ChannelStocks != null && ChannelStocks.Count > 0)
{ {
if (_portUtil.BoardType==(Int32)BoardTypeEnum.fridge) if (_portUtil.BoardType == (Int32)BoardTypeEnum.fridge)
{ {
_portUtil.FridgeOperate = true; _portUtil.FridgeOperate = true;
//发送冰箱延迟报警的指令 //发送冰箱延迟报警的指令
@ -291,11 +501,11 @@ namespace DM_Weight.ViewModels
{ {
if (ChannelStocks != null && ChannelStocks.Count > 0) if (ChannelStocks != null && ChannelStocks.Count > 0)
{ {
if (_portUtil.BoardType== (Int32)BoardTypeEnum.fridge) if (_portUtil.BoardType == (Int32)BoardTypeEnum.fridge)
{ {
string[] iTempertureRange = ConfigurationManager.AppSettings["temperatureRange"].Split('-'); string[] iTempertureRange = ConfigurationManager.AppSettings["temperatureRange"].Split('-');
//发送查询冰箱温度的指令 //发送查询冰箱温度的指令
float retT= await _portUtil.GetFridgeTemperature(); float retT = await _portUtil.GetFridgeTemperature();
if (retT > Convert.ToSingle(iTempertureRange[0]) && retT < Convert.ToSingle(iTempertureRange[1])) if (retT > Convert.ToSingle(iTempertureRange[0]) && retT < Convert.ToSingle(iTempertureRange[1]))
{ {
_portUtil.FridgeOperate = true; _portUtil.FridgeOperate = true;
@ -350,6 +560,10 @@ namespace DM_Weight.ViewModels
.Where(cs => cs.Quantity > 0) .Where(cs => cs.Quantity > 0)
.OrderBy(cs => cs.ColNo) .OrderBy(cs => cs.ColNo)
.ToList(); .ToList();
if (queryData != null && queryData.Count > 0)
{
OpenBoxVisibility = (queryData[0].BoardType == (Int32)BoardTypeEnum.box || queryData[0].BoardType == (Int32)BoardTypeEnum.weighBox || queryData[0].BoardType == (Int32)BoardTypeEnum.weighSmartBox) ? true : false;
}
ChannelStocks = queryData; ChannelStocks = queryData;
} }
@ -374,5 +588,98 @@ namespace DM_Weight.ViewModels
// 取消消息订阅 // 取消消息订阅
_eventAggregator.GetEvent<PortUtilEvent>().Unsubscribe(DoMyPrismEvent); _eventAggregator.GetEvent<PortUtilEvent>().Unsubscribe(DoMyPrismEvent);
} }
//关闭抽屉后获取称重稳定数量
public void GetWeightQuantity()
{
List<int[]> finalyQuantity = new List<int[]>();
new PromiseUtil<int>().taskAsyncLoop(200, 0, async (options, next, stop) =>
{
if (!_portUtil.Operate || Status == 0)
{
stop();
}
else
{
try
{
logger.Info("关闭抽屉后获取称重稳定数量");
if (finalyQuantity.Count >= 10)
{
for (int i = 0; i < finalyQuantity.Count; i++)
{
logger.Info($"finalyQuantity{i} {string.Join(",", finalyQuantity[i])}");
}
if (AreAllArraysEqual(finalyQuantity))
{
stop();
// 告诉前台数据变化
_eventAggregator.GetEvent<PortUtilEvent>().Publish(new util.DeviceMsg()
{
EventType = util.EventType.UPDATEQUANTITY,
WindowName = "DrawerTakeDrugWindow",
Quantitys = finalyQuantity[0]
});
logger.Info($"数量变化【{string.Join(",", finalyQuantity[0])}】");
// 重新初始化数据
_portUtil.ResetData();
CompleteIsEnable = true;
CancleIsEnable = true;
}
else
{
finalyQuantity.RemoveAt(0);
CancleIsEnable = true;
next();
}
}
else
{
if (finalyQuantity.Count >= 9)
{
CancleIsEnable = true;
}
else
{
CancleIsEnable = false;
}
CompleteIsEnable = false;
_portUtil.DrawerNo = DrawerNo;
int[] quantity = await _portUtil.CheckQuantityByAddrForMulti();
AfterQuantity = quantity;
int[] Quantitys = new int[BeforeQuantity.Length];
for (int i = 0; i < BeforeQuantity.Length; i++)
{
Quantitys[i] = BeforeQuantity[i] - AfterQuantity[i];
}
finalyQuantity.Add(Quantitys);
logger.Info($"Quantity{string.Join(",", Quantitys)}");
// 告诉前台数据变化
_eventAggregator.GetEvent<PortUtilEvent>().Publish(new util.DeviceMsg()
{
EventType = util.EventType.UPDATEQUANTITY,
WindowName = "DrawerTakeDrugWindow",
Quantitys = finalyQuantity[0]
});
next();
}
}
catch (Exception ex)
{
logger.Info($"关闭抽屉后获取称重稳定数量异常{ex.Message}");
next();
}
}
});
}
public bool AreAllArraysEqual(List<int[]> arrays)
{
if (arrays == null || arrays.Count == 0) return false;
// 取第一个数组作为参照进行比较
var referenceArray = arrays[0];
// 检查列表中除了第一个数组外的所有数组是否与第一个数组相等
return arrays.Skip(1).All(array => array.SequenceEqual(referenceArray));
}
} }
} }

View File

@ -2,6 +2,7 @@
using DM_Weight.msg; using DM_Weight.msg;
using DM_Weight.Port; using DM_Weight.Port;
using DM_Weight.util; using DM_Weight.util;
using log4net;
using Prism.Commands; using Prism.Commands;
using Prism.Events; using Prism.Events;
using Prism.Mvvm; using Prism.Mvvm;
@ -20,6 +21,7 @@ namespace DM_Weight.ViewModels
{ {
public class FridgeWindowViewModel : BindableBase, IRegionMemberLifetime, INavigationAware public class FridgeWindowViewModel : BindableBase, IRegionMemberLifetime, INavigationAware
{ {
private readonly ILog logger = LogManager.GetLogger(typeof(FridgeWindowViewModel));
//温度区间 //温度区间
private string _temperatureRange = CommonClass.ReadAppSetting("temperatureRange").ToString(); private string _temperatureRange = CommonClass.ReadAppSetting("temperatureRange").ToString();
public string TemperatureRange public string TemperatureRange
@ -28,10 +30,19 @@ namespace DM_Weight.ViewModels
set set
{ {
SetProperty(ref _temperatureRange, value); SetProperty(ref _temperatureRange, value);
//更新配置文件中冰箱温度区间
CommonClass.SaveAppSetting("temperatureRange", _temperatureRange);
} }
} }
//温度不在范围超时时间
private string _outRangeTime = CommonClass.ReadAppSetting("OutRangeTime").ToString();
public string OutRangeTime
{
get => _outRangeTime;
set
{
SetProperty(ref _outRangeTime, value);
}
}
private float defaultValue = Convert.ToSingle(CommonClass.ReadAppSetting("temperatureValue")); private float defaultValue = Convert.ToSingle(CommonClass.ReadAppSetting("temperatureValue"));
//温度值 //温度值
private float _temperatureValue = Convert.ToSingle(CommonClass.ReadAppSetting("temperatureValue")); private float _temperatureValue = Convert.ToSingle(CommonClass.ReadAppSetting("temperatureValue"));
@ -62,14 +73,14 @@ namespace DM_Weight.ViewModels
get => _btnIsEnable; get => _btnIsEnable;
set => SetProperty(ref _btnIsEnable, value); set => SetProperty(ref _btnIsEnable, value);
} }
//冰箱状态:true关;false开 //冰箱状态:true关1;false开0
private bool _fridgeState; private bool _fridgeState;
public bool FridgeState public bool FridgeState
{ {
get => _fridgeState; get => _fridgeState;
set => SetProperty(ref _fridgeState, value); set => SetProperty(ref _fridgeState, value);
} }
//报警状态:true关;false开 //报警状态:true关1;false开0
private bool _alarmState; private bool _alarmState;
public bool AlarmState public bool AlarmState
{ {
@ -77,9 +88,7 @@ namespace DM_Weight.ViewModels
set => SetProperty(ref _alarmState, value); set => SetProperty(ref _alarmState, value);
} }
private int _defaultLoginMode;//1开0关
private int _defaultAlarmMode;//1开0关
private float retTemperature = Convert.ToSingle(ConfigurationManager.AppSettings["temperatureValue"]); private float retTemperature = Convert.ToSingle(ConfigurationManager.AppSettings["temperatureValue"]);
@ -109,51 +118,58 @@ namespace DM_Weight.ViewModels
//{ //{
// ConfigurationManager.RefreshSection("FridgeState"); // ConfigurationManager.RefreshSection("FridgeState");
//发送冰箱使能/失能指令 //发送冰箱使能/失能指令
if (_fridgeState) if (FridgeState)
{ {
await _portUtil.FridgeOff(); await _portUtil.FridgeOff();
Thread.Sleep(100); Thread.Sleep(100);
CommonClass.SaveAppSetting("FridgeState", "0"); CommonClass.SaveAppSetting("FridgeState", "1");
//Configuration _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//_configuration.AppSettings.Settings["FridgeState"].Value = "1";
//_configuration.Save();
//ConfigurationManager.RefreshSection("FridgeState");
} }
else else
{ {
await _portUtil.FridegOpen(); await _portUtil.FridegOpen();
Thread.Sleep(100); Thread.Sleep(100);
CommonClass.SaveAppSetting("FridgeState", "1"); CommonClass.SaveAppSetting("FridgeState", "0");
//Configuration _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//_configuration.AppSettings.Settings["FridgeState"].Value = "0";
//_configuration.Save();
//ConfigurationManager.RefreshSection("FridgeState");
//冰箱打开定时获取冰箱温度
_eventAggregator.GetEvent<FridgeEvent>().Publish();
} }
//}
//温度报警设定
//if (AlarmState != _defaultAlarmMode.Equals(1))
//{
//发送警报使能/失能指令 //发送警报使能/失能指令
if (_alarmState) if (AlarmState)
{ {
await _portUtil.FridgeAlarmOff(); await _portUtil.FridgeAlarmOff();
Thread.Sleep(100); Thread.Sleep(100);
CommonClass.SaveAppSetting("AlarmState", "0"); CommonClass.SaveAppSetting("AlarmState", "1");
//Configuration _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//_configuration.AppSettings.Settings["AlarmState"].Value = "1";
//_configuration.Save();
//ConfigurationManager.RefreshSection("AlarmState");
} }
else else
{ {
await _portUtil.FridgeAlarmOn(); await _portUtil.FridgeAlarmOn();
Thread.Sleep(100); Thread.Sleep(100);
CommonClass.SaveAppSetting("AlarmState", "1"); CommonClass.SaveAppSetting("AlarmState", "0");
//Configuration _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//_configuration.AppSettings.Settings["AlarmState"].Value = "0";
//_configuration.Save();
//ConfigurationManager.RefreshSection("AlarmState");
} }
//} //设定冰箱1温度区间
//string[] range = ConfigurationManager.AppSettings["temperatureRange"].Split('-');
//if (retTemperature != TemperatureValue)
//{
// //设定冰箱温度
// await _portUtil.SetFridgeTemperature(TemperatureValue);
// CommonClass.SaveAppSetting("temperatureValue", TemperatureValue.ToString());
//}
//设定冰箱温度区间
string[] range = ConfigurationManager.AppSettings["temperatureRange"].Split('-');
string[] newRange = TemperatureRange.Split('-'); string[] newRange = TemperatureRange.Split('-');
if (range.Length >= 2) if (newRange.Length >= 2)
{ {
bool bMix = float.TryParse(range[0], out float Min); bool bMix = float.TryParse(newRange[0], out float Min);
bool bMax = float.TryParse(range[1], out float Max); bool bMax = float.TryParse(newRange[1], out float Max);
if (bMix && bMax) if (bMix && bMax)
{ {
@ -166,12 +182,27 @@ namespace DM_Weight.ViewModels
if (Max != Convert.ToSingle(newRange[1])) if (Max != Convert.ToSingle(newRange[1]))
{ {
Thread.Sleep(100); Thread.Sleep(100);
//设定冰箱温度最 //设定冰箱温度最
await _portUtil.FridgeMaxSetting(Convert.ToSingle(newRange[1])); await _portUtil.FridgeMaxSetting(Convert.ToSingle(newRange[1]));
Thread.Sleep(100); Thread.Sleep(100);
} }
} }
//Configuration _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//_configuration.AppSettings.Settings["TemperatureRange"].Value = TemperatureRange;
//_configuration.Save();
//ConfigurationManager.RefreshSection("TemperatureRange");
CommonClass.SaveAppSetting("TemperatureRange", TemperatureRange);
} }
//超时时间
if (OutRangeTime != null)
{
//Configuration _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//_configuration.AppSettings.Settings["OutRangeTime"].Value = OutRangeTime;
//_configuration.Save();
//ConfigurationManager.RefreshSection("OutRangeTime");
CommonClass.SaveAppSetting("OutRangeTime", OutRangeTime);
}
_portUtil.FridgeOperate = false; _portUtil.FridgeOperate = false;
AlertMsg alertMsg = new AlertMsg AlertMsg alertMsg = new AlertMsg
@ -180,13 +211,6 @@ namespace DM_Weight.ViewModels
Type = MsgType.SUCCESS Type = MsgType.SUCCESS
}; };
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg); _eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
//_fridgeState = ReadAppSetting("FridgeState").Equals(1);
//_defaultLoginMode = ReadAppSetting("FridgeState");
//_defaultAlarmMode = ReadAppSetting("AlarmState");
//_alarmState = ReadAppSetting("AlarmState").Equals(1);
//_temperatureRange = CommonClass.ReadAppSetting("temperatureRange");
//_temperatureValue = Convert.ToSingle(CommonClass.ReadAppSetting("temperatureValue"));
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -200,21 +224,17 @@ namespace DM_Weight.ViewModels
_portUtil.FridgeOperate = false; _portUtil.FridgeOperate = false;
} }
} }
public FridgeWindowViewModel()
{
}
//手动实现调用配置的逻辑 规避修改配置文件后不起作用的问题 //手动实现调用配置的逻辑 规避修改配置文件后不起作用的问题
public int ReadAppSetting(string key) //public int ReadAppSetting(string key)
{ //{
string xPath = "/configuration/appSettings//add[@key='" + key + "']"; // string xPath = "/configuration/appSettings//add[@key='" + key + "']";
XmlDocument doc = new XmlDocument(); // XmlDocument doc = new XmlDocument();
string exeFileName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; // string exeFileName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
doc.Load(exeFileName + ".dll.config"); // doc.Load(exeFileName + ".dll.config");
XmlNode node = doc.SelectSingleNode(xPath); // XmlNode node = doc.SelectSingleNode(xPath);
return Convert.ToInt32(node.Attributes["value"].Value); // logger.Info($"xPath:{xPath} exeFileName:{exeFileName} ReadAppSetting key:{key} value:{node.Attributes["value"].Value}");
} // return Convert.ToInt32(node.Attributes["value"].Value);
//}
public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback) public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
{ {
@ -222,12 +242,11 @@ namespace DM_Weight.ViewModels
public void OnNavigatedTo(NavigationContext navigationContext) public void OnNavigatedTo(NavigationContext navigationContext)
{ {
_fridgeState = ReadAppSetting("FridgeState").Equals(0); FridgeState = CommonClass.ReadAppSetting("FridgeState").Equals("1");
_defaultLoginMode = ReadAppSetting("FridgeState");
_defaultAlarmMode = ReadAppSetting("AlarmState"); AlarmState = CommonClass.ReadAppSetting("AlarmState").Equals("1");
_alarmState = ReadAppSetting("AlarmState").Equals(0);
GetTemperature();
} }
public bool IsNavigationTarget(NavigationContext navigationContext) public bool IsNavigationTarget(NavigationContext navigationContext)
@ -237,22 +256,7 @@ namespace DM_Weight.ViewModels
public void OnNavigatedFrom(NavigationContext navigationContext) public void OnNavigatedFrom(NavigationContext navigationContext)
{ {
} }
//public void OnNavigatedTo(NavigationContext navigationContext)
//{
// GetTemperature();
//}
//public bool IsNavigationTarget(NavigationContext navigationContext)
//{
// return true;
//}
//public void OnNavigatedFrom(NavigationContext navigationContext)
//{
//}
//获取冰箱温度值,如有更改则保存更改 //获取冰箱温度值,如有更改则保存更改
private async Task GetTemperature() private async Task GetTemperature()
{ {

View File

@ -25,6 +25,7 @@ using DM_Weight.msg;
using DM_Weight.Common; using DM_Weight.Common;
using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Logging;
using System.Threading; using System.Threading;
using System.Windows.Media;
namespace DM_Weight.ViewModels namespace DM_Weight.ViewModels
{ {
@ -40,12 +41,28 @@ namespace DM_Weight.ViewModels
/// </summary> /// </summary>
private string _wd = "恒温冷藏抽屉当前温度2.8(非真实数据)"; private string _wd = "恒温冷藏抽屉当前温度2.8(非真实数据)";
public string WD { get => _wd; set => SetProperty(ref _wd, value); } public string WD { get => _wd; set => SetProperty(ref _wd, value); }
System.Timers.Timer WDTimer; private SolidColorBrush _alertColor = Brushes.White;
public SolidColorBrush AlertColor
{
get => _alertColor;
set => SetProperty(ref _alertColor, value);
}
private int loginMode = Convert.ToInt32(ConfigurationManager.AppSettings["loginMode"]?.ToString() ?? "1"); private int loginMode = Convert.ToInt32(ConfigurationManager.AppSettings["loginMode"]?.ToString() ?? "1");
public bool MultiLogin public bool MultiLogin
{ {
get => loginMode == 2; get => loginMode == 2;
} }
//温度区间
private string TemperatureRange = CommonClass.ReadAppSetting("temperatureRange").ToString();
//温度不在区间计时器(超过配置文件中的时间后要报警)
public DateTime? FridgeTime { get; set; }
//冰箱是否异常状态:0正常1异常
//public string FridgeWorkingState = ConfigurationManager.AppSettings["FridgeworkingState"].ToString();
//冰箱开关状态:0开1关
public string FridgeState = ConfigurationManager.AppSettings["FridgeState"].ToString();
//冰箱渡不在区间超时时间
private string _outRangeTime = ConfigurationManager.AppSettings["OutRangeTime"].ToString();
public string OutRangeTime { get => _outRangeTime; set => SetProperty(ref _outRangeTime, value); }
private PremissionDm? _selectedMenu; private PremissionDm? _selectedMenu;
@ -186,7 +203,8 @@ namespace DM_Weight.ViewModels
IRegionManager _regionManager; IRegionManager _regionManager;
IUnityContainer _container; IUnityContainer _container;
//是否退出
bool IsLeave = false;
private bool _is16Drawer; private bool _is16Drawer;
public bool Is16Drawer { get => _is16Drawer; set => SetProperty(ref _is16Drawer, value); } public bool Is16Drawer { get => _is16Drawer; set => SetProperty(ref _is16Drawer, value); }
public bool KeepAlive => false; public bool KeepAlive => false;
@ -266,32 +284,6 @@ namespace DM_Weight.ViewModels
Is16Drawer = count == 16; Is16Drawer = count == 16;
} }
/// <summary> /// <summary>
/// 获取温度信息
/// </summary>
private async void GetWD(object sender, ElapsedEventArgs e)
{
if (!_portUtil.FridgeOperate)
{
string retStr = string.Empty;
byte[] data = null;
float retT = await _portUtil.GetFridgeTemperature();
Thread.Sleep(80);
WD = $"恒温冷藏抽屉当前温度:{Math.Round((retT - 1.5), 2)}℃";
}
}
private async void GetWD()
{
if (!_portUtil.FridgeOperate)
{
string retStr = string.Empty;
byte[] data = null;
float retT = await _portUtil.GetFridgeTemperature();
Thread.Sleep(80);
WD = $"恒温冷藏抽屉当前温度:{Math.Round((retT-1.5),2)}℃";
}
}
/// <summary>
/// 将收到的返回转换成具体温度数值 /// 将收到的返回转换成具体温度数值
/// </summary> /// </summary>
/// <param name="receiveData"></param> /// <param name="receiveData"></param>
@ -371,43 +363,229 @@ namespace DM_Weight.ViewModels
int autoExit = Convert.ToInt32(ConfigurationManager.AppSettings["autoExit"] ?? "0"); int autoExit = Convert.ToInt32(ConfigurationManager.AppSettings["autoExit"] ?? "0");
if (autoExit > 0) if (autoExit > 0)
{ {
System.Timers.Timer timer = new System.Timers.Timer(); //int interval = autoExit * 1000;
timer.Interval = 1000; new PromiseUtil<int>().taskAsyncLoop(1000, 0, async (options, next, stop) =>
timer.Elapsed += (sender, e) => {
try
{ {
// 串口无人操作
if (!_portUtil.Operate) if (!_portUtil.Operate)
{ {
// 30秒内无人操作鼠标键盘 // 无人操作鼠标键盘
if ((DateTime.Now - _portUtil.dateTime).TotalSeconds > autoExit && CheckComputerFreeState.GetLastInputTime() > autoExit) if ((DateTime.Now - _portUtil.dateTime).TotalSeconds > autoExit && CheckComputerFreeState.GetLastInputTime() > autoExit)
{ {
logger.Info($"设备30秒内无人操作用户【{Operator?.Nickname}】自动退出登录"); logger.Info($"设备{autoExit}内无人操作,用户【{Operator?.Nickname}】自动退出登录,_portUtil.Operate:{_portUtil.Operate},totalSecond:{(DateTime.Now - _portUtil.dateTime).TotalSeconds},lastInputTime:{CheckComputerFreeState.GetLastInputTime()},autoExit:{autoExit}");
Operator = null; Operator = null;
Reviewer = null; Reviewer = null;
Application.Current.Dispatcher.Invoke(() => //Application.Current.Dispatcher.Invoke(() =>
//{
stop();
System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{ {
_regionManager.RequestNavigate("MainRegion", "LoginWindow"); _regionManager.RequestNavigate("MainRegion", "LoginWindow");
timer.Stop(); }));
//});
//timer.Dispose();
}
else
{
if (Operator == null)
{
stop();
}
else
{
next();
}
}
}
else
{
_portUtil.dateTime = DateTime.Now;
next();
}
}
catch (Exception ex)
{
logger.Info($"自动退出异常:{ex.Message}");
}
}); });
} }
} GetFridgeTemperature();
};
timer.Start();
}
//#region 温度查询定时
//int interval = Convert.ToInt32(ConfigurationManager.AppSettings["Interval"]);
//if (interval > 0)
//{
// WDTimer = new System.Timers.Timer();
// WDTimer.Elapsed += new System.Timers.ElapsedEventHandler(GetWD); _eventAggregator.GetEvent<FridgeEvent>().Subscribe(GetFridgeTemperature);
// WDTimer.Interval = interval; }
// WDTimer.Start();
// //WDTimer.AutoReset = true;
// //WDTimer.Enabled = true; //获取冰箱温度定时
private void GetFridgeTemperature()
{
//根据配置文件中的 冰箱温度定时时间循环
logger.Info("获取冰箱温度定时");
int TemperatureTimer = Convert.ToInt32(CommonClass.ReadAppSetting("TemperatureTimer")) * 1000;
logger.Info($"获取冰箱温度定时-TemperatureTimer");
string[] tempRange = TemperatureRange.Split('-');
new PromiseUtil<int>().taskAsyncLoop(TemperatureTimer, 0, async (options, next, stop) =>
{
try
{
FridgeState = CommonClass.ReadAppSetting("FridgeState");
if (!_portUtil.FridgeOperate && FridgeState.Equals("0"))
{
string retStr = string.Empty;
byte[] data = null;
float retT = await _portUtil.GetFridgeTemperature();
Thread.Sleep(80);
WD = $"恒温冷藏抽屉当前温度:{Math.Round((retT), 2)}℃;";
AlertColor = Brushes.White;
logger.Info(WD);
if (tempRange != null && tempRange.Count() >= 2)
{
if (retT < Convert.ToSingle(tempRange[0]) || retT > Convert.ToSingle(tempRange[1]))
{
//查询制冷片温度
float retT2 = await _portUtil.GetFridgeTemperature2();
if (retT2 > 65)
{
if (!FridgeState.Equals("1"))
{
//停掉冰箱
await _portUtil.FridgeOff();
CommonClass.SaveAppSetting("FridgeState", "1");
//AlertMsg alertMsg = new AlertMsg
//{
// Message = $"冰箱制冷片温度超过65度已关闭冰箱制冷功能!!!",
// Type = MsgType.ERROR
//};
//_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{
DialogParameters dialogParameters = new DialogParameters();
dialogParameters.Add("warnMessage", "冰箱制冷片温度超过65度已关闭冰箱制冷功能!!!");
DialogServiceExtensions.ShowDialogHost(_dialogService, "WarnDialog", dialogParameters, DoDialogResult, "RootDialog");
}));
}
logger.Info($"制冷片温度超过65度");
Thread.Sleep(100);
//给出提示
WD += "冰箱温度异常,已关闭冰箱制冷功能";
AlertColor = Brushes.Red;
FridgeTime = null;
stop();
}
else
{
if (FridgeTime == null)
{
FridgeTime = DateTime.Now;
//温度不在范围,但没有超过时间
if (IsLeave)
{
FridgeTime = null;
stop();
}
else
{
next();
}
}
else
{
if ((DateTime.Now - FridgeTime.Value).TotalMinutes > Convert.ToInt32(OutRangeTime))
{
logger.Info($"冰箱温度不在范围内,超过{OutRangeTime}分钟");
//停掉冰箱
await _portUtil.FridgeOff();
Thread.Sleep(100);
CommonClass.SaveAppSetting("FridgeState", "0");
//给出提示
WD += "冰箱温度异常,已关闭冰箱制冷功能;";
AlertColor = Brushes.Red;
FridgeState = "1";
CommonClass.SaveAppSetting("FridgeState", "1");
//AlertMsg alertMsg = new AlertMsg
//{
// Message = $"冰箱温度异常,已关闭冰箱制冷功能!!!",
// Type = MsgType.ERROR
//};
//_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
{
DialogParameters dialogParameters = new DialogParameters();
dialogParameters.Add("warnMessage", "冰箱温度异常,已关闭冰箱制冷功能!!!");
DialogServiceExtensions.ShowDialogHost(_dialogService, "WarnDialog", dialogParameters, DoDialogResult, "RootDialog");
}));
FridgeTime = null;
stop();
}
else
{
//温度不在范围,但没有超过时间
if (IsLeave)
{
FridgeTime = null;
stop();
}
else
{
next();
}
}
}
}
}
else
{
if (IsLeave)
{
FridgeTime = null;
stop();
}
else
{
next();
}
}
}
else
{
logger.Info($"获取冰箱温度范围有误{TemperatureRange}");
//if (Convert.ToInt32(ConfigurationManager.AppSettings["hasFridge"]) > 1)
//{
// float retTemp = await _portUtil.GetFridgeTemperature(2);
// Thread.Sleep(80);
// WD += $"{retTemp}℃";
//} //}
//#endregion if (IsLeave)
//GetWD(); {
FridgeTime = null;
stop();
}
else
{
next();
}
}
}
else
{
WD = $"恒温冷藏抽屉串口关闭或冰箱制冷异常制冷关闭!!!";
AlertColor = Brushes.Red;
FridgeTime = null;
stop();
}
}
catch (Exception ex)
{
logger.Info($"获取冰箱异常:{ex.Message}");
next();
}
});
} }
//每次导航的时候该实列用不用重新创建true是不重新创建,false是重新创建 //每次导航的时候该实列用不用重新创建true是不重新创建,false是重新创建
@ -419,7 +597,9 @@ namespace DM_Weight.ViewModels
//这个方法用于拦截请求 //这个方法用于拦截请求
public void OnNavigatedFrom(NavigationContext navigationContext) public void OnNavigatedFrom(NavigationContext navigationContext)
{ {
IsLeave = true;
navigationContext.NavigationService.Region.RegionManager.Regions.Remove(PrismManager.SettingViewRegionName); navigationContext.NavigationService.Region.RegionManager.Regions.Remove(PrismManager.SettingViewRegionName);
_eventAggregator.GetEvent<FridgeEvent>().Unsubscribe(GetFridgeTemperature);
} }
} }
} }

View File

@ -247,18 +247,18 @@ namespace DM_Weight.ViewModels
for (int i = 0; i < record.Count; i++) for (int i = 0; i < record.Count; i++)
{ {
ChannelStock it = record[i]; ChannelStock it = record[i];
if (it.BoardType == (Int32)BoardTypeEnum.weigh && it.PosNo == 0) //if (it.BoardType == (Int32)BoardTypeEnum.weigh && it.PosNo == 0)
{ //{
_portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity); // _portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity);
} //}
// 更新数据 库存信息 // 更新数据 库存信息
SqlSugarHelper.Db.Updateable(new ChannelStock() SqlSugarHelper.Db.Updateable(new ChannelStock()
{ {
Quantity = it.Quantity + it.AddQuantity, Quantity = it.Quantity + it.AddQuantity,
PosNo = 1, PosNo = 1,
Id = it.Id,
ManuNo = it.ManuNo, ManuNo = it.ManuNo,
EffDate = it.EffDate, EffDate = it.EffDate,
Id = it.Id,
}).UpdateColumns(it => new { it.Quantity, it.ManuNo, it.EffDate, it.PosNo }).ExecuteCommand(); }).UpdateColumns(it => new { it.Quantity, it.ManuNo, it.EffDate, it.PosNo }).ExecuteCommand();
// 获取更新完库存后的药品库存 // 获取更新完库存后的药品库存
List<ChannelStock> nowChannels = SqlSugarHelper.Db.Queryable<ChannelStock>() List<ChannelStock> nowChannels = SqlSugarHelper.Db.Queryable<ChannelStock>()
@ -285,12 +285,12 @@ namespace DM_Weight.ViewModels
StockQuantity = nowChannels.Sum(it => it.Quantity) StockQuantity = nowChannels.Sum(it => it.Quantity)
}).ExecuteCommand(); }).ExecuteCommand();
//称重计数或称重+智能显示+管控药盒 类型需要 发26指令 //称重计数或称重+智能显示+管控药盒 类型需要 发26指令
if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox) //if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{ //{
//计数数量设置发送称重26指令 // //计数数量设置发送称重26指令
_portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity); // _portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity);
Thread.Sleep(80); // Thread.Sleep(80);
} //}
} }
return true; return true;
}); });
@ -303,7 +303,8 @@ namespace DM_Weight.ViewModels
{ {
singleChannels.ForEach(it => singleChannels.ForEach(it =>
{ {
_portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.Quantity + it.AddQuantity); _portUtil.WriteQuantityMethod(it.Quantity + it.AddQuantity,it.DrawerNo, it.ColNo);
Thread.Sleep(200);
}); });
} }

View File

@ -320,7 +320,7 @@ namespace DM_Weight.ViewModels
ManuNo = it.ManuNo, ManuNo = it.ManuNo,
EffDate = it.EffDate, EffDate = it.EffDate,
Id = it.Id, Id = it.Id,
}).UpdateColumns(it => new { it.Quantity, it.ManuNo, it.EffDate }).ExecuteCommand(); }).UpdateColumns(it => new { it.Quantity,it.ManuNo,it.EffDate }).ExecuteCommand();
// 获取更新完库存后的药品库存 // 获取更新完库存后的药品库存
List<ChannelStock> nowChannels = SqlSugarHelper.Db.Queryable<ChannelStock>() List<ChannelStock> nowChannels = SqlSugarHelper.Db.Queryable<ChannelStock>()
.Where(cs => cs.MachineId.Equals(it.MachineId)) .Where(cs => cs.MachineId.Equals(it.MachineId))
@ -346,12 +346,12 @@ namespace DM_Weight.ViewModels
StockQuantity = nowChannels.Sum(it => it.Quantity) StockQuantity = nowChannels.Sum(it => it.Quantity)
}).ExecuteCommand(); }).ExecuteCommand();
//称重计数或称重+智能显示+管控药盒 类型需要 发26指令 //称重计数或称重+智能显示+管控药盒 类型需要 发26指令
if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox) //if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{ //{
//计数数量设置发送称重26指令 // //计数数量设置发送称重26指令
_portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity); // _portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity);
Thread.Sleep(80); // Thread.Sleep(80);
} //}
} }
return true; return true;
}); });
@ -364,7 +364,8 @@ namespace DM_Weight.ViewModels
{ {
singleChannels.ForEach(it => singleChannels.ForEach(it =>
{ {
_portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.Quantity - it.TakeQuantity); _portUtil.WriteQuantityMethod(it.Quantity - it.TakeQuantity,it.DrawerNo, it.ColNo);
Thread.Sleep(200);
}); });
} }
AlertMsg alertMsg = new AlertMsg AlertMsg alertMsg = new AlertMsg

View File

@ -17,6 +17,7 @@ using DM_Weight.Views;
using Unity; using Unity;
using System.Threading; using System.Threading;
using System.Timers; using System.Timers;
using System.Configuration;
namespace DM_Weight.ViewModels namespace DM_Weight.ViewModels
{ {
@ -82,32 +83,30 @@ namespace DM_Weight.ViewModels
})); }));
#region //#region 温度查询定时
int interval = 60000; //int interval = Convert.ToInt32(ConfigurationManager.AppSettings["Interval"]);
if (interval > 0) //if (interval > 0)
{ //{
System.Timers.Timer doorTimer = new System.Timers.Timer(); // System.Timers.Timer doorTimer = new System.Timers.Timer();
doorTimer.Elapsed += new System.Timers.ElapsedEventHandler(doorStatus);
doorTimer.Interval = interval;
doorTimer.Start();
}
#endregion
// doorTimer.Elapsed += new System.Timers.ElapsedEventHandler(doorStatus);
// doorTimer.Interval = interval;
// doorTimer.Start();
//}
//#endregion
} }
/// <summary> /// <summary>
/// 监测后门是否打开 /// 监测后门是否打开
/// </summary> /// </summary>
private async void doorStatus(object sender, ElapsedEventArgs e) //private async void doorStatus(object sender, ElapsedEventArgs e)
{ //{
if (!_portUtil.Operate) // if (!_portUtil.Operate)
{ // {
//监测后门是否打开 // //监测后门是否打开
_portUtil.GetSingleBoardBackDoorState(); // _portUtil.GetSingleBoardBackDoorState();
} // }
} //}
void doMyPrismEvent2(AlertMsg msg) void doMyPrismEvent2(AlertMsg msg)
{ {
switch (msg.Type) switch (msg.Type)

View File

@ -405,12 +405,12 @@ namespace DM_Weight.ViewModels
}).ExecuteCommand(); }).ExecuteCommand();
//称重计数或称重+智能显示+管控药盒 类型需要 发26指令 //称重计数或称重+智能显示+管控药盒 类型需要 发26指令
if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox) //if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{ //{
//计数数量设置发送称重26指令 // //计数数量设置发送称重26指令
_portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity); // _portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity);
Thread.Sleep(80); // Thread.Sleep(80);
} //}
} }
//更新处方状态 //更新处方状态
SqlSugarHelper.Db.Updateable(new OrderInfo() SqlSugarHelper.Db.Updateable(new OrderInfo()
@ -432,7 +432,8 @@ namespace DM_Weight.ViewModels
{ {
singleChannels.ForEach(it => singleChannels.ForEach(it =>
{ {
_portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.Quantity - it.TakeQuantity); _portUtil.WriteQuantityMethod(it.Quantity - it.TakeQuantity,it.DrawerNo, it.ColNo);
Thread.Sleep(200);
}); });
} }
AlertMsg alertMsg = new AlertMsg AlertMsg alertMsg = new AlertMsg

View File

@ -342,12 +342,12 @@ namespace DM_Weight.ViewModels
StockQuantity = nowChannels.Sum(it => it.Quantity) StockQuantity = nowChannels.Sum(it => it.Quantity)
}).ExecuteCommand(); }).ExecuteCommand();
//称重计数或称重+智能显示+管控药盒 类型需要 发26指令 //称重计数或称重+智能显示+管控药盒 类型需要 发26指令
if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox) //if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{ //{
//计数数量设置发送称重26指令 // //计数数量设置发送称重26指令
_portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity); // _portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity);
Thread.Sleep(80); // Thread.Sleep(80);
} //}
} }
return true; return true;
}); });
@ -360,7 +360,8 @@ namespace DM_Weight.ViewModels
{ {
singleChannels.ForEach(it => singleChannels.ForEach(it =>
{ {
_portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.Quantity + it.TakeQuantity); _portUtil.WriteQuantityMethod(it.Quantity + it.TakeQuantity,it.DrawerNo, it.ColNo);
Thread.Sleep(200);
}); });
} }
AlertMsg alertMsg = new AlertMsg AlertMsg alertMsg = new AlertMsg

View File

@ -340,7 +340,7 @@ namespace DM_Weight.ViewModels
ManuNo = it.ManuNo, ManuNo = it.ManuNo,
EffDate = it.EffDate, EffDate = it.EffDate,
Id = it.Id, Id = it.Id,
}).UpdateColumns(it => new { it.Quantity, it.ManuNo, it.EffDate }).ExecuteCommand(); }).UpdateColumns(it => new { it.Quantity }).ExecuteCommand();
// 获取更新完库存后的药品库存 // 获取更新完库存后的药品库存
List<ChannelStock> nowChannels = SqlSugarHelper.Db.Queryable<ChannelStock>() List<ChannelStock> nowChannels = SqlSugarHelper.Db.Queryable<ChannelStock>()
.Where(cs => cs.MachineId.Equals(it.MachineId)) .Where(cs => cs.MachineId.Equals(it.MachineId))
@ -366,12 +366,12 @@ namespace DM_Weight.ViewModels
StockQuantity = nowChannels.Sum(it => it.Quantity) StockQuantity = nowChannels.Sum(it => it.Quantity)
}).ExecuteCommand(); }).ExecuteCommand();
//称重计数或称重+智能显示+管控药盒 类型需要 发26指令 //称重计数或称重+智能显示+管控药盒 类型需要 发26指令
if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox) //if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{ //{
//计数数量设置发送称重26指令 // //计数数量设置发送称重26指令
_portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity); // _portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity);
Thread.Sleep(80); // Thread.Sleep(80);
} //}
} }
return true; return true;
}); });
@ -383,7 +383,8 @@ namespace DM_Weight.ViewModels
{ {
singleChannels.ForEach(it => singleChannels.ForEach(it =>
{ {
_portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.Quantity - it.TakeQuantity); _portUtil.WriteQuantityMethod(it.Quantity - it.TakeQuantity,it.DrawerNo, it.ColNo);
Thread.Sleep(200);
}); });
} }
AlertMsg alertMsg = new AlertMsg AlertMsg alertMsg = new AlertMsg

View File

@ -226,14 +226,14 @@ namespace DM_Weight.ViewModels
List<OrderInfo> queryData = SqlSugarHelper.Db.Queryable<OrderInfo>() List<OrderInfo> queryData = SqlSugarHelper.Db.Queryable<OrderInfo>()
.InnerJoin<OrderDetail>((oi, od) => oi.OrderNo == od.OrderNo) .InnerJoin<OrderDetail>((oi, od) => oi.OrderNo == od.OrderNo)
.InnerJoin(SqlSugarHelper.Db.Queryable<ChannelStock>().Where(cs => cs.DrawerType == (Int32)DrawerTypeEnum.drawerTypeOne).Where(cs => cs.MachineId.Equals(ConfigurationManager.AppSettings["machineId"] ?? "DM1")).GroupBy(cs => cs.DrugId), (oi, od, t) => od.DrugId == t.DrugId) .InnerJoin(SqlSugarHelper.Db.Queryable<ChannelStock>().Where(cs => cs.DrawerType == (Int32)DrawerTypeEnum.drawerTypeOne).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.OrderDate.ToString("yyyy-MM-dd") == OrderDate) .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("OrderNo"), oi => oi.OrderNo == SearchValue)
.WhereIF(!String.IsNullOrEmpty(SearchValue) && SelectedItem.Code.Equals("PatientId"), oi => oi.PatientId == 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"]) .WhereIF(!String.IsNullOrEmpty(ConfigurationManager.AppSettings["storage"]), oi => oi.Pharmacy == ConfigurationManager.AppSettings["storage"])
.Where(oi => oi.DmStatus == 0) .Where(oi => oi.DmStatus == 0)
.Where(oi => oi.HisDispFlag == 0) .Where(oi => oi.HisDispFlag == 0)
.Where(oi => oi.CancelFlag == 0) .Where(oi => oi.CancelFlag == 0)
.GroupBy(oi => oi.OrderDate) .GroupBy(oi => oi.ChargeDate)
.Select(oi => oi) .Select(oi => oi)
.ToPageList(PageNum, PageSize, ref totalCount); .ToPageList(PageNum, PageSize, ref totalCount);
//.ToList(); //.ToList();
@ -245,7 +245,7 @@ namespace DM_Weight.ViewModels
//接收导航传过来的参数 现在是在此处初始化了表格数据 //接收导航传过来的参数 现在是在此处初始化了表格数据
public void OnNavigatedTo(NavigationContext navigationContext) public void OnNavigatedTo(NavigationContext navigationContext)
{ {
_eventAggregator.GetEvent<PortUtilEvent>().Subscribe(DoMyPrismEvent); //_eventAggregator.GetEvent<PortUtilEvent>().Subscribe(DoMyPrismEvent);
RequestData(); RequestData();
} }
@ -260,16 +260,16 @@ namespace DM_Weight.ViewModels
{ {
// 取消消息订阅 // 取消消息订阅
_eventAggregator.GetEvent<PortUtilEvent>().Unsubscribe(DoMyPrismEvent); //_eventAggregator.GetEvent<PortUtilEvent>().Unsubscribe(DoMyPrismEvent);
} }
void DoMyPrismEvent(DeviceMsg msg) //void DoMyPrismEvent(DeviceMsg msg)
{ //{
if (msg.EventType == EventType.CODESCAN) // if (msg.EventType == EventType.CODESCAN)
{ // {
SearchValue = msg.Code; // SearchValue = msg.Code;
} // }
} //}
} }
} }

View File

@ -273,12 +273,12 @@ namespace DM_Weight.ViewModels
StockQuantity = nowChannels.Sum(it => it.Quantity) StockQuantity = nowChannels.Sum(it => it.Quantity)
}).ExecuteCommand(); }).ExecuteCommand();
//称重计数或称重+智能显示+管控药盒 类型需要 发26指令 //称重计数或称重+智能显示+管控药盒 类型需要 发26指令
if (ChannelStock.BoardType == (Int32)BoardTypeEnum.weigh || ChannelStock.BoardType == (Int32)BoardTypeEnum.weighSmartBox) //if (ChannelStock.BoardType == (Int32)BoardTypeEnum.weigh || ChannelStock.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{ //{
//计数数量设置发送称重26指令 // //计数数量设置发送称重26指令
_portUtil.SetNumCount(ChannelStock.DrawerNo, ChannelStock.ColNo, ChannelStock.AddQuantity); // _portUtil.SetNumCount(ChannelStock.DrawerNo, ChannelStock.ColNo, ChannelStock.AddQuantity);
Thread.Sleep(80); // Thread.Sleep(80);
} //}
return true; return true;
}); });
if (f.Data) if (f.Data)
@ -286,7 +286,8 @@ namespace DM_Weight.ViewModels
// 更新屏显库存 // 更新屏显库存
if (ChannelStock.BoardType == (Int32)BoardTypeEnum.smart|| ChannelStock.BoardType == (Int32)BoardTypeEnum.weighSmartBox) if (ChannelStock.BoardType == (Int32)BoardTypeEnum.smart|| ChannelStock.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{ {
_portUtil.WriteQuantity(ChannelStock.DrawerNo, ChannelStock.ColNo, ChannelStock.Quantity + ReturnQuantity); _portUtil.WriteQuantityMethod(ChannelStock.Quantity + ReturnQuantity,ChannelStock.DrawerNo, ChannelStock.ColNo);
Thread.Sleep(200);
} }
AlertMsg alertMsg = new AlertMsg AlertMsg alertMsg = new AlertMsg

View File

@ -281,12 +281,12 @@ namespace DM_Weight.ViewModels
StockQuantity = nowChannels.Sum(it => it.Quantity) StockQuantity = nowChannels.Sum(it => it.Quantity)
}).ExecuteCommand(); }).ExecuteCommand();
//称重计数或称重+智能显示+管控药盒 类型需要 发26指令 //称重计数或称重+智能显示+管控药盒 类型需要 发26指令
if (ChannelStock.BoardType == (Int32)BoardTypeEnum.weigh || ChannelStock.BoardType == (Int32)BoardTypeEnum.weighSmartBox) //if (ChannelStock.BoardType == (Int32)BoardTypeEnum.weigh || ChannelStock.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{ //{
//计数数量设置发送称重26指令 // //计数数量设置发送称重26指令
_portUtil.SetNumCount(ChannelStock.DrawerNo, ChannelStock.ColNo, ChannelStock.AddQuantity); // _portUtil.SetNumCount(ChannelStock.DrawerNo, ChannelStock.ColNo, ChannelStock.AddQuantity);
Thread.Sleep(80); // Thread.Sleep(80);
} //}
} }
return true; return true;
@ -296,7 +296,8 @@ namespace DM_Weight.ViewModels
// 更新屏显库存 // 更新屏显库存
if (ChannelStock.BoardType == (Int32)BoardTypeEnum.smart|| ChannelStock.BoardType == (Int32)BoardTypeEnum.weighSmartBox) if (ChannelStock.BoardType == (Int32)BoardTypeEnum.smart|| ChannelStock.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{ {
_portUtil.WriteQuantity(ChannelStock.DrawerNo, ChannelStock.ColNo, ChannelStock.Quantity + ReturnQuantity); _portUtil.WriteQuantityMethod(ChannelStock.Quantity + ReturnQuantity,ChannelStock.DrawerNo, ChannelStock.ColNo);
Thread.Sleep(200);
} }
AlertMsg alertMsg = new AlertMsg AlertMsg alertMsg = new AlertMsg

View File

@ -11,6 +11,7 @@ using System.Threading.Tasks;
using DM_Weight.Models; using DM_Weight.Models;
using DM_Weight.util; using DM_Weight.util;
using DM_Weight.Common; using DM_Weight.Common;
using System.Configuration;
namespace DM_Weight.ViewModels namespace DM_Weight.ViewModels
{ {
@ -56,7 +57,7 @@ namespace DM_Weight.ViewModels
{ {
DialogParameters dialogParameters = new DialogParameters(); DialogParameters dialogParameters = new DialogParameters();
dialogParameters.Add("channel", Channel); dialogParameters.Add("channel", Channel);
DialogServiceExtensions.ShowDialogHost(_dialogService, "ReturnEmptyDialog", dialogParameters, DoDialogResult, "RootDialog"); DialogServiceExtensions.ShowDialogHost(_dialogService, "ReturnEmptyWithOrderDialog", dialogParameters, DoDialogResult, "RootDialog");
} }
}); });
} }
@ -100,7 +101,7 @@ namespace DM_Weight.ViewModels
Channels = SqlSugarHelper.Db.Queryable<ChannelStock>() Channels = SqlSugarHelper.Db.Queryable<ChannelStock>()
.LeftJoin<DrugInfo>((cs,di) => cs.DrugId == di.DrugId.ToString()) .LeftJoin<DrugInfo>((cs,di) => cs.DrugId == di.DrugId.ToString())
.Where((cs) => cs.DrawerType != (Int32)DrawerTypeEnum.drawerTypeOne) .Where((cs) => cs.DrawerType != (Int32)DrawerTypeEnum.drawerTypeOne && cs.MachineId == (ConfigurationManager.AppSettings["machineId"] ?? "DM1"))
.Select((cs, di) => new ChannelStock{ .Select((cs, di) => new ChannelStock{
CanReturnQuantity = SqlFunc.Subqueryable<MachineRecord>().Where(mr => mr.DrugId == cs.DrugId).Where(mr => mr.Type == 2).Where(mr => mr.Status != 2).Select(mr => SqlFunc.IsNull(SqlFunc.AggregateSumNoNull(mr.Quantity - mr.ReturnQuantity1 - mr.ReturnQuantity2), 0)) , CanReturnQuantity = SqlFunc.Subqueryable<MachineRecord>().Where(mr => mr.DrugId == cs.DrugId).Where(mr => mr.Type == 2).Where(mr => mr.Status != 2).Select(mr => SqlFunc.IsNull(SqlFunc.AggregateSumNoNull(mr.Quantity - mr.ReturnQuantity1 - mr.ReturnQuantity2), 0)) ,
DrugInfo = new DrugInfo DrugInfo = new DrugInfo

View File

@ -0,0 +1,716 @@
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<OrderTakeSelect> StaticOrderTakeSelects = new()
{
new OrderTakeSelect
{
Code = "OrderNo",
Name = "处方号"
},
new OrderTakeSelect
{
Code = "PatientId",
Name = "患者编号"
}
};
private List<OrderTakeSelect> _orderTakeSelects = StaticOrderTakeSelects;
public List<OrderTakeSelect> OrderTakeSelects
{
get { return _orderTakeSelects; }
set
{
SetProperty(ref _orderTakeSelects, value);
}
}
private OrderTakeSelect _selectedItem = StaticOrderTakeSelects[0];
/// <summary>
/// 查询条件 查询字段
/// </summary>
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<OrderInfo> _orderInfos = new();
public List<OrderInfo> OrderInfos { get { return _orderInfos; } set { SetProperty(ref _orderInfos, value); } }
private string _orderDate = DateTime.Now.ToString("yyyy-MM-dd");
/// <summary>
/// 查询条件 处方日期
/// </summary>
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;
/// <summary>
/// 查询条件 查询字段值
/// </summary>
public string? SearchValue
{
get { return _searchValue; }
set
{
SetProperty(ref _searchValue, value);
RequestData();
}
}
/// <summary>
/// 取药日期
/// </summary>
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<ChannelStock> __channelStocks = new List<ChannelStock>();
public List<ChannelStock> ChannelStocks
{
get => __channelStocks;
set => SetProperty(ref __channelStocks, value);
}
//回收箱库位
public ChannelStock? CStock;
private List<MachineRecord>? _machineRecords;
public List<MachineRecord>? MachineRecords
{
get => _machineRecords;
set => SetProperty(ref _machineRecords, value);
}
private List<OrderDetail>? _ordertails;
public List<OrderDetail>? OrderDetails
{
get => _ordertails;
set => SetProperty(ref _ordertails, value);
}
/// <summary>
/// 取药人列表
/// </summary>
private List<UserList>? _userLists = new() { new UserList() { UserName = "全部", Id = 0 } };
public List<UserList>? UserLists
{
get => _userLists;
set => SetProperty(ref _userLists, value);
}
/// <summary>
/// 选中取药人
/// </summary>
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<IGrouping<int, ChannelStock>> enumerable;
private IEnumerator<IGrouping<int, ChannelStock>> 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>("MachineRecord");
//}
// 委托 被动执行 被子窗口执行
// dialogResult 第一方面可以拿到任意参数 第二方面 可判断关闭状态
RequestData();
}
public bool KeepAlive => false;
public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
{
continuationCallback(true);
}
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
/// <summary>
/// 还空瓶按钮--打开抽屉
/// </summary>
public DelegateCommand OpenDrawer
{
get => new DelegateCommand(() =>
{
if (Status == 0)
{
if (OrderDetails != null && OrderDetails.Count > 0)
{
List<MachineRecord> records = OrderDetails[0].MachineRecords.Where(rd => rd.CurrentReturn > 0).ToList();
if (records != null && records.Count > 0)
{
CStock = SqlSugarHelper.Db.Queryable<ChannelStock>()
.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<SnackbarEvent>().Publish(alertMsg);
}
}
else
{
//未输入还空瓶数量
AlertMsg alertMsg = new AlertMsg
{
Message = "没有与之对应的取药记录或没有填写空瓶数量",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
}
}
else
{
AlertMsg alert = new AlertMsg
{
Message = "该处方下无药品明细",
Type = MsgType.ERROR
};
_eventAggregator.GetEvent<SnackbarEvent>().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<SnackbarEvent>().Publish(alert);
return false;
}
}
if (OrderDetails[0].MachineRecords != null && OrderDetails[0].MachineRecords.Count > 0)
{
List<MachineRecord> 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<SnackbarEvent>().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<ChannelStock>(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<SnackbarEvent>().Publish(alertMsg);
}
if (!f.IsSuccess)
{
AlertMsg alertMsg = new AlertMsg
{
Message = "操作失败!",
Type = MsgType.ERROR,
};
_eventAggregator.GetEvent<SnackbarEvent>().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<int, ChannelStock> groupingBefore = enumerator.Current;
//int DrawerNoBefore = groupingBefore.Key;
//if (enumerator.MoveNext())
//{
// IGrouping<int, ChannelStock> 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<SnackbarEvent>().Publish(alertMsg);
Status = 0;
break;
}
}
}
public void OnNavigatedFrom(NavigationContext navigationContext)
{
// 取消消息订阅
_eventAggregator.GetEvent<PortUtilEvent>().Unsubscribe(DoMyPrismEvent);
}
public void OnNavigatedTo(NavigationContext navigationContext)
{
//查询表格数据
RequestData();
BindUserList();
_eventAggregator.GetEvent<PortUtilEvent>().Subscribe(DoMyPrismEvent);
}
private void RequestData()
{
OrderInfos.Clear();
int totalCount = 0;
List<OrderInfo> queryData = SqlSugarHelper.Db.Queryable<OrderInfo>()
.InnerJoin<OrderDetail>((oi, od) => oi.OrderNo == od.OrderNo)
// .InnerJoin(SqlSugarHelper.Db.Queryable<ChannelStock>().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<OrderDetail>().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<UserList>().Distinct()
.InnerJoin<MachineRecord>((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<OrderDetail>()
.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<MachineRecord> machineRecords = new List<MachineRecord>();
machineRecords = SqlSugarHelper.Db.Queryable<MachineRecord>()
.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<ChannelList>()
// .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;
}
}
}
}

View File

@ -250,11 +250,17 @@ namespace DM_Weight.ViewModels
PremissionName = "归还药品", PremissionName = "归还药品",
PremissionPath = "ReturnDrugWindow2", PremissionPath = "ReturnDrugWindow2",
}; };
//PremissionDm huanyao2 = new PremissionDm
//{
// Id = 32,
// PremissionName = "归还空瓶",
// PremissionPath = "ReturnEmptyWindow",
//};
PremissionDm huanyao2 = new PremissionDm PremissionDm huanyao2 = new PremissionDm
{ {
Id = 32, Id = 32,
PremissionName = "归还空瓶", PremissionName = "归还空瓶",
PremissionPath = "ReturnEmptyWindow", PremissionPath = "ReturnWithOrderWindow",
}; };
PremissionDm huanyao3 = new PremissionDm PremissionDm huanyao3 = new PremissionDm
{ {

View File

@ -272,12 +272,12 @@ namespace DM_Weight.ViewModels
StockQuantity = nowChannels.Sum(it => it.Quantity) StockQuantity = nowChannels.Sum(it => it.Quantity)
}).ExecuteCommand(); }).ExecuteCommand();
//称重计数或称重+智能显示+管控药盒 类型需要 发26指令 //称重计数或称重+智能显示+管控药盒 类型需要 发26指令
if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox) //if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{ //{
//计数数量设置发送称重26指令 // //计数数量设置发送称重26指令
_portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity); // _portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity);
Thread.Sleep(80); // Thread.Sleep(80);
} //}
} }
return true; return true;
}); });
@ -290,7 +290,8 @@ namespace DM_Weight.ViewModels
{ {
singleChannels.ForEach(it => singleChannels.ForEach(it =>
{ {
_portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.Quantity + it.AddQuantity); _portUtil.WriteQuantityMethod(it.Quantity + it.AddQuantity,it.DrawerNo, it.ColNo);
Thread.Sleep(200);
}); });
} }

View File

@ -101,7 +101,7 @@ namespace DM_Weight.ViewModels
case EventType.UPDATEQUANTITY: case EventType.UPDATEQUANTITY:
if (Status == 1) if (Status == 1)
{ {
logger.Info($"抽屉【{DrawerNo}】库位药品数量【{msg.Quantitys}】"); logger.Info($"抽屉【{DrawerNo}】库位药品数量【{string.Join(",", msg.Quantitys)}】");
} }
break; break;
// 打开失败 // 打开失败
@ -249,12 +249,12 @@ namespace DM_Weight.ViewModels
StockQuantity = nowChannels.Sum(it => it.Quantity) StockQuantity = nowChannels.Sum(it => it.Quantity)
}).ExecuteCommand(); }).ExecuteCommand();
//称重计数或称重+智能显示+管控药盒 类型需要 发26指令 //称重计数或称重+智能显示+管控药盒 类型需要 发26指令
if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox) //if (it.BoardType == (Int32)BoardTypeEnum.weigh || it.BoardType == (Int32)BoardTypeEnum.weighSmartBox)
{ //{
//计数数量设置发送称重26指令 // //计数数量设置发送称重26指令
_portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity); // _portUtil.SetNumCount(it.DrawerNo, it.ColNo, it.AddQuantity);
Thread.Sleep(80); // Thread.Sleep(80);
} //}
} }
return true; return true;
}); });
@ -267,7 +267,8 @@ namespace DM_Weight.ViewModels
{ {
singleChannels.ForEach(it => singleChannels.ForEach(it =>
{ {
_portUtil.WriteQuantity(it.DrawerNo, it.ColNo, it.Quantity - it.TakeQuantity); _portUtil.WriteQuantityMethod(it.Quantity - it.TakeQuantity,it.DrawerNo, it.ColNo);
Thread.Sleep(200);
}); });
} }

View File

@ -0,0 +1,50 @@
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DM_Weight.ViewModels
{
public class WarnDialogViewModel:BindableBase, IDialogAware, IRegionMemberLifetime
{
private string _warnMessage;
public string WarnMessage
{
get => _warnMessage;
set => SetProperty(ref _warnMessage, value);
}
public string Title => "警告";
public bool KeepAlive => false;
public event Action<IDialogResult> RequestClose;
public bool CanCloseDialog()
{
return true;
}
public void OnDialogClosed()
{
}
public void OnDialogOpened(IDialogParameters parameters)
{
WarnMessage=parameters.GetValue<string>("warnMessage");
}
public DelegateCommand CancleTake
{
get => new DelegateCommand(() =>
{
RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel));
});
}
}
}

View File

@ -16,6 +16,8 @@
<convert:InputQuantityConverter x:Key="InputQuantityConverter" /> <convert:InputQuantityConverter x:Key="InputQuantityConverter" />
<convert:DrawerBtnVisiConverter x:Key="DrawerBtnVisiConverter" /> <convert:DrawerBtnVisiConverter x:Key="DrawerBtnVisiConverter" />
<convert:BiaoDingStatusConverter x:Key="BiaoDingStatusConverter" /> <convert:BiaoDingStatusConverter x:Key="BiaoDingStatusConverter" />
<convert:OpenBoxConverter x:Key="OpenBoxConverter" />
<FrameworkElement x:Key="ProxyElement" DataContext="{Binding}"/>
<!--<convert:BiaoDingBtnVisibleConverter x:Key="BiaoDingBtnVisibleConverter" /> <!--<convert:BiaoDingBtnVisibleConverter x:Key="BiaoDingBtnVisibleConverter" />
<convert:BiaoDingBtnVisibleConverter x:Key="BiaoDingQuantityConverter" />--> <convert:BiaoDingBtnVisibleConverter x:Key="BiaoDingQuantityConverter" />-->
<Style x:Key="st" TargetType="GridViewColumnHeader"> <Style x:Key="st" TargetType="GridViewColumnHeader">
@ -181,16 +183,26 @@
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition /> <RowDefinition />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<ContentControl Content="{StaticResource ProxyElement}" Visibility="Collapsed"/>
<StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Right"> <StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Right">
<TextBlock Text="放好药品后击确认按钮,点击按钮后勿触碰抽屉" Foreground="Red" Margin="1 10 10 1" Visibility="{Binding Status,Converter={StaticResource BiaoDingStatusConverter},ConverterParameter=ConfirmVisibi}"/> <TextBlock Text="点击【开药盒】按钮打开药盒开始标定" FontWeight="Bold" Margin="1 10 10 1" />
<Button <Button
Margin="0 0 3 0" Margin="0 0 3 0"
VerticalAlignment="Center" VerticalAlignment="Center"
Command="{Binding OpenDrawer}" Command="{Binding OpenDrawer}"
Style="{StaticResource MaterialDesignOutlinedLightButton}"
materialDesign:ButtonProgressAssist.IsIndicatorVisible="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=opearBtnLoading}"
materialDesign:ButtonProgressAssist.IsIndeterminate="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=opearBtnLoading}"
Content="开抽屉" />
<!--<Button
Margin="0 0 3 0"
VerticalAlignment="Center"
Command="{Binding BiaoDingCommand}"
materialDesign:ButtonProgressAssist.IsIndicatorVisible="{Binding Status,Converter={StaticResource BiaoDingStatusConverter},ConverterParameter=BiaoDingLoading}" materialDesign:ButtonProgressAssist.IsIndicatorVisible="{Binding Status,Converter={StaticResource BiaoDingStatusConverter},ConverterParameter=BiaoDingLoading}"
materialDesign:ButtonProgressAssist.IsIndeterminate="{Binding Status,Converter={StaticResource BiaoDingStatusConverter},ConverterParameter=BiaoDingLoading}" materialDesign:ButtonProgressAssist.IsIndeterminate="{Binding Status,Converter={StaticResource BiaoDingStatusConverter},ConverterParameter=BiaoDingLoading}"
Style="{StaticResource MaterialDesignOutlinedLightButton}"
IsEnabled="{Binding Status,Converter={StaticResource BiaoDingStatusConverter},ConverterParameter=BiaoDingBtnFlag}" Style="{StaticResource MaterialDesignOutlinedLightButton}"
Content="标定" /> Content="标定" />
<Button <Button
@ -210,7 +222,7 @@
Command="{Binding CancleTake}" Command="{Binding CancleTake}"
Visibility="{Binding Status,Converter={StaticResource BiaoDingStatusConverter},ConverterParameter=CancelVisibi}" Visibility="{Binding Status,Converter={StaticResource BiaoDingStatusConverter},ConverterParameter=CancelVisibi}"
Style="{StaticResource MaterialDesignOutlinedLightButton}" Style="{StaticResource MaterialDesignOutlinedLightButton}"
Content="取消" /> Content="取消" />-->
</StackPanel> </StackPanel>
<DataGrid <DataGrid
Padding="0 6 0 0" Padding="0 6 0 0"
@ -219,14 +231,13 @@
ItemsSource="{Binding ChannelStocks,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding CStock,Mode=TwoWay}" ItemsSource="{Binding ChannelStocks,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding CStock,Mode=TwoWay}"
materialDesign:DataGridAssist.EnableEditBoxAssist="False" materialDesign:DataGridAssist.EnableEditBoxAssist="False"
materialDesign:DataGridAssist.CellPadding="13" materialDesign:DataGridAssist.CellPadding="13"
SelectionUnit="Cell"
CanUserAddRows="False" CanUserAddRows="False"
AutoGenerateColumns="False"> AutoGenerateColumns="False">
<i:Interaction.Triggers> <!--<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged"> <i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectionChangedCommand}" /> <i:InvokeCommandAction Command="{Binding SelectionChangedCommand}" />
</i:EventTrigger> </i:EventTrigger>
</i:Interaction.Triggers> </i:Interaction.Triggers>-->
<DataGrid.Resources> <DataGrid.Resources>
<Style TargetType="{x:Type DataGridColumnHeader}" BasedOn="{StaticResource MaterialDesignDataGridColumnHeader}"> <Style TargetType="{x:Type DataGridColumnHeader}" BasedOn="{StaticResource MaterialDesignDataGridColumnHeader}">
<Setter Property="Background" Value="#31ccec" /> <Setter Property="Background" Value="#31ccec" />
@ -296,7 +307,7 @@
Header="状态" Header="状态"
IsReadOnly="True" IsReadOnly="True"
ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/> ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/>
<DataGridTemplateColumn Width="100" Header="添加数量"> <!--<DataGridTemplateColumn Width="100" Header="标定数量">
<DataGridTemplateColumn.CellTemplate> <DataGridTemplateColumn.CellTemplate>
<DataTemplate> <DataTemplate>
<TextBox IsEnabled="{Binding PosNo,Converter={StaticResource BiaoDingStatusConverter},ConverterParameter=AddQuantityEnabled}" Style="{StaticResource MaterialDesignDataGridTextColumnEditingStyle}"> <TextBox IsEnabled="{Binding PosNo,Converter={StaticResource BiaoDingStatusConverter},ConverterParameter=AddQuantityEnabled}" Style="{StaticResource MaterialDesignDataGridTextColumnEditingStyle}">
@ -311,6 +322,13 @@
</TextBox> </TextBox>
</DataTemplate> </DataTemplate>
</DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>-->
<DataGridTemplateColumn Width="100" Header="操作">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="开药盒" Command="{Binding DataContext.OpenBoxCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}" CommandParameter="{Binding}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn> </DataGridTemplateColumn>
</DataGrid.Columns> </DataGrid.Columns>
</DataGrid> </DataGrid>

View File

@ -0,0 +1,102 @@
<UserControl x:Class="DM_Weight.Views.Dialog.BiaoDingDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:DM_Weight.Views.Dialog"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
xmlns:convert="clr-namespace:DM_Weight.Converter"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
mc:Ignorable="d"
MinWidth="380" Width="Auto"
Height="Auto">
<UserControl.Resources>
<convert:StatusConverter x:Key="StatusConverter" />
</UserControl.Resources>
<materialDesign:Card Padding="0">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid Background="#03a9f4" Grid.Row="0">
<TextBlock VerticalAlignment="Center" Foreground="{DynamicResource PrimaryHueDarkForegroundBrush}" Margin="16 4 16 4" Style="{StaticResource MaterialDesignHeadline5TextBlock}" Text="{Binding TitleStr}" />
<Button
Style="{StaticResource MaterialDesignIconForegroundButton}"
Foreground="{DynamicResource PrimaryHueDarkForegroundBrush}"
HorizontalAlignment="Right"
Command="{Binding BtnCloseCommand}"
ToolTip="关闭"
>
<materialDesign:PackIcon Kind="Close" Width="34" Height="34" />
</Button>
</Grid>
<StackPanel Grid.Row="1" Margin="0">
<TextBlock Text="{Binding StrMessage}" Foreground="Red" Margin="12" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" />
<TextBox Height="50" Width="200"
Grid.Column="1"
materialDesign:HintAssist.Hint="标定数量"
Margin="6 0 0 10" Text="{Binding BDQuantity, UpdateSourceTrigger=PropertyChanged}"
Style="{StaticResource MaterialDesignOutlinedTextBox}">
</TextBox>
</StackPanel>
<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal" Grid.Column="1" HorizontalAlignment="Center" Margin="6">
<Button Margin="6"
Style="{StaticResource MaterialDesignRaisedAccentButton}"
Visibility="{Binding Status,Converter={StaticResource StatusConverter}, ConverterParameter=clearVisuability}"
materialDesign:ButtonProgressAssist.IsIndicatorVisible="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=clearBtnLoading}"
materialDesign:ButtonProgressAssist.IsIndeterminate="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=clearBtnLoading}"
Content="清空"
Command="{Binding ClearCommand}"></Button>
<Button
Margin="6"
Style="{StaticResource MaterialDesignRaisedAccentButton}"
materialDesign:ButtonProgressAssist.IsIndicatorVisible="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=biaoDingBtnLoading}"
materialDesign:ButtonProgressAssist.IsIndeterminate="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=biaoDingBtnLoading}"
Content="标定" IsEnabled="{Binding BiaoDingEnable}"
Command="{Binding BiaoDingCommand}">
</Button>
<Button
Margin="6"
Visibility="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=CancelBtn}"
Style="{StaticResource MaterialDesignRaisedButton}"
Background="Orange"
BorderBrush="Orange"
Content="取消"
Command="{Binding CancelCommand}" />
<!--<Button
Margin="2"
Visibility="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=CompleteBtn}"
Style="{StaticResource MaterialDesignRaisedAccentButton}"
Content="完成"
Command="{Binding FinishCommand}"/>-->
<!--<Button
Margin="6"
Visibility="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=CancelBtn}"
Style="{StaticResource MaterialDesignRaisedButton}"
Background="Orange"
BorderBrush="Orange"
Content="取消"
Command="{Binding CancelCommand}" />-->
</StackPanel>
</Grid>
<materialDesign:Snackbar
Background="{Binding SnackbarBackground}"
MessageQueue="{Binding SnackbarMessageQueue}"/>
</Grid>
</materialDesign:Card>
</UserControl>

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace DM_Weight.Views.Dialog
{
/// <summary>
/// BiaoDingDialog.xaml 的交互逻辑
/// </summary>
public partial class BiaoDingDialog : UserControl
{
public BiaoDingDialog()
{
InitializeComponent();
}
}
}

View File

@ -155,7 +155,6 @@
Visibility="{Binding Quantity, Converter={StaticResource NotZeroToVisibilityConverter}}" Visibility="{Binding Quantity, Converter={StaticResource NotZeroToVisibilityConverter}}"
Text="{Binding Quantity, StringFormat=({0})}" /> Text="{Binding Quantity, StringFormat=({0})}" />
</StackPanel> </StackPanel>
<TextBlock <TextBlock
HorizontalAlignment="Left" HorizontalAlignment="Left"
Grid.Row="1" Grid.Row="1"

View File

@ -151,7 +151,7 @@
ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}" ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"
EditingElementStyle="{StaticResource MaterialDesignDataGridTextColumnEditingStyle}" EditingElementStyle="{StaticResource MaterialDesignDataGridTextColumnEditingStyle}"
/> />
<DataGridTextColumn Width="130" <!--<DataGridTextColumn Width="130"
Header="批次" Header="批次"
IsReadOnly="True" IsReadOnly="True"
Binding="{Binding ManuNo}" Binding="{Binding ManuNo}"
@ -164,7 +164,7 @@
Binding="{Binding EffDate}" Binding="{Binding EffDate}"
ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}" ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"
EditingElementStyle="{StaticResource MaterialDesignDataGridTextColumnEditingStyle}" EditingElementStyle="{StaticResource MaterialDesignDataGridTextColumnEditingStyle}"
/> />-->
<DataGridTextColumn Width="100" <DataGridTextColumn Width="100"
Header="取出数量" Header="取出数量"
IsReadOnly="True" IsReadOnly="True"

View File

@ -35,7 +35,7 @@
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition Height="50" /> <RowDefinition Height="50" />
<RowDefinition Height="Auto" /> <RowDefinition Height="300" />
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Grid Background="#03a9f4" Grid.Row="0"> <Grid Background="#03a9f4" Grid.Row="0">
@ -130,6 +130,10 @@
<Style TargetType="{x:Type GridViewColumnHeader}" BasedOn="{StaticResource {x:Type GridViewColumnHeader}}"> <Style TargetType="{x:Type GridViewColumnHeader}" BasedOn="{StaticResource {x:Type GridViewColumnHeader}}">
<Setter Property="Foreground" Value="White" /> <Setter Property="Foreground" Value="White" />
</Style> </Style>
<Style TargetType="ScrollViewer">
<Setter Property="HorizontalScrollBarVisibility" Value="Visible"/>
<Setter Property="VerticalScrollBarVisibility" Value="Visible"/>
</Style>
</ListView.Resources> </ListView.Resources>
<ListView.View> <ListView.View>
<GridView ColumnHeaderContainerStyle="{StaticResource st}"> <GridView ColumnHeaderContainerStyle="{StaticResource st}">

View File

@ -81,7 +81,7 @@
ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}" ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"
EditingElementStyle="{StaticResource MaterialDesignDataGridTextColumnEditingStyle}" EditingElementStyle="{StaticResource MaterialDesignDataGridTextColumnEditingStyle}"
/> />
<DataGridTextColumn <!--<DataGridTextColumn
Header="批次" Header="批次"
IsReadOnly="True" IsReadOnly="True"
Binding="{Binding ManuNo}" Binding="{Binding ManuNo}"
@ -94,7 +94,7 @@
Binding="{Binding EffDate}" Binding="{Binding EffDate}"
ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}" ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"
EditingElementStyle="{StaticResource MaterialDesignDataGridTextColumnEditingStyle}" EditingElementStyle="{StaticResource MaterialDesignDataGridTextColumnEditingStyle}"
/> />-->
<DataGridTextColumn <DataGridTextColumn
Header="取出数量" Header="取出数量"
IsReadOnly="True" IsReadOnly="True"

View File

@ -0,0 +1,40 @@
<UserControl x:Class="DM_Weight.Views.Dialog.WarnDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:DM_Weight.Views.Dialog"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="2*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid Grid.Row="0" Background="#FFD32F2F" Grid.ColumnSpan="3">
<TextBlock Text="警告" HorizontalAlignment="Center" FontSize="20" FontWeight="Bold" Foreground="White" Margin="16 4 16 4" VerticalAlignment="Center"/>
</Grid>
<TextBlock Grid.Row="1" Grid.RowSpan="2" Grid.ColumnSpan="3" VerticalAlignment="Center"
Margin="16 14 16 4" FontSize="16" FontWeight="Bold"
Style="{StaticResource MaterialDesignHeadline5TextBlock}"
Text="{Binding WarnMessage,UpdateSourceTrigger=PropertyChanged}" TextWrapping="Wrap" />
<Button Grid.Row="3" Grid.Column="1"
Margin="6"
Style="{StaticResource MaterialDesignOutlinedLightButton}"
Content="确认"
Command="{Binding CancleTake}" />
</Grid>
</UserControl>

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace DM_Weight.Views.Dialog
{
/// <summary>
/// WarnDialog.xaml 的交互逻辑
/// </summary>
public partial class WarnDialog : UserControl
{
public WarnDialog()
{
InitializeComponent();
}
}
}

View File

@ -15,6 +15,8 @@
<convert:StatusConverter x:Key="StatusConverter" /> <convert:StatusConverter x:Key="StatusConverter" />
<convert:InputQuantityConverter x:Key="InputQuantityConverter" /> <convert:InputQuantityConverter x:Key="InputQuantityConverter" />
<convert:QuantityCountConverter x:Key="QuantityCountConverter"/> <convert:QuantityCountConverter x:Key="QuantityCountConverter"/>
<convert:OpenBoxConverter x:Key="OpenBoxConverter" />
<FrameworkElement x:Key="ProxyElement" DataContext="{Binding}"/>
</UserControl.Resources> </UserControl.Resources>
<Grid> <Grid>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
@ -22,7 +24,7 @@
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
<ColumnDefinition /> <ColumnDefinition />
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<ContentControl Content="{StaticResource ProxyElement}" Visibility="Collapsed"/>
<Grid Margin="0" Grid.Column="0" Width="280" Height="570" Visibility="{Binding Is8Drawer, Converter={StaticResource BooleanToVisibilityConverter}}"> <Grid Margin="0" Grid.Column="0" Width="280" Height="570" Visibility="{Binding Is8Drawer, Converter={StaticResource BooleanToVisibilityConverter}}">
<Grid.Background> <Grid.Background>
<ImageBrush ImageSource="/Images/box.png" /> <ImageBrush ImageSource="/Images/box.png" />
@ -165,7 +167,7 @@
VerticalAlignment="Center" VerticalAlignment="Center"
Command="{Binding TakeFinish}" Command="{Binding TakeFinish}"
Visibility="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=CompleteBtn}" Visibility="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=CompleteBtn}"
Style="{StaticResource MaterialDesignOutlinedLightButton}" Style="{StaticResource MaterialDesignOutlinedLightButton}" IsEnabled="{Binding CompleteIsEnable}"
Content="完成" /> Content="完成" />
<Button <Button
@ -174,6 +176,7 @@
Command="{Binding CancleTake}" Command="{Binding CancleTake}"
Visibility="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=CancelBtn}" Visibility="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=CancelBtn}"
Style="{StaticResource MaterialDesignOutlinedLightButton}" Style="{StaticResource MaterialDesignOutlinedLightButton}"
IsEnabled="{Binding CancleIsEnable}"
Content="取消" /> Content="取消" />
</StackPanel> </StackPanel>
<DataGrid <DataGrid
@ -183,6 +186,7 @@
ItemsSource="{Binding ChannelStocks}" ItemsSource="{Binding ChannelStocks}"
materialDesign:DataGridAssist.EnableEditBoxAssist="False" materialDesign:DataGridAssist.EnableEditBoxAssist="False"
materialDesign:DataGridAssist.CellPadding="13" materialDesign:DataGridAssist.CellPadding="13"
HorizontalScrollBarVisibility="Visible"
SelectionUnit="Cell" SelectionUnit="Cell"
CanUserAddRows="False" CanUserAddRows="False"
AutoGenerateColumns="False" ScrollViewer.HorizontalScrollBarVisibility="Hidden"> AutoGenerateColumns="False" ScrollViewer.HorizontalScrollBarVisibility="Hidden">
@ -206,12 +210,12 @@
</Style> </Style>
</DataGrid.Resources> </DataGrid.Resources>
<DataGrid.Columns> <DataGrid.Columns>
<DataGridTextColumn Width="80" <DataGridTextColumn Width="60"
Binding="{Binding ColNo}" Binding="{Binding ColNo}"
Header="库位" Header="库位"
IsReadOnly="True" IsReadOnly="True"
ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/> ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/>
<DataGridTextColumn Width="181" <!--<DataGridTextColumn Width="181"
Binding="{Binding DrugInfo.DrugName}" Binding="{Binding DrugInfo.DrugName}"
Header="药品名称" Header="药品名称"
IsReadOnly="True" IsReadOnly="True"
@ -220,8 +224,31 @@
Binding="{Binding DrugInfo.DrugSpec}" Binding="{Binding DrugInfo.DrugSpec}"
Header="规格" Header="规格"
IsReadOnly="True" IsReadOnly="True"
ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/> ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/>-->
<DataGridTextColumn Width="100" <DataGridTemplateColumn Header="药品名称">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<TextBlock TextAlignment="Center" Text="{Binding DrugInfo.DrugName}"/>
<TextBlock TextAlignment="Center" Text="{Binding DrugInfo.DrugSpec}"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="批次">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<TextBlock TextAlignment="Center" Text="{Binding ManuNo}"/>
<TextBlock TextAlignment="Center" Text="{Binding EffDate}"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!--<DataGridTextColumn Width="100"
Binding="{Binding ManuNo}" Binding="{Binding ManuNo}"
Header="批次" Header="批次"
IsReadOnly="True" IsReadOnly="True"
@ -230,7 +257,7 @@
Binding="{Binding EffDate}" Binding="{Binding EffDate}"
Header="效期" Header="效期"
IsReadOnly="True" IsReadOnly="True"
ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/> ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/>-->
<!--<DataGridTemplateColumn Width="200" IsReadOnly="True" <!--<DataGridTemplateColumn Width="200" IsReadOnly="True"
Header="批次"> Header="批次">
<DataGridTemplateColumn.CellTemplate> <DataGridTemplateColumn.CellTemplate>
@ -279,7 +306,7 @@
</Binding> </Binding>
</DataGridTextColumn.Binding> </DataGridTextColumn.Binding>
</DataGridTextColumn>--> </DataGridTextColumn>-->
<DataGridTemplateColumn Width="100" <DataGridTemplateColumn Width="90"
Header="添加数量"> Header="添加数量">
<DataGridTemplateColumn.CellTemplate> <DataGridTemplateColumn.CellTemplate>
<DataTemplate> <DataTemplate>
@ -296,7 +323,14 @@
</DataTemplate> </DataTemplate>
</DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn> </DataGridTemplateColumn>
<DataGridTemplateColumn Width="100"
Header="操作" Visibility="{Binding DataContext.OpenBoxVisibility,Source={StaticResource ProxyElement},Converter={StaticResource OpenBoxConverter}}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="开药盒" Command="{Binding DataContext.OpenBoxCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}" CommandParameter="{Binding}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns> </DataGrid.Columns>
</DataGrid> </DataGrid>
<!--<ListView <!--<ListView

View File

@ -15,12 +15,16 @@
<convert:DrawerSelectConverter x:Key="DrawerSelectConverter" /> <convert:DrawerSelectConverter x:Key="DrawerSelectConverter" />
<convert:StatusConverter x:Key="StatusConverter" /> <convert:StatusConverter x:Key="StatusConverter" />
<convert:InputQuantityConverter x:Key="InputQuantityConverter" /> <convert:InputQuantityConverter x:Key="InputQuantityConverter" />
<convert:OpenBoxConverter x:Key="OpenBoxConverter" />
<FrameworkElement x:Key="ProxyElement" DataContext="{Binding}"/>
</UserControl.Resources> </UserControl.Resources>
<Grid> <Grid>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
<ColumnDefinition /> <ColumnDefinition />
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<ContentControl Content="{StaticResource ProxyElement}" Visibility="Collapsed"/>
<Grid Margin="0" Grid.Column="0" Width="280" Height="570" Visibility="{Binding Is8Drawer, Converter={StaticResource BooleanToVisibilityConverter}}"> <Grid Margin="0" Grid.Column="0" Width="280" Height="570" Visibility="{Binding Is8Drawer, Converter={StaticResource BooleanToVisibilityConverter}}">
<Grid.Background> <Grid.Background>
<ImageBrush ImageSource="/Images/box.png" /> <ImageBrush ImageSource="/Images/box.png" />
@ -73,7 +77,7 @@
</Grid> </Grid>
</Grid> </Grid>
<Grid Margin="0" Grid.Column="0" Width="300" Height="570" Visibility="{Binding Is16Drawer, Converter={StaticResource BooleanToVisibilityConverter}}"> <Grid Margin="0" Grid.Column="1" Width="300" Height="570" Visibility="{Binding Is16Drawer, Converter={StaticResource BooleanToVisibilityConverter}}">
<Grid.Resources> <Grid.Resources>
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource MaterialDesignPaperLightButton}"> <Style TargetType="{x:Type Button}" BasedOn="{StaticResource MaterialDesignPaperLightButton}">
<Setter Property="Foreground" Value="#00a0ea" /> <Setter Property="Foreground" Value="#00a0ea" />
@ -143,7 +147,7 @@
</Grid> </Grid>
</Grid> </Grid>
<Grid Grid.Column="1" Margin="6"> <Grid Grid.Column="2" Margin="6">
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition /> <RowDefinition />
@ -164,6 +168,7 @@
Command="{Binding TakeFinish}" Command="{Binding TakeFinish}"
Visibility="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=CompleteBtn}" Visibility="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=CompleteBtn}"
Style="{StaticResource MaterialDesignOutlinedLightButton}" Style="{StaticResource MaterialDesignOutlinedLightButton}"
IsEnabled="{Binding CompleteIsEnable}"
Content="完成" /> Content="完成" />
<Button <Button
@ -172,6 +177,7 @@
Command="{Binding CancleTake}" Command="{Binding CancleTake}"
Visibility="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=CancelBtn}" Visibility="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=CancelBtn}"
Style="{StaticResource MaterialDesignOutlinedLightButton}" Style="{StaticResource MaterialDesignOutlinedLightButton}"
IsEnabled="{Binding CancleIsEnable}"
Content="取消" /> Content="取消" />
</StackPanel> </StackPanel>
<DataGrid <DataGrid
@ -208,7 +214,18 @@
Header="库位" Header="库位"
IsReadOnly="True" IsReadOnly="True"
ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/> ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/>
<DataGridTextColumn Width="181" <DataGridTemplateColumn Header="药品名称">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<TextBlock TextAlignment="Center" Text="{Binding DrugInfo.DrugName}"/>
<TextBlock TextAlignment="Center" Text="{Binding DrugInfo.DrugSpec}"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!--<DataGridTextColumn
Binding="{Binding DrugInfo.DrugName}" Binding="{Binding DrugInfo.DrugName}"
Header="药品名称" Header="药品名称"
IsReadOnly="True" IsReadOnly="True"
@ -227,8 +244,19 @@
Binding="{Binding EffDate}" Binding="{Binding EffDate}"
Header="效期" Header="效期"
IsReadOnly="True" IsReadOnly="True"
ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/> ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/>-->
<DataGridTextColumn Width="80" <DataGridTemplateColumn Header="批次">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<TextBlock TextAlignment="Center" Text="{Binding ManuNo}"/>
<TextBlock TextAlignment="Center" Text="{Binding EffDate}"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Width="60"
Binding="{Binding Quantity}" Binding="{Binding Quantity}"
Header="库存" Header="库存"
IsReadOnly="True" IsReadOnly="True"
@ -244,7 +272,7 @@
</Binding> </Binding>
</DataGridTextColumn.Binding> </DataGridTextColumn.Binding>
</DataGridTextColumn>--> </DataGridTextColumn>-->
<DataGridTemplateColumn Width="100" <DataGridTemplateColumn Width="90"
Header="取出数量"> Header="取出数量">
<DataGridTemplateColumn.CellTemplate> <DataGridTemplateColumn.CellTemplate>
<DataTemplate> <DataTemplate>
@ -261,7 +289,14 @@
</DataTemplate> </DataTemplate>
</DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn> </DataGridTemplateColumn>
<DataGridTemplateColumn Width="100"
Header="操作" Visibility="{Binding DataContext.OpenBoxVisibility,Source={StaticResource ProxyElement},Converter={StaticResource OpenBoxConverter}}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="开药盒" Command="{Binding DataContext.OpenBoxCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}" CommandParameter="{Binding}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns> </DataGrid.Columns>
</DataGrid> </DataGrid>
</Grid> </Grid>

View File

@ -15,20 +15,21 @@
</i:Interaction.Behaviors> </i:Interaction.Behaviors>
<Grid Width="400"> <Grid Width="400">
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/> <ColumnDefinition Width="2*"/>
<ColumnDefinition Width="2*"/> <ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="*"/> <RowDefinition Height="*"/>
<RowDefinition Height="1.2*"/> <RowDefinition Height="*"/>
<RowDefinition Height="2*"/> <RowDefinition Height="*"/>
<RowDefinition Height="2*"/> <RowDefinition Height="*"/>
<RowDefinition Height="2*"/> <RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/> <RowDefinition Height="*"/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<TextBlock Margin="6 0 0 0" Text="冰箱温度区间:" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" /> <TextBlock Margin="6 0 0 0" Text="冰箱温度区间:" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" />
<TextBox Grid.Row="1" <TextBox Grid.Row="1" Height="50"
Grid.Column="1" Grid.Column="1"
materialDesign:HintAssist.Hint="温度区间2-8度以-分隔" materialDesign:HintAssist.Hint="温度区间2-8度以-分隔"
Margin="6 0 0 10" Margin="6 0 0 10"
@ -41,20 +42,6 @@
</Binding> </Binding>
</TextBox.Text> </TextBox.Text>
</TextBox> </TextBox>
<!--<TextBlock Text="冰箱温度:" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" />
<TextBox Grid.Row="1"
Grid.Column="1"
materialDesign:HintAssist.Hint="保留小数点后一位"
Margin="6 10 0 10"
Style="{StaticResource MaterialDesignOutlinedTextBox}">
<TextBox.Text>
<Binding Path="TemperatureValue" Delay="1000" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
<Binding.ValidationRules>
<rules:TemperatureRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>-->
<TextBlock Text="冰箱状态:" Margin="0 18 0 0" Grid.Row="2" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" /> <TextBlock Text="冰箱状态:" Margin="0 18 0 0" Grid.Row="2" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" />
<ToggleButton Grid.Row="2" Grid.Column="1" Width="38" Height="38" Margin="6 18 0 0" <ToggleButton Grid.Row="2" Grid.Column="1" Width="38" Height="38" Margin="6 18 0 0"
HorizontalAlignment="Left" HorizontalAlignment="Left"
@ -72,6 +59,13 @@
ToolTip="报警状态" ToolTip="报警状态"
Content="打开" Content="打开"
materialDesign:ToggleButtonAssist.OnContent="关闭" /> materialDesign:ToggleButtonAssist.OnContent="关闭" />
<Button Grid.Row="4" Grid.ColumnSpan="2" Content="保存" Command="{Binding SaveCommand}" IsEnabled="{Binding BtnIsEnable}" /> <TextBlock Grid.Column="0" Grid.Row="4" Text="冰箱不在区间超时时间:" Margin="0 18 0 0" HorizontalAlignment="Right" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" />
<TextBox Grid.Row="4" Height="50"
Grid.Column="1"
materialDesign:HintAssist.Hint="超时时间以分钟为单位"
Margin="6 0 0 10" Text="{Binding OutRangeTime, UpdateSourceTrigger=PropertyChanged}"
Style="{StaticResource MaterialDesignOutlinedTextBox}">
</TextBox>
<Button Grid.Row="5" Grid.ColumnSpan="2" Content="保存" Command="{Binding SaveCommand}" IsEnabled="{Binding BtnIsEnable}" />
</Grid> </Grid>
</UserControl> </UserControl>

View File

@ -118,7 +118,7 @@
<Grid Grid.Column="2"> <Grid Grid.Column="2">
<StackPanel Margin="6" Orientation="Horizontal" HorizontalAlignment="Right"> <StackPanel Margin="6" Orientation="Horizontal" HorizontalAlignment="Right">
<Button Content="储物箱" Command="{Binding OpenRecoverCommand}" Visibility="{Binding Is16Drawer, Converter={StaticResource BooleanToVisibilityConverter}}" Style="{StaticResource MaterialDesignFlatSecondaryLightButton}" /> <Button Content="储物箱" Command="{Binding OpenRecoverCommand}" Visibility="{Binding Is16Drawer, Converter={StaticResource BooleanToVisibilityConverter}}" Style="{StaticResource MaterialDesignFlatSecondaryLightButton}" />
<TextBlock Margin="0,10,10,0" Text="{Binding WD}" Foreground="White" FontWeight="Bold" FontSize="14"/> <TextBlock Margin="0,10,10,0" Text="{Binding WD}" Foreground="{Binding AlertColor}" FontWeight="Bold" FontSize="14"/>
</StackPanel> </StackPanel>
</Grid> </Grid>

View File

@ -18,10 +18,10 @@
WindowStartupLocation="CenterScreen" WindowStartupLocation="CenterScreen"
Topmost="False" Topmost="False"
prism:ViewModelLocator.AutoWireViewModel="True" prism:ViewModelLocator.AutoWireViewModel="True"
Title="主窗口" Height="768" Width="1024" WindowStyle="None" WindowState="Maximized"> Title="主窗口" WindowStyle="None" WindowState="Maximized">
<WindowChrome.WindowChrome> <!--<WindowChrome.WindowChrome>
<WindowChrome CornerRadius="4" GlassFrameThickness="1" /> <WindowChrome CornerRadius="4" GlassFrameThickness="0" />
</WindowChrome.WindowChrome> </WindowChrome.WindowChrome>-->
<materialDesign:DialogHost <materialDesign:DialogHost
DialogMargin="0" DialogMargin="0"

View File

@ -0,0 +1,316 @@
<UserControl x:Class="DM_Weight.Views.ReturnWithOrderWindow"
xmlns:pagination="clr-namespace:DM_Weight.Components.pagination"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:DM_Weight.Views"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
xmlns:convert="clr-namespace:DM_Weight.Converter"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
MinWidth="880"
Width="Auto"
Height="Auto"
mc:Ignorable="d">
<UserControl.Resources>
<convert:StatusConverter x:Key="StatusConverter" />
<Style x:Key="st" TargetType="GridViewColumnHeader">
<Style.Setters>
<Setter Property="Height">
<Setter.Value>55</Setter.Value>
</Setter>
<Setter Property="Background">
<Setter.Value>#31ccec</Setter.Value>
</Setter>
<Setter Property="Foreground">
<Setter.Value>white</Setter.Value>
</Setter>
</Style.Setters>
</Style>
</UserControl.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="4*" />
<ColumnDefinition Width="5*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="8*"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid Margin="0 6 0 6" Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1.5*" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="4.5*"/>
</Grid.ColumnDefinitions>
<ComboBox
Grid.Column="0"
Margin="6 0 0 0"
Style="{StaticResource MaterialDesignOutlinedComboBox}"
SelectedItem="{Binding SelectedItem}"
DisplayMemberPath="Name"
ItemsSource="{Binding OrderTakeSelects}"
/>
<TextBox
Grid.Column="1"
Text="{Binding SearchValue, UpdateSourceTrigger=PropertyChanged}"
materialDesign:HintAssist.Hint="{Binding SelectedItem.Name}"
materialDesign:HintAssist.IsFloating="True"
Margin="6 0 0 0"
Style="{StaticResource MaterialDesignOutlinedTextBox}"/>
<DatePicker
Grid.Column="2"
SelectedDate="{Binding OrderDate, StringFormat=yyyy-MM-dd, TargetNullValue='',UpdateSourceTrigger=PropertyChanged}"
SelectedDateFormat="Short"
Margin="6 0 0 0"
materialDesign:HintAssist.Hint="开方日期"
Style="{StaticResource MaterialDesignOutlinedDatePicker}" />
</Grid>
<ListView Grid.Row="1"
ItemsSource="{Binding OrderInfos}"
SelectedItem="{Binding SelectedOrder}"
materialDesign:ListViewAssist.HeaderRowBackground="#31ccec"
materialDesign:DataGridAssist.ColumnHeaderPadding="10"
materialDesign:ListViewAssist.ListViewItemPadding="13">
<ListView.Resources>
<Style TargetType="{x:Type GridViewColumnHeader}" BasedOn="{StaticResource {x:Type GridViewColumnHeader}}">
<Setter Property="Foreground" Value="White" />
</Style>
</ListView.Resources>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding RowSelected}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<ListView.View>
<GridView ColumnHeaderContainerStyle="{StaticResource st}">
<GridViewColumn Width="100"
Header="处方号"
DisplayMemberBinding="{Binding OrderNo}"/>
<GridViewColumn Width="70"
Header="时间"
DisplayMemberBinding="{Binding ChargeDate, StringFormat=yyyy-MM-dd}" />
<GridViewColumn Width="60" DisplayMemberBinding="{Binding PName}" Header="姓名">
<!--<GridViewColumn.Header>
<TextBlock Text= "" TextWrapping="Wrap"/>
</GridViewColumn.Header>-->
</GridViewColumn>
<GridViewColumn Width="60"
DisplayMemberBinding="{Binding Sex}" Header="性别">
<!--<GridViewColumn.Header>
<TextBlock Text="" TextWrapping="Wrap"/>
</GridViewColumn.Header>-->
</GridViewColumn>
<GridViewColumn Width="200"
DisplayMemberBinding="{Binding IdNumber}"
Header="身份证号"/>
<GridViewColumn Width="130"
DisplayMemberBinding="{Binding DeptName}"
Header="科室"/>
<GridViewColumn Width="80"
DisplayMemberBinding="{Binding orderDetail.Quantity}"
Header="数量"/>
</GridView>
</ListView.View>
</ListView>
<pagination:Pagination Grid.Row="2"
CurrentPage="{Binding PageNum}"
PageSize="{Binding PageSize}"
TotalPages="{Binding TotalCount}"
InfoTextIsEnabel="True"
/>
</Grid>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<Grid Margin="0 6 0 6" Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<ComboBox materialDesign:HintAssist.Hint="取药人"
Grid.Column="0"
Margin="6 0 0 0"
Style="{StaticResource MaterialDesignOutlinedComboBox}"
SelectedItem="{Binding UserSelects}"
DisplayMemberPath="UserName"
ItemsSource="{Binding UserLists}"
/>
<DatePicker
Grid.Column="1"
SelectedDate="{Binding OptDate, StringFormat=yyyy-MM-dd, TargetNullValue='',UpdateSourceTrigger=PropertyChanged}"
SelectedDateFormat="Short"
Margin="6 0 0 0"
materialDesign:HintAssist.Hint="取药日期"
Style="{StaticResource MaterialDesignOutlinedDatePicker}" />
<StackPanel Margin="6" Grid.Column="3" Orientation="Horizontal" HorizontalAlignment="Right">
<Button
Margin="16 0 6 0"
VerticalAlignment="Center"
Command="{Binding OpenDrawer}"
Visibility="{Binding Status,Converter={StaticResource StatusConverter}, ConverterParameter=opearBtnVisible}"
materialDesign:ButtonProgressAssist.IsIndicatorVisible="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=opearBtnLoading}"
materialDesign:ButtonProgressAssist.IsIndeterminate="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=opearBtnLoading}"
Style="{StaticResource MaterialDesignOutlinedLightButton}"
Content="还空瓶" />
<Button
Margin="0 0 3 0"
VerticalAlignment="Center"
Command="{Binding SaveCommand}"
materialDesign:ButtonProgressAssist.IsIndicatorVisible="{Binding Status,Converter={StaticResource StatusConverter},ConverterParameter=TakeFinishLoading}"
materialDesign:ButtonProgressAssist.IsIndeterminate="{Binding Status,Converter={StaticResource StatusConverter},ConverterParameter=TakeFinishLoading}"
Visibility="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=CompleteBtn}"
Style="{StaticResource MaterialDesignOutlinedLightButton}"
Content="完成" />
<Button
Margin="0 0 6 0"
VerticalAlignment="Center"
Command="{Binding CancleTake}"
Visibility="{Binding Status, Converter={StaticResource StatusConverter}, ConverterParameter=CancelBtn}"
Style="{StaticResource MaterialDesignOutlinedLightButton}"
Content="取消" />
</StackPanel>
</Grid>
<ScrollViewer Grid.Row="1">
<ItemsControl
ItemsSource="{Binding OrderDetails}"
Grid.IsSharedSizeScope="True" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border BorderBrush="White" BorderThickness="1">
<StackPanel Orientation="Horizontal" Background="#31ccec" Grid.Column="0">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<!--<RowDefinition/>-->
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
</Grid.ColumnDefinitions>
<TextBlock TextWrapping="Wrap" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="0 10 0 0 " Text="{Binding DrugInfo.DrugName}"/>
<TextBlock TextWrapping="Wrap" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="0 0 0 1 " Text="{Binding DrugInfo.DrugSpec}"/>
<!--<Button Grid.Row="2" Padding="0 0 0 1 " Style="{x:Null}" BorderBrush="{x:Null}" Background="{x:Null}" Click="Button_Click" CommandParameter="{Binding}">
<Button.Content>
<Border Width="32" Height="32" CornerRadius="16" Background="CornflowerBlue" VerticalAlignment="Center" HorizontalAlignment="Center">
<Path Data="M0 11L22 11M11 0L11 22" Stroke="WhiteSmoke" StrokeThickness="4" VerticalAlignment="Center" HorizontalAlignment="Center"></Path>
</Border>
</Button.Content>
</Button>-->
</Grid>
</StackPanel>
</Border>
<DataGrid
Margin="0"
Grid.Column="1"
materialDesign:DataGridAssist.ColumnHeaderPadding="15"
ItemsSource="{Binding MachineRecords}"
materialDesign:DataGridAssist.EnableEditBoxAssist="False"
materialDesign:DataGridAssist.CellPadding="13"
SelectionUnit="Cell"
CanUserAddRows="False"
AutoGenerateColumns="False">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridColumnHeader}" BasedOn="{StaticResource MaterialDesignDataGridColumnHeader}">
<Setter Property="Background" Value="#31ccec" />
<Setter Property="Foreground" Value="white" />
<Setter Property="Height" Value="56" />
<Setter Property="BorderBrush" Value="white"/>
<Setter Property="BorderThickness" Value="0.6"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
<Style TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource MaterialDesignDataGridCell}">
<Style.Triggers>
<Trigger Property="IsReadOnly" Value="True">
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="HorizontalAlignment" Value="Center"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<!--<DataGridTemplateColumn Width="200" IsReadOnly="True"
Header="批次">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
Style="{StaticResource MaterialDesignDataGridComboBox}"
ItemsSource="{Binding DrugInfo.DrugManuNos}"
SelectedItem="{Binding drugManuNo,UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="ManuNo" >
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>-->
<DataGridTextColumn Width="100"
Binding="{Binding drugManuNo.ManuNo}"
Header="批次"
IsReadOnly="True"
ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/>
<DataGridTextColumn Width="100"
Binding="{Binding drugManuNo.EffDate}"
Header="效期"
IsReadOnly="True"
ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/>
<DataGridTextColumn Width="100"
Binding="{Binding Quantity}"
Header="取药数量"
IsReadOnly="True"
ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/>
<DataGridTextColumn Width="100"
Binding="{Binding CanReturnQuantity}"
Header="可还空瓶数"
IsReadOnly="True"
ElementStyle="{StaticResource MaterialDesignDataGridTextColumnStyle}"/>
<DataGridTemplateColumn Width="100"
Header="还空瓶数量">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Style="{StaticResource MaterialDesignDataGridTextColumnEditingStyle}">
<TextBox.Text>
<Binding Path="CurrentReturn" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</Grid>
</UserControl>

View File

@ -0,0 +1,40 @@
using DM_Weight.Models;
using DM_Weight.msg;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace DM_Weight.Views
{
/// <summary>
/// ReturnWithOrderWindow.xaml 的交互逻辑
/// </summary>
public partial class ReturnWithOrderWindow : UserControl
{
//IEventAggregator _eventAggregator;
public ReturnWithOrderWindow()
{
InitializeComponent();
//_eventAggregator = eventAggregator;
}
//private void Button_Click(object sender, RoutedEventArgs e)
//{
// Button btn = (Button)sender;
// OrderDetail od = (OrderDetail)btn.CommandParameter;
// //vms.AddAction(cls);
// _eventAggregator.GetEvent<ReturnEmptyEvent>().Publish(od);
//}
}
}

View File

@ -0,0 +1,13 @@
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DM_Weight.msg
{
public class FridgeEvent:PubSubEvent
{
}
}

View File

@ -0,0 +1,14 @@
using DM_Weight.Models;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DM_Weight.msg
{
public class ReturnEmptyEvent:PubSubEvent<OrderDetail>
{
}
}

View File

@ -0,0 +1,41 @@
using SharpPromise;
using System;
using System.Threading.Tasks;
namespace DM_Weight.util
{
public class PromiseUtil<T>
{
public int _delay { get; set; }
public T? _data { get; set; }
public async Task taskAsyncLoop(int delay, T data, Action<PromiseUtil<T>, Action, Action> action)
{
_data = data;
_delay = 0;
while (_delay >= 0)
{
await new Promise(async (Action onResolve, Action onReject) =>
{
await Task.Delay(_delay);
try
{
await Task.Run(() => action(this, onResolve, onReject));
}
catch (Exception ex)
{
onReject();
}
}).Then(() =>
{
_delay = delay;
}).Catch((Exception e) =>
{
_delay = -1;
});
}
}
}
}