!提交代码

This commit is contained in:
hehaibing-1996
2024-04-15 18:43:28 +08:00
commit e89b64ea3a
232 changed files with 22292 additions and 0 deletions

View File

@ -0,0 +1,34 @@
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace .ViewModel
{
public class AboutViewModel : BindableBase
{
public AboutViewModel()
{
var versionInfo = FileVersionInfo.GetVersionInfo(LocalFile.AppPath);
Name = versionInfo.ProductName;
Company = $"{versionInfo.CompanyName} {versionInfo.LegalCopyright}";
Ver = $"v {new string(versionInfo.FileVersion.Take(5).ToArray())}";
}
/// <summary>
/// 程序名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 公司名
/// </summary>
public string Company { get; set; }
/// <summary>
/// 版本
/// </summary>
public string Ver { get; set; }
}
}

View File

@ -0,0 +1,199 @@
using HandyControl.Controls;
using LiveCharts;
using Ping9719.WpfEx.Mvvm;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace .ViewModel
{
public class DataChartViewModel : BindableBase
{
#region
private bool isLoad;
public bool IsLoad { get => isLoad; set { SetProperty(ref isLoad, value); } }
#endregion
#region
private List<int> year = new List<int>();
/// <summary>
/// 年
/// </summary>
public List<int> Year { get => year; set { SetProperty(ref year, value); } }
private List<int> month = new List<int>();
/// <summary>
/// 月
/// </summary>
public List<int> Month { get => month; set { SetProperty(ref month, value); } }
private int yearIndex;
/// <summary>
/// 年索引
/// </summary>
public int YearIndex { get => yearIndex; set { SetProperty(ref yearIndex, value); UpdataMonth(); } }
private int monthIndex;
/// <summary>
/// 月索引
/// </summary>
public int MonthIndex { get => monthIndex; set { SetProperty(ref monthIndex, value); StatChart(); } }
#endregion
#region
public ChartValues<int> ChartValues1 { get; set; } = new ChartValues<int>();
public ChartValues<int> ChartValues2 { get; set; } = new ChartValues<int>();
public ChartValues<int> ChartValues3 { get; set; } = new ChartValues<int>();
public Func<double, string> LabelFormatterX { get; set; } = value => $"{value}号";
public Func<double, string> LabelFormatterY { get; set; } = value => $"{value}个";
private IList<string> chartLabelsX;
/// <summary>
/// X轴轴信息
/// </summary>
public IList<string> ChartLabelsX { get => chartLabelsX; set { SetProperty(ref chartLabelsX, value); } }
#endregion
#region
/// <summary>
/// 更新年
/// </summary>
public async void UpdataYear()
{
try
{
IsLoad = true;
Year = await DataDb.db.Queryable<MyTestTable>()
.GroupBy(o => o.Time.Year)
.OrderByDescending(o => o.Time.Year)
.Select(o => o.Time.Year)
.ToListAsync();
}
catch (Exception ex)
{
Year = new List<int>();
Growl.Error("刷新数据失败:" + ex.Message);
}
finally
{
YearIndex = Year.Any() ? 0 : -1;
}
}
/// <summary>
/// 更新月
/// </summary>
public async void UpdataMonth()
{
try
{
IsLoad = true;
if (!Year.Any() || YearIndex < 0)
return;
var dt1 = new DateTime(Year[YearIndex], 1, 1);
var dt2 = dt1.AddYears(1);
Month = await DataDb.db.Queryable<MyTestTable>()
.Where(o => o.Time > dt1 && o.Time < dt2)
.GroupBy(o => o.Time.Month)
.OrderBy(o => o.Time.Month)
.Select(o => o.Time.Month)
.ToListAsync();
}
catch (Exception ex)
{
Month = new List<int>();
Growl.Error("刷新数据失败:" + ex.Message);
}
finally
{
MonthIndex = Month.Any() ? Month.Count - 1 : -1;
}
}
public ICommand ButStatChartCommand { get => new DelegateCommand(ButStatChart); }
/// <summary>
/// 点击刷新
/// </summary>
public void ButStatChart()
{
if (IsLoad)
{
Growl.Info("有任务正在进行");
return;
}
if (!Year.Any() || !Month.Any() || YearIndex < 0 || MonthIndex < 0)
{
Growl.Info("没有选择年份或月份");
return;
}
StatChart();
}
/// <summary>
/// 刷新统计信息
/// </summary>
public async void StatChart()
{
try
{
if (!Year.Any() || !Month.Any() || YearIndex < 0 || MonthIndex < 0)
{
ChartValues1.Clear();
ChartValues2.Clear();
ChartValues3.Clear();
return;
}
IsLoad = true;
await Task.Delay(200);
var year = Year[YearIndex];
var month = Month[MonthIndex];
var dt1 = new DateTime(year, month, 1);
var dt2 = dt1.AddMonths(1);
//从数据库中查询、统计数量
var dbdata = await DataDb.db.Queryable<MyTestTable>()
.Where(o => o.Time > dt1 && o.Time < dt2)
.GroupBy(o => o.Time.Day)
.Select(o => new
{
day = o.Time.Day,
count = SqlFunc.AggregateCount(o.Id),
okCount = SqlFunc.AggregateCount(o.Status == "合格" ? "" : null),
notCount = SqlFunc.AggregateCount(o.Status != "合格" ? "" : null),
})
.OrderBy(o => o.day)
.ToListAsync();
ChartLabelsX = dbdata.Select(o => o.day.ToString()).ToList();
ChartValues1.Clear();
ChartValues2.Clear();
ChartValues3.Clear();
ChartValues1.AddRange(dbdata.Select(o => o.count));
ChartValues2.AddRange(dbdata.Select(o => o.okCount));
ChartValues3.AddRange(dbdata.Select(o => o.notCount));
}
catch (Exception ex)
{
Growl.Error("刷新数据失败:" + ex.Message);
}
finally
{
IsLoad = false;
}
}
#endregion
}
}

View File

@ -0,0 +1,201 @@
using HandyControl.Controls;
using MiniExcelLibs;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using SqlSugar;
using HandyControl.Data;
using System.Windows;
namespace .ViewModel
{
public class DataListViewModel : BindableBase
{
private List<MyTestTable> dataList = new List<MyTestTable>();
/// <summary>
/// 列表数据
/// </summary>
public List<MyTestTable> DataList { get => dataList; set { SetProperty(ref dataList, value); } }
#region
private bool IsLoad_;
public bool IsLoad { get => IsLoad_; set { SetProperty(ref IsLoad_, value); } }
#endregion
#region
private DateTime? timeGo = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
/// <summary>
/// 开始时间(默认只显示今天开始的数据)
/// </summary>
public DateTime? TimeGo { get => timeGo; set { SetProperty(ref timeGo, value); } }
private DateTime? timeTo;
/// <summary>
/// 结束时间
/// </summary>
public DateTime? TimeTo { get => timeTo; set { SetProperty(ref timeTo, value); } }
private string info1;
public string Info1 { get => info1; set { SetProperty(ref info1, value); } }
private string info2;
public string Info2 { get => info2; set { SetProperty(ref info2, value); } }
#endregion
#region
private int maxPageCount;
/// <summary>
/// 最大页数
/// </summary>
public int MaxPageCount { get => maxPageCount; set { SetProperty(ref maxPageCount, value); } }
private int pageIndex = 1;
/// <summary>
/// 当前页
/// </summary>
public int PageIndex { get => pageIndex; set { SetProperty(ref pageIndex, value); } }
private int dataCountPerPage = 20;
/// <summary>
/// 每页的数据量
/// </summary>
public int DataCountPerPage { get => dataCountPerPage; set { SetProperty(ref dataCountPerPage, value); } }
public ICommand PageUpdateCommand { get => new DelegateCommand<FunctionEventArgs<int>>(PageUpdate); }
/// <summary>
/// 页码更新
/// </summary>
public void PageUpdate(FunctionEventArgs<int> page)
{
PageIndex = page.Info;
UpdateList();
}
#endregion
public ICommand ExportExcelCommand { get => new DelegateCommand(ExportExcel); }
/// <summary>
/// 导出为excel
/// </summary>
public async void ExportExcel()
{
if (IsLoad)
{
Growl.Info("有任务正在进行,请稍等片刻。");
return;
}
IsLoad = true;
Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
sfd.Filter = ".xlsx文件(*.xlsx)|*.xlsx";
sfd.FileName = "XXXX记录信息";
sfd.OverwritePrompt = true;
if (sfd.ShowDialog() != true)
{
IsLoad = false;
return;
}
string path = sfd.FileName;
try
{
//1.查询数据库,加入筛选条件,并按照时间倒序排序,并导出指定列
var dbData = DataDb.db.Queryable<MyTestTable>()
.WhereIF(TimeGo != null, o => o.Time > TimeGo)
.WhereIF(TimeTo != null, o => o.Time < TimeTo)
.WhereIF(!string.IsNullOrWhiteSpace(Info1), o => o.Info1.StartsWith(Info1.Trim()))
.WhereIF(!string.IsNullOrWhiteSpace(Info2), o => o.Info2.StartsWith(Info2.Trim()))
.OrderByDescending(o => o.Id)
.Select(o => new
{
1 = o.Info1,
2 = o.Info2,
= o.Status,
= o.Time.ToString("yyyy-MM-dd HH:mm:ss"),
});
//2.导出为Excel使用内存缓存的方式防止数据量过大导致内存泄露
var sqlkv = dbData.ToSql();
var dataReader = await DataDb.db.Ado.GetDataReaderAsync(sqlkv.Key, sqlkv.Value);
await MiniExcel.SaveAsAsync(path, dataReader, overwriteFile: true);
dataReader.Close();
Growl.Success("导出成功。");
}
catch (Exception ex)
{
Growl.Error("导出失败:" + ex.Message);
}
finally
{
IsLoad = false;
}
}
public ICommand UpdateListCommand { get => new DelegateCommand(UpdateList); }
/// <summary>
/// 更新信息
/// </summary>
public async void UpdateList()
{
if (IsLoad)
{
Growl.Info("有任务正在进行,请稍等片刻。");
return;
}
IsLoad = true;
try
{
await Task.Delay(200);
//1.查询数据库,加入筛选条件,并按照时间倒序排序
var dbData = DataDb.db.Queryable<MyTestTable>()
.WhereIF(TimeGo != null, o => o.Time > TimeGo)
.WhereIF(TimeTo != null, o => o.Time < TimeTo)
.WhereIF(!string.IsNullOrWhiteSpace(Info1), o => o.Info1.StartsWith(Info1.Trim()))
.WhereIF(!string.IsNullOrWhiteSpace(Info2), o => o.Info2.StartsWith(Info2.Trim()))
.OrderByDescending(o => o.Id);
//2.开始分页(如模型不一样使用‘.Select<Model>()’来转换)
RefAsync<int> totalNumber = 0;
RefAsync<int> totalPage = 0;
DataList = await dbData.ToPageListAsync(PageIndex, DataCountPerPage, totalNumber, totalPage);
MaxPageCount = totalPage.Value;
}
catch (Exception ex)
{
Growl.Error("加载数据失败:" + ex.Message);
}
finally
{
IsLoad = false;
}
}
public ICommand SeeCommand { get => new DelegateCommand<MyTestTable>(See); }
/// <summary>
/// 查看详情
/// </summary>
public void See(MyTestTable obj)
{
if (IsLoad)
{
Growl.Info("有任务正在进行,请稍等片刻。");
return;
}
Growl.Info("信息:" + Newtonsoft.Json.JsonConvert.SerializeObject(obj));
}
}
}

View File

@ -0,0 +1,206 @@
using HandyControl.Controls;
using MiniExcelLibs;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using SqlSugar;
using HandyControl.Data;
using System.Windows;
namespace .ViewModel
{
public class DataListWarnInfoViewModel : BindableBase
{
private List<WarnInfoItemDb> dataList = new List<WarnInfoItemDb>();
/// <summary>
/// 列表数据
/// </summary>
public List<WarnInfoItemDb> DataList { get => dataList; set { SetProperty(ref dataList, value); } }
#region
private bool isLoad1 = false;
public bool IsLoad1 { get => isLoad1; set { SetProperty(ref isLoad1, value); } }
private bool isLoad2 = false;
public bool IsLoad2 { get => isLoad2; set { SetProperty(ref isLoad2, value); } }
#endregion
#region
private DateTime? timeGo = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
/// <summary>
/// 开始时间(默认只显示今天开始的数据)
/// </summary>
public DateTime? TimeGo { get => timeGo; set { SetProperty(ref timeGo, value); } }
private DateTime? timeTo;
/// <summary>
/// 结束时间
/// </summary>
public DateTime? TimeTo { get => timeTo; set { SetProperty(ref timeTo, value); } }
private string info1;
public string Info1 { get => info1; set { SetProperty(ref info1, value); } }
private string info2;
public string Info2 { get => info2; set { SetProperty(ref info2, value); } }
#endregion
#region
private int maxPageCount;
/// <summary>
/// 最大页数
/// </summary>
public int MaxPageCount { get => maxPageCount; set { SetProperty(ref maxPageCount, value); } }
private int pageIndex = 1;
/// <summary>
/// 当前页
/// </summary>
public int PageIndex { get => pageIndex; set { SetProperty(ref pageIndex, value); } }
private int dataCountPerPage = 20;
/// <summary>
/// 每页的数据量
/// </summary>
public int DataCountPerPage { get => dataCountPerPage; set { SetProperty(ref dataCountPerPage, value); } }
public ICommand PageUpdateCommand { get => new DelegateCommand<FunctionEventArgs<int>>(PageUpdate); }
/// <summary>
/// 页码更新
/// </summary>
public void PageUpdate(FunctionEventArgs<int> page)
{
PageIndex = page.Info;
UpdateList();
}
#endregion
public ICommand ExportExcelCommand { get => new DelegateCommand(ExportExcel); }
/// <summary>
/// 导出为excel
/// </summary>
public async void ExportExcel()
{
if (IsLoad2)
{
Growl.Info("有任务正在进行,请稍等片刻。");
return;
}
Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
sfd.Filter = ".xlsx文件(*.xlsx)|*.xlsx";
sfd.FileName = "警告信息记录信息";
sfd.OverwritePrompt = true;
if (sfd.ShowDialog() != true)
{
IsLoad1 = false;
return;
}
string path = sfd.FileName;
try
{
//1.查询数据库,加入筛选条件,并按照时间倒序排序,并导出指定列
var dbData = WarnInfoDb.db.Queryable<WarnInfoItemDb>()
.WhereIF(TimeGo != null, o => o.TimeGo > TimeGo)
.WhereIF(TimeTo != null, o => o.TimeGo < TimeTo)
.WhereIF(!string.IsNullOrWhiteSpace(Info1), o => o.Source.StartsWith(Info1.Trim()))
.WhereIF(!string.IsNullOrWhiteSpace(Info2), o => o.Level.StartsWith(Info2.Trim()))
.OrderByDescending(o => o.TimeGo)
.Select(o => new
{
= o.Source,
= o.Text,
= o.Level,
= o.Solution,
= o.WarnType,
= o.TimeGo.ToString("yyyy-MM-dd HH:mm:ss"),
= o.TimeTo.HasValue ? o.TimeTo.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
= o.DuraTime,
});
//2.导出为Excel使用内存缓存的方式防止数据量过大导致内存泄露
var sqlkv = dbData.ToSql();
var dataReader = await DataDb.db.Ado.GetDataReaderAsync(sqlkv.Key, sqlkv.Value);
await MiniExcel.SaveAsAsync(path, dataReader, overwriteFile: true);
dataReader.Close();
Growl.Success("导出成功。");
}
catch (Exception ex)
{
Growl.Error("导出失败:" + ex.Message);
}
finally
{
IsLoad1 = false;
}
}
public ICommand UpdateListCommand { get => new DelegateCommand(UpdateList); }
/// <summary>
/// 更新信息
/// </summary>
public async void UpdateList()
{
if (IsLoad1)
{
Growl.Info("有任务正在进行,请稍等片刻。");
return;
}
try
{
await Task.Delay(200);
//1.查询数据库,加入筛选条件,并按照时间倒序排序
var dbData = WarnInfoDb.db.Queryable<WarnInfoItemDb>()
.WhereIF(TimeGo != null, o => o.TimeGo > TimeGo)
.WhereIF(TimeTo != null, o => o.TimeGo < TimeTo)
.WhereIF(!string.IsNullOrWhiteSpace(Info1), o => o.Source.StartsWith(Info1.Trim()))
.WhereIF(!string.IsNullOrWhiteSpace(Info2), o => o.Level.StartsWith(Info2.Trim()))
.OrderByDescending(o => o.TimeGo);
//2.开始分页(如模型不一样使用‘.Select<Model>()’来转换)
RefAsync<int> totalNumber = 0;
RefAsync<int> totalPage = 0;
DataList = await dbData.ToPageListAsync(PageIndex, DataCountPerPage, totalNumber, totalPage);
MaxPageCount = totalPage.Value;
}
catch (Exception ex)
{
Growl.Error("加载数据失败:" + ex.Message);
}
finally
{
IsLoad2 = false;
}
}
public ICommand SeeCommand { get => new DelegateCommand<MyTestTable>(See); }
/// <summary>
/// 查看详情
/// </summary>
public void See(MyTestTable obj)
{
if (IsLoad1 || IsLoad2)
{
Growl.Info("有任务正在进行,请稍等片刻。");
return;
}
Growl.Info("信息:" + Newtonsoft.Json.JsonConvert.SerializeObject(obj));
}
}
}

View File

@ -0,0 +1,677 @@
using HandyControl.Controls;
using Ping9719.WpfEx;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace .ViewModel
{
public class DeviceViewModel : BindableBase
{
//循环间隙时间
int whileSleep = 1500;
/// <summary>
/// 是否繁忙。繁忙状态下不在进行定时刷新操作。
/// </summary>
public bool IsBusy { get; set; } = false;
//public IIoTBase plc;
#region
/// <summary>
/// 监听
/// </summary>
public IEnumerable<DeviceReadModel> DataReads { get; set; }
/// <summary>
/// 控制
/// </summary>
public IEnumerable<DeviceWriteModel> DataWrites { get; set; }
/// <summary>
/// 气缸
/// </summary>
public IEnumerable<DeviceUrnModel> DataUrns { get; set; }
/// <summary>
/// 伺服
/// </summary>
public IEnumerable<DeviceServoModel> DataServos { get; set; }
private bool IsVis_ = false;
/// <summary>
/// 当前页面是否显示
/// </summary>
public bool IsVis { get => IsVis_; set { SetProperty(ref IsVis_, value); } }
#region
private bool IsVisRead_ = true;
public bool IsVisRead { get => IsVisRead_; set { SetProperty(ref IsVisRead_, value); } }
private bool IsVisWrite_ = true;
public bool IsVisWrite { get => IsVisWrite_; set { SetProperty(ref IsVisWrite_, value); } }
private bool IsVisUrn_ = true;
public bool IsVisUrn { get => IsVisUrn_; set { SetProperty(ref IsVisUrn_, value); } }
private bool IsVisServo_ = true;
public bool IsVisServo { get => IsVisServo_; set { SetProperty(ref IsVisServo_, value); } }
#endregion
#region
private bool IsVisExpRead_ = true;
public bool IsVisExpRead { get => IsVisExpRead_; set { SetProperty(ref IsVisExpRead_, value); } }
private bool IsVisExpWrite_ = true;
public bool IsVisExpWrite { get => IsVisExpWrite_; set { SetProperty(ref IsVisExpWrite_, value); } }
private bool IsVisExpUrn_ = false;
public bool IsVisExpUrn { get => IsVisExpUrn_; set { SetProperty(ref IsVisExpUrn_, value); } }
private bool IsVisExpServo_ = false;
public bool IsVisExpServo { get => IsVisExpServo_; set { SetProperty(ref IsVisExpServo_, value); } }
#endregion
#endregion
/// <summary>
/// 循环读取数据
/// </summary>
public async void WhileRead()
{
while (true)
{
try
{
if (!IsVis || IsBusy)
{
await Task.Delay(whileSleep);
continue;
}
////监控
if (DataReads != null && IsVisExpRead)
{
foreach (var item in DataReads)
{
if (!item.IsExpanded)
continue;
var plcAdd = item.ExcelTag;
if (string.IsNullOrWhiteSpace(plcAdd.))
continue;
var ts = plcAdd..Trim().ToLower();
switch (ts)
{
case "bool":
//var datab = plc?.Read<bool>(plcAdd.地址);
//item.Value = datab?.IsSucceed == true ? datab.Value : false;
break;
case "byte":
//var datay = plc?.Read<byte>(plcAdd.地址);
//item.Value = datay?.IsSucceed == true ? datay.Value : "-";
break;
case "int16":
//var datai16 = plc?.Read<Int16>(plcAdd.地址);
//item.Value = datai16?.IsSucceed == true ? datai16.Value : "-";
break;
case "int32":
//var datai32 = plc?.Read<int>(plcAdd.地址);
//item.Value = datai32?.IsSucceed == true ? datai32.Value : "-";
break;
case "uint16":
//var dataui16 = plc?.Read<UInt16>(plcAdd.地址);
//item.Value = dataui16?.IsSucceed == true ? dataui16.Value : "-";
break;
case "uint32":
//var dataui32 = plc?.Read<UInt32>(plcAdd.地址);
//item.Value = dataui32?.IsSucceed == true ? dataui32.Value : "-";
break;
case "float":
case "single":
//var datas = plc?.Read<float>(plcAdd.地址);
//item.Value = datas?.IsSucceed == true ? datas.Value : "-";
break;
case "double":
//var datad = plc?.Read<double>(plcAdd.地址);
//item.Value = datad?.IsSucceed == true ? datad.Value : "-";
break;
default:
break;
}
}
}
////控制
if (DataWrites != null && IsVisExpWrite)
{
foreach (var item in DataWrites)
{
if (!item.IsExpanded)
continue;
var plcAdd = item.ExcelTag;
if (string.IsNullOrWhiteSpace(plcAdd.))
continue;
var ts = plcAdd..Trim().ToLower();
switch (ts)
{
case "bool":
//var datab = plc?.Read<bool>(plcAdd.读地址);
//item.Value = datab?.IsSucceed == true ? datab.Value : false;
break;
case "byte":
//var datay = plc?.Read<byte>(plcAdd.读地址);
//item.Value = datay?.IsSucceed == true ? datay.Value : "-";
break;
case "int16":
//var datai16 = plc?.Read<Int16>(plcAdd.读地址);
//item.Value = datai16?.IsSucceed == true ? datai16.Value : "-";
break;
case "int32":
//var datai32 = plc?.Read<int>(plcAdd.读地址);
//item.Value = datai32?.IsSucceed == true ? datai32.Value : "-";
break;
case "uint16":
//var dataui16 = plc?.Read<UInt16>(plcAdd.读地址);
//item.Value = dataui16?.IsSucceed == true ? dataui16.Value : "-";
break;
case "uint32":
//var dataui32 = plc?.Read<UInt32>(plcAdd.读地址);
//item.Value = dataui32?.IsSucceed == true ? dataui32.Value : "-";
break;
case "float":
case "single":
//var datas = plc?.Read<float>(plcAdd.读地址);
//item.Value = datas?.IsSucceed == true ? datas.Value : "-";
break;
case "double":
//var datad = plc?.Read<double>(plcAdd.读地址);
//item.Value = datad?.IsSucceed == true ? datad.Value : "-";
break;
default:
break;
}
}
}
////气缸
if (DataUrns != null && IsVisExpUrn)
{
foreach (var item in DataUrns)
{
if (!item.IsExpanded)
continue;
var plcAdd = item.ExcelTag;
if (!string.IsNullOrWhiteSpace(plcAdd.))
{
//var data1 = plc?.Read<bool>(plcAdd.推到位地址);
//item.IsGoTo = data1?.IsSucceed == true ? data1.Value : false;
}
if (!string.IsNullOrWhiteSpace(plcAdd.))
{
//var data2 = plc?.Read<bool>(plcAdd.回到位地址);
//item.IsRetTo = data2?.IsSucceed == true ? data2.Value : false;
}
}
}
////伺服
if (DataServos != null && IsVisExpServo)
{
foreach (var item in DataServos)
{
if (!item.IsExpanded)
continue;
////读取地址信息
var plcAdd = item.ExcelTag;
if (!string.IsNullOrWhiteSpace(plcAdd.))
{
//var data1 = plc?.Read<float>(plcAdd.当前位置获取);
//item.Location = data1?.IsSucceed == true ? data1.Value : 0;
}
if (!string.IsNullOrWhiteSpace(plcAdd.) && (item.IsJog || !item.IsFold))
{
//var data2 = plc?.Read<Int16>(plcAdd.手动速度获取);
//item.JogSpeed = data2?.IsSucceed == true ? data2.Value : 0;
}
if (!string.IsNullOrWhiteSpace(plcAdd.) && (!item.IsJog || !item.IsFold))
{
//var data3 = plc?.Read<Int16>(plcAdd.自动速度设置);
//item.AutoSpeed = data3?.IsSucceed == true ? data3.Value : 0;
}
}
}
await Task.Delay(whileSleep);
}
catch (Exception)
{
}
}
}
/*一起选中【操作控制】【操作气缸】【操作伺服】可以快速解开全部注释*/
#region
////单击
public void WriteClick(object sender, RoutedEventArgs e)
{
var data = (DeviceWriteModel)((FrameworkElement)sender).DataContext;
var dataExcel = data.ExcelTag;
var mode = dataExcel.?.Trim() ?? "";
if (dataExcel..Trim().ToLower() == "bool" && mode.StartsWith("切换"))
{
Task.Run(() =>
{
var boolval = data.Value is true;
//plc?.Write(dataExcel.写地址, !boolval);
data.Value = !boolval;
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "控制", Funct = string.Empty, Val = data.Value, Mode = mode });
});
}
else
{
var ts = dataExcel..Trim().ToLower();
switch (ts)
{
case "byte":
WriteClickDialog<byte>(data);
break;
case "int16":
WriteClickDialog<Int16>(data);
break;
case "int32":
WriteClickDialog<Int32>(data);
break;
case "uint16":
WriteClickDialog<UInt16>(data);
break;
case "uint32":
WriteClickDialog<UInt32>(data);
break;
case "float":
case "single":
WriteClickDialog<float>(data);
break;
case "double":
WriteClickDialog<double>(data);
break;
default:
break;
}
}
}
////单击弹框
void WriteClickDialog<T>(DeviceWriteModel data) where T : struct
{
var dataExcel = data.ExcelTag;
var val = TipInputView.Show<T>($"请输入新的[{dataExcel.名称}]值:", "修改值", "请输入值");
if (!val.HasValue)
return;
//plc?.Write<T>(dataExcel.写地址, val.Value);
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "控制", Funct = string.Empty, Val = val.Value, Mode = "" });
}
////按下左键
public void LeftDown(object sender, MouseButtonEventArgs e)
{
var data = (DeviceWriteModel)((FrameworkElement)sender).DataContext;
var dataExcel = data.ExcelTag;
var mode = dataExcel.?.Trim() ?? "";
if (dataExcel..Trim().ToLower() == "bool" && mode.StartsWith("点动"))
{
Task.Run(() =>
{
//plc?.Write(dataExcel.写地址, true);
data.Value = true;
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "控制", Funct = string.Empty, Val = data.Value, Mode = mode });
});
}
}
////放开左键
public void LeftUp(object sender, MouseButtonEventArgs e)
{
var data = (DeviceWriteModel)((FrameworkElement)sender).DataContext;
var dataExcel = data.ExcelTag;
var mode = dataExcel.?.Trim() ?? "";
if (dataExcel..Trim().ToLower() == "bool" && mode.StartsWith("点动"))
{
Task.Run(() =>
{
//plc?.Write(dataExcel.写地址, false);
data.Value = false;
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "控制", Funct = string.Empty, Val = data.Value, Mode = mode });
});
}
}
#endregion
#region
////按钮1单击
public void Button1_Click(object sender, RoutedEventArgs e)
{
var data = (DeviceUrnModel)((FrameworkElement)sender).DataContext;
var dataExcel = data.ExcelTag;
var mode = dataExcel.?.Trim() ?? "";
if (mode.StartsWith("切换"))
{
Task.Run(() =>
{
//plc?.Write(dataExcel.推地址, true);
//plc?.Write(dataExcel.回地址, false);
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "气缸", Funct = "推", Val = true, Mode = mode });
});
}
}
////按钮1按下
public void But1ClickDown(object sender, RoutedEventArgs e)
{
var data = (DeviceUrnModel)((FrameworkElement)sender).DataContext;
var dataExcel = data.ExcelTag;
var mode = dataExcel.?.Trim() ?? "";
if (mode.StartsWith("点动"))
{
Task.Run(() =>
{
//plc?.Write(dataExcel.推地址, true);
data.IsGoTo = true;
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "气缸", Funct = "推", Val = true, Mode = mode });
});
}
}
////按钮1松开
public void But1ClickUp(object sender, RoutedEventArgs e)
{
var data = (DeviceUrnModel)((FrameworkElement)sender).DataContext;
var dataExcel = data.ExcelTag;
var mode = dataExcel.?.Trim() ?? "";
if (mode.StartsWith("点动"))
{
Task.Run(() =>
{
//plc?.Write(dataExcel.推地址, false);
data.IsGoTo = false;
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "气缸", Funct = "推", Val = false, Mode = mode });
});
}
}
////按钮2单击
public void Button2_Click(object sender, RoutedEventArgs e)
{
var data = (DeviceUrnModel)((FrameworkElement)sender).DataContext;
var dataExcel = data.ExcelTag;
var mode = dataExcel.?.Trim() ?? "";
if (mode.StartsWith("切换"))
{
Task.Run(() =>
{
//plc?.Write(dataExcel.推地址, false);
//plc?.Write(dataExcel.回地址, true);
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "气缸", Funct = "回", Val = true, Mode = mode });
});
}
}
////按钮2按下
public void But2ClickDown(object sender, RoutedEventArgs e)
{
var data = (DeviceUrnModel)((FrameworkElement)sender).DataContext;
var dataExcel = data.ExcelTag;
var mode = dataExcel.?.Trim() ?? "";
if (mode.StartsWith("点动"))
{
Task.Run(() =>
{
//plc?.Write(dataExcel.回地址, true);
data.IsRetTo = true;
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "气缸", Funct = "回", Val = true, Mode = mode });
});
}
}
////按钮2松开
public void But2ClickUp(object sender, RoutedEventArgs e)
{
var data = (DeviceUrnModel)((FrameworkElement)sender).DataContext;
var dataExcel = data.ExcelTag;
var mode = dataExcel.?.Trim() ?? "";
if (mode.StartsWith("点动"))
{
Task.Run(() =>
{
//plc?.Write(dataExcel.回地址, false);
data.IsRetTo = false;
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "气缸", Funct = "回", Val = false, Mode = mode });
});
}
}
#endregion
#region
////尝试改变伺服的位置时
public void LocationChange(object sender, RoutedEventArgs e)
{
var data = (DeviceServoModel)((FrameworkElement)sender).DataContext;
var dataExcel = data.ExcelTag;
var mode = string.Empty;
////运动方式
if (e.OriginalSource is ServoClickType servoClickType)
{
if (servoClickType == ServoClickType.StartDotAdd)
{
//plc?.Write(dataExcel.位置点动加, true);
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "伺服", Funct = "开始点动加", Val = true, Mode = mode });
}
else if (servoClickType == ServoClickType.EndDotAdd)
{
//plc?.Write(dataExcel.位置点动加, false);
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "伺服", Funct = "结束点动加", Val = false, Mode = mode });
}
else if (servoClickType == ServoClickType.StartDotSub)
{
//plc?.Write(dataExcel.位置点动减, true);
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "伺服", Funct = "开始点动减", Val = true, Mode = mode });
}
else if (servoClickType == ServoClickType.EndDotSub)
{
//plc?.Write(dataExcel.位置点动减, false);
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "伺服", Funct = "结束点动减", Val = false, Mode = mode });
}
}
////运动到指定位置
else if (e.OriginalSource is double val)
{
//plc?.Write(dataExcel.位置移动, Convert.ToSingle(val));
data.Location = val;
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "伺服", Funct = "位置移动", Val = val, Mode = mode });
}
}
////尝试改变伺服的速度时
public void SpeedChange(object sender, RoutedEventArgs e)
{
var data = (DeviceServoModel)((FrameworkElement)sender).DataContext;
var dataExcel = data.ExcelTag;
var mode = string.Empty;
var data2 = (ServoSpeed)e.OriginalSource;
if (data2.Name.StartsWith("手动"))
{
//plc?.Write(dataExcel.手动速度设置, Convert.ToSingle(data2.Speed));
data.JogSpeed = data2.Speed;
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "伺服", Funct = "手动速度设置", Val = data2.Speed, Mode = mode });
}
else
{
//plc?.Write(dataExcel.自动速度设置, Convert.ToSingle(data2.Speed));
data.AutoSpeed = data2.Speed;
IotDevice.UserChange?.Invoke(new IotDevice() { Name = data.Name, Type = "伺服", Funct = "自动速度设置", Val = data2.Speed, Mode = mode });
}
}
#endregion
}
public class DeviceReadModel : BindableBase
{
#region
private string Name_;
/// <summary>
/// 名称
/// </summary>
public string Name { get => Name_; set { SetProperty(ref Name_, value); } }
private object Value_;
/// <summary>
/// 值
/// </summary>
public object Value { get => Value_; set { SetProperty(ref Value_, value); } }
/// <summary>
/// 是否可见
/// </summary>
public bool IsExpanded { get; set; }
/// <summary>
/// Excel原始数据
/// </summary>
public ExcelDeviceReadModel ExcelTag { get; set; }
#endregion
}
public class DeviceWriteModel : BindableBase
{
#region
private string Name_;
/// <summary>
/// 名称
/// </summary>
public string Name { get => Name_; set { SetProperty(ref Name_, value); } }
private object Value_;
/// <summary>
/// 是否合格
/// </summary>
public object Value { get => Value_; set { SetProperty(ref Value_, value); } }
/// <summary>
/// 是否可见
/// </summary>
public bool IsExpanded { get; set; }
/// <summary>
/// Excel原始数据
/// </summary>
public ExcelDeviceWriteModel ExcelTag { get; set; }
#endregion
}
public class DeviceUrnModel : BindableBase
{
#region
private string Name_;
/// <summary>
/// 名称
/// </summary>
public string Name { get => Name_; set { SetProperty(ref Name_, value); } }
private bool IsGoTo_;
/// <summary>
/// 是否推到位
/// </summary>
public bool IsGoTo { get => IsGoTo_; set { SetProperty(ref IsGoTo_, value); } }
private bool IsRetTo_;
/// <summary>
/// 是否回到位
/// </summary>
public bool IsRetTo { get => IsRetTo_; set { SetProperty(ref IsRetTo_, value); } }
/// <summary>
/// 是否可见
/// </summary>
public bool IsExpanded { get; set; }
/// <summary>
/// 自定义数据
/// </summary>
public ExcelDeviceUrnModel ExcelTag { get; set; }
#endregion
}
public class DeviceServoModel : BindableBase
{
#region
private string Name_;
/// <summary>
/// 名称
/// </summary>
public string Name { get => Name_; set { SetProperty(ref Name_, value); } }
private double JogSpeed_;
/// <summary>
/// 手动模式速度
/// </summary>
public double JogSpeed { get => JogSpeed_; set { SetProperty(ref JogSpeed_, value); } }
private double AutoSpeed_;
/// <summary>
/// 自动模式速度
/// </summary>
public double AutoSpeed { get => AutoSpeed_; set { SetProperty(ref AutoSpeed_, value); } }
private double Location_;
/// <summary>
/// 伺服当前位置
/// </summary>
public double Location { get => Location_; set { SetProperty(ref Location_, value); } }
private bool IsJog_ = true;
/// <summary>
/// 是否主页显示为手动模式
/// </summary>
public bool IsJog { get => IsJog_; set { SetProperty(ref IsJog_, value); } }
private bool IsFold_ = true;
/// <summary>
/// 是否折叠
/// </summary>
public bool IsFold { get => IsFold_; set { SetProperty(ref IsFold_, value); } }
/// <summary>
/// 是否可见
/// </summary>
public bool IsExpanded { get; set; }
private ExcelDeviceServoModel ExcelTag_;
/// <summary>
/// 自定义数据
/// </summary>
public ExcelDeviceServoModel ExcelTag { get => ExcelTag_; set { SetProperty(ref ExcelTag_, value); } }
#endregion
}
}

View File

@ -0,0 +1,109 @@
using HandyControl.Controls;
using LiveCharts;
using Ping9719.WpfEx;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using HandyControl.Tools.Extension;
using .Views.Controls;
using .Api;
using WCS.Model;
namespace .ViewModel
{
public class HomeViewModel : BindableBase
{
WarnInfoContainer WarnInfo = new WarnInfoContainer();//警告、错误等信息
#region
private string textErr;
/// <summary>
/// 错误文本
/// </summary>
public string TextErr { get => textErr; set { SetProperty(ref textErr, value); } }
public ICommand ClearTextInfoCommand { get => new DelegateCommand(ClearTextInfo); }
/// <summary>
/// 清除信息文本
/// </summary>
public void ClearTextInfo()
{
TextBoxLog.ClearLog();
}
public ICommand ClearTextErrCommand { get => new DelegateCommand(ClearTextErr); }
/// <summary>
/// 清除全部错误文本
/// </summary>
public void ClearTextErr()
{
WarnInfo.RemoveAll(WarnInfoType.AlwayWarn);
}
public ICommand AddUserControlCommand { get => new DelegateCommand(AddUserControl); }
public WrapPanel wrapPanel;
public async void AddUserControl()
{
var dia = Dialog.Show(new TextDialog());
try
{
var body = new GetShelfStatusRequest()
{
UserName = "xxx",
DeviceType = "WCS前端",
GroupNames = LocalFile.Config.GroupName,
};
var Result = await ApiHelp.Post<GetShelfStatusResponse>([LocalFile.Config.ApiIpHost, "home/getShelfStatus"], body);
if (Result != null && Result.Data?.Count > 0)
{
wrapPanel.Children.Clear();
Result.Data.ForEach(t =>
{
var shelf = new ShelfStatusControl(t.ShelfCode, t.CurentMode, t.GroupName);
wrapPanel.Children.Add(shelf);
});
}
}
catch (Exception ex)
{
}
finally
{
dia.Close();
}
}
#endregion
#region
/// <summary>
/// 页面第一次加载时执行的任务
/// </summary>
public void LoadTask()
{
//注册警告事件
WarnInfo.WarnInfoChanged += (all, add, rem) =>
{
TextErr = string.Join(Environment.NewLine, all.OrderBy(o => (o.WarnType, o.Source, o.Text)));
if (add.Any())
Logs.Write(add.Select(o => o.ToString()), LogsType.Warning);
if (rem.Any())
Logs.Write(rem.Select(o => o.ToString()), LogsType.Warning);
//警告信息保存到数据库
if (WarnInfoDb.IsEnabled)
{
WarnInfoDb.db.Insertable(WarnInfoItemDb.GetList(add)).ExecuteCommand();
WarnInfoDb.db.Updateable(WarnInfoItemDb.GetList(rem)).ExecuteCommand();
}
};
}
#endregion
}
}

View File

@ -0,0 +1,55 @@
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
namespace .ViewModel
{
public class ImageListenerViewModel : BindableBase
{
#region MyRegion
private BitmapFrame ImageSource_;
public BitmapFrame ImageSource { get => ImageSource_; set { SetProperty(ref ImageSource_, value); } }
public double ImageWidth { get; set; }
public double ImageHeight { get; set; }
#endregion
#region
private double ScaleXY_ = 1;
public double ScaleXY { get => ScaleXY_; set { SetProperty(ref ScaleXY_, value); } }
private double CenterX_;
public double CenterX { get => CenterX_; set { SetProperty(ref CenterX_, value); } }
private double CenterY_;
public double CenterY { get => CenterY_; set { SetProperty(ref CenterY_, value); } }
private double TranslateX_;
public double TranslateX { get => TranslateX_; set { SetProperty(ref TranslateX_, value); } }
private double TranslateY_;
public double TranslateY { get => TranslateY_; set { SetProperty(ref TranslateY_, value); } }
/// <summary>
/// 自适应大小
/// </summary>
public void ImgAutoSize()
{
ScaleXY = 1;
CenterX = 0;
CenterY = 0;
TranslateX = 0;
TranslateY = 0;
}
#endregion
}
}

View File

@ -0,0 +1,207 @@
using HandyControl.Controls;
using MiniExcelLibs;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using SqlSugar;
using HandyControl.Data;
using System.Windows;
using Newtonsoft.Json.Linq;
using .Views.Controls;
using WCS.Model.ApiModel.User;
using .Api;
using WCS.Model;
using WCS.Model.ApiModel;
using System.Windows.Controls;
using WCS.Model.ApiModel.InterfaceRecord;
using TouchSocket.Sockets;
using TouchSocket.Core;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel;
using WCS.BLL.DbModels;
using WCS.Model.ApiModel.MatBaseInfo;
using System.Security.Cryptography;
namespace .ViewModel
{
public class InInventoryViewModel : BindableBase
{
public InInventoryViewModel()
{
//初始化串口接收事件
var scanners = ScannerManager.Scanners;
foreach (var scanner in scanners)
{
scanner.SerialPortClient.Received = (client, e) =>
{
//获取串口号
var COM = client.MainSerialPort.PortName;
//获取扫码枪对象
var scanner = ScannerManager.Scanners.Where(t => t.COM == COM).FirstOrDefault();
if (scanner == null)
return EasyTask.CompletedTask;
int newBytes = e.ByteBlock.Len;
if (newBytes > 0)
{
var currentScanedCode = Encoding.UTF8.GetString(e.ByteBlock, 0, e.ByteBlock.Len);
Logs.Write($"接收到扫码枪扫码数据{currentScanedCode}");
scanner.TempCode += currentScanedCode;
//校验末尾码
CheckDataCompleteness(scanner);
scanner.ScannerDisplayControl.RefreshValues(scanner.ShelfCode, scanner.MatSn);
}
return EasyTask.CompletedTask;
};
}
}
#region Property
private string shelfCode;
public string ShelfCode
{
get { return shelfCode; }
set
{
SetProperty(ref shelfCode, value);
}
}
#endregion
#region Command
public void CheckDataCompleteness(Scanner scanner)
{
if (scanner.TempCode.EndsWith("\r"))//结束符 TODO结束符是否需要自定义 现场配置
{
scanner.TempCode = scanner.TempCode.Replace("\r", string.Empty).Replace("\n", string.Empty);
try
{
//TO DO 配置项进行配置正则表达式
//数据处理
string ModuleCodePattern = "^[ABCD][0-9]{2}-R[0-9]{1,2}C[0-9]{1,2}$";
var isModuleCode = Regex.IsMatch(scanner.TempCode, ModuleCodePattern);
if (isModuleCode)
{
ModuleCodeProcess(scanner);
}
//TO DO 增加正则表达式进行判断是否扫到的是物料码
else
{
MatSnProcess(scanner);
}
}
catch (Exception ex)
{
var message = "入库扫码枪扫码发生异常:" + ex.Message;
}
finally
{
//不管入库成功与否 认为本次扫码完毕 清空暂存数据
scanner.TempCode = string.Empty;
}
}
}
/// <summary>
/// 扫到模组码的数据处理
/// </summary>
/// <param name="scanner"></param>
public void ModuleCodeProcess(Scanner scanner)
{
//如果扫码枪前一个货架未退出入库
if (scanner.IsInstoreMode)
{
//判断当前入库货架是否包含本次扫码的模组
if (scanner.ModulesStr.Contains(scanner.TempCode))
{
return;
}
else
{
#region
try
{
var body = new ShelfGoOutInStoreRequest()
{
ShelfCode = scanner.ShelfCode,
IPAdress = scanner.COM,
DeviceType = LocalFile.Config.DeviceType,
UserName = LocalStatic.CurrentUser,
};
var Result = ApiHelp.GetDataFromHttp<ResponseBase>(LocalFile.Config.ApiIpHost + "instore/shelfGoOutInStore", body, "POST");
if (Result != null && Result.Code == 200)
{
scanner.ShelfCode = string.Empty;
scanner.ModulesStr = string.Empty;
}
}
catch (Exception ex)
{
}
#endregion
}
}
//调用接口 请求进入入库模式
#region
try
{
var body = new ShelfGoInInstoreRequest()
{
ModuleCode = scanner.TempCode,
DeviceType = LocalFile.Config.DeviceType,
UserName = LocalStatic.CurrentUser,
IpAdress = scanner.COM,
};
var Result = ApiHelp.GetDataFromHttp<ShelfGoInInstoreResponse>(LocalFile.Config.ApiIpHost + "instore/shelfGoInInStore", body, "POST");
if (Result != null && Result.Code == 200)
{
scanner.ShelfCode = Result.Data.ShelfCode;
scanner.ModulesStr = Result.Data.ModulesStr;
}
}
catch (Exception ex)
{
}
#endregion
}
/// <summary>
/// 扫到物料码的数据处理
/// </summary>
public void MatSnProcess(Scanner scanner)
{
#region
try
{
var body = new QueryByMatSnRequest()
{
ShelfCode = scanner.ShelfCode,
IpAddress = scanner.COM,
DeviceType = LocalFile.Config.DeviceType,
UserName = LocalStatic.CurrentUser,
};
var Result = ApiHelp.GetDataFromHttp<QueryByMatSnResponse>(LocalFile.Config.ApiIpHost + "instore/queryByMatSn", body, "POST");
if (Result != null && Result.Code == 200)
{
scanner.MatSn = Result.Data.materialBar;
}
}
catch (Exception ex)
{
}
#endregion
}
#endregion
}
}

View File

@ -0,0 +1,288 @@
using HandyControl.Controls;
using MiniExcelLibs;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using SqlSugar;
using HandyControl.Data;
using System.Windows;
using Newtonsoft.Json.Linq;
using .Views.Controls;
using WCS.Model.ApiModel.User;
using .Api;
using WCS.Model;
using WCS.Model.ApiModel;
using System.Windows.Controls;
using WCS.Model.ApiModel.InterfaceRecord;
namespace .ViewModel
{
public class InterfaceRecordViewModel : BindableBase
{
#region Property
private List<SystemApiLogModel> dataGridItemSource;
public List<SystemApiLogModel> DataGridItemSource
{
get { return dataGridItemSource; }
set
{
SetProperty(ref dataGridItemSource, value);
}
}
/// <summary>
/// 接口地址
/// </summary>
private string requestUrl;
public string RequestUrl
{
get { return requestUrl; }
set
{
SetProperty(ref requestUrl, value);
}
}
/// <summary>
/// 请求参数
/// </summary>
private string requestBody;
public string RequestBody
{
get { return requestBody; }
set
{
SetProperty(ref requestBody, value);
}
}
/// <summary>
/// 请求时间的类型
/// </summary>
private TimeType timeType;
public TimeType TimeType
{
get { return timeType; }
set
{
SetProperty(ref timeType, value);
}
}
public IEnumerable<string> TimeTypes => GetEnumValues();
private IEnumerable<string> GetEnumValues()
{
return Enum.GetNames(typeof(TimeType));
}
private DateTime startTime;
public DateTime StartTime
{
get { return startTime; }
set
{
SetProperty(ref startTime, value);
}
}
private DateTime endTime;
public DateTime EndTime
{
get { return endTime; }
set
{
SetProperty(ref endTime, value);
}
}
/// <summary>
/// 调用类型 调用/被调用
/// </summary>
private string requestType;
public string RequestType
{
get { return requestType; }
set
{
SetProperty(ref requestType, value);
}
}
#endregion
#region Command
public ICommand BtnResetCommand { get => new DelegateCommand(BtnReset); }
public void BtnReset()
{
RequestUrl = string.Empty;
RequestBody = string.Empty;
RequestType = string.Empty;
TimeType = TimeType.;
StartTime = DateTime.Now.Date;
EndTime = DateTime.Now.Date.AddDays(1);
}
public ICommand BtnSearchCommand { get => new DelegateCommand(BtnSearchReset); }
public void BtnSearchReset()
{
BtnSearch(true);
}
public void BtnSearch(bool IsPageReset = true)
{
if (CurrentPage == 0 || IsPageReset)
{
CurrentPage = 1;
return;
}
#region
var dia = Dialog.Show(new TextDialog());
try
{
var body = new GetInterfaceRecordsRequest()
{
RequestUrl = RequestUrl,
RequestBody = RequestBody,
RequestType = RequestType,
TimeType = TimeType,
StartTime = StartTime,
EndTime = EndTime,
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
PageNumber = CurrentPage,
PageSize = 10,
};
var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<SystemApiLogModel>>(LocalFile.Config.ApiIpHost + "interfaceRecord/getInterfaceRecord", body, "POST");
if (Result != null && Result.Data != null && Result.Data.Lists != null)
{
DataGridItemSource = Result.Data.Lists;
MaxPage = Result.Data.MaxPage;
TotalCount = Result.Data.TotalCount;
}
}
catch (Exception ex)
{
Growl.Error("加载数据失败:" + ex.Message);
}
finally
{
dia.Close();
}
#endregion
}
public ICommand BtnExportCommand { get => new DelegateCommand(BtnExport); }
public async void BtnExport()
{
try
{
#region
Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
sfd.Filter = ".xlsx文件(*.xlsx)|*.xlsx";
sfd.FileName = "接口记录" + DateTime.Now.ToString("yyyyMMddhhmmss");
sfd.OverwritePrompt = true;
if (sfd.ShowDialog() != true)
{
return;
}
string path = sfd.FileName;
#endregion
var body = new GetInterfaceRecordsRequest()
{
RequestUrl = RequestUrl,
RequestBody = RequestBody,
RequestType = RequestType,
TimeType = TimeType,
StartTime = StartTime,
EndTime = EndTime,
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
PageNumber = CurrentPage,
PageSize = 10,
};
await ApiHelp.PostDownloadFileAsync(path, System.Net.Http.HttpMethod.Post, LocalFile.Config.ApiIpHost + "interfaceRecord/exportInterfaceRecord", body);
Growl.Success("导出成功!");
}
catch (Exception ex)
{
Growl.Error("导出失败:" + ex.Message);
}
}
#endregion
#region PageOperation
private int currentPage;
public int CurrentPage
{
get { return currentPage; }
set
{
SetProperty(ref currentPage, value);
BtnSearch(false);
}
}
private int maxPage;
public int MaxPage
{
get { return maxPage; }
set { SetProperty(ref maxPage, value); }
}
//总数量
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set { SetProperty(ref totalCount, value); }
}
public ICommand BtnFirstPageCommand { get => new DelegateCommand(BtnFirstPage); }
public void BtnFirstPage()
{
CurrentPage = 1;
}
public ICommand BtnPrePageCommand { get => new DelegateCommand(BtnPrePage); }
public void BtnPrePage()
{
if (CurrentPage > 1)
{
CurrentPage--;
}
}
public ICommand BtnNextPageCommand { get => new DelegateCommand(BtnNextPage); }
public void BtnNextPage()
{
if (CurrentPage < MaxPage)
{
CurrentPage++;
}
}
public ICommand BtnLastPageCommand { get => new DelegateCommand(BtnLastPage); }
public void BtnLastPage()
{
if (CurrentPage != MaxPage)
{
CurrentPage = MaxPage;
}
}
#endregion
}
}

View File

@ -0,0 +1,227 @@
using HandyControl.Controls;
using Newtonsoft.Json;
using Ping9719.WpfEx;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Markup;
namespace .ViewModel
{
public class MainViewModel : BindableBase
{
Mutex mutex;
private string title = string.Empty;
/// <summary>
/// 标题
/// </summary>
public string Title { get => title; set { SetProperty(ref title, value); } }
#region _MainWindow2
//隐藏式选项卡的高度
public double TabItemHeight { get; set; } = 0;
private string SelectedValue_ = "主页";
public string SelectedValue { get => SelectedValue_; set { SetProperty(ref SelectedValue_, value); } }
#endregion
private DateTime time;
/// <summary>
/// 时间
/// </summary>
public DateTime Time { get => time; set { SetProperty(ref time, value); } }
/// <summary>
/// 在初始化前的相关检查
/// </summary>
public bool InitAgo()
{
//只允许打开一个
mutex = new Mutex(true, string.Concat("MengXun货架标准上位机", Path.GetFileNameWithoutExtension(LocalFile.AppName)), out bool createdNew);
if (!createdNew)
{
MessageBox.Warning("已有实列在运行!", "提示");
return false;
}
//初始化
Tuple<string, string, Action>[] tuples = new Tuple<string, string, Action>[]
{
new Tuple<string, string, Action>("检测文件..", "缺少文件,尝试将项目[data/]中的所有文件复制到[bin/data/]中", () =>
{
if(!System.IO.File.Exists(LocalFile.ConfigPath))
throw new Exception("缺少文件,请尝试将项目[data/]中的所有文件复制到[bin/data/]中");
}),
new Tuple<string, string, Action>("检测文件..", "配置文件中没有内容,请联系管理员", () =>
{
if(string.IsNullOrWhiteSpace(System.IO.File.ReadAllText(LocalFile.ConfigPath, Encoding.UTF8)))
throw new Exception($"配置文件[{LocalFile.ConfigPath}]中没有内容");
}),
new Tuple<string, string, Action>("初始化数据中..", "初始化数据库失败,请联系管理员", () =>
{
}),
new Tuple<string, string, Action>("初始化扫码枪连接..", "初始化扫码枪连接失败,请联系管理员", () =>
{
ScannerManager.InitScanners();
}),
};
MainLoadWindow.TaskSleepTime = 200;
if (!MainLoadWindow.Show(tuples))
return false;
//清理日志
Task.Run(() =>
{
if (LocalFile.Config.Sys.SaveLogDay < 0)
return;
Logs.Clear(TimeSpan.FromDays(LocalFile.Config.Sys.SaveLogDay));
});
////不登录,直接使用最高权限
//{
// UserLoginView.NotLogin();
// return true;
//}
//登录
{
var userLoginView = new UserLoginView();
var isok = userLoginView.ShowDialog() == true;
userLoginView = null;
return isok;
}
}
/// <summary>
/// 初始化并运行时间
/// </summary>
public async void Init(System.Windows.Window window)
{
//加载 程序名称
var versionInfo = FileVersionInfo.GetVersionInfo(LocalFile.AppPath);
Title = versionInfo.ProductName;
//加载 窗体模式
if (LocalFile.Config.Sys.StartupFull)
window.WindowState = System.Windows.WindowState.Maximized;
//注册 设备
IotDevice.UserChange = ((iot) =>
{
if (string.IsNullOrEmpty(iot.Funct))
Growl.Info($"你点击了[{iot.Name}],尝试改为[{iot.Val}]");
else
Growl.Info($"你点击了[{iot.Name}][{iot.Funct}],尝试改为[{iot.Val}]");
});
//注册 信息
TextBoxLog.TextBoxLogAdd = ((info) =>
{
Logs.Write(info.Text, LogsType.Info, info.Time);
});
//加载 时钟
while (true)
{
Time = DateTime.Now;
await Task.Delay(1);
}
}
public ICommand OpenUserCommand { get => new DelegateCommand(OpenUser); }
/// <summary>
/// 打开用户
/// </summary>
public void OpenUser()
{
if (UserInfoView.viewModel.IsLogin)
{
var userInfoView = new UserInfoView();
userInfoView.ShowDialog();
if (userInfoView.IsExitLogin)
{
Growl.Info("您已退出登录。");
userInfoView = null;
}
}
else
{
var userLoginView = new UserLoginView();
//登录成功
if (userLoginView.ShowDialog() == true)
{
Growl.Success($"欢迎您:{UserInfoView.viewModel.LoginName}");
userLoginView = null;
}
}
}
public ICommand OpenLogCommand { get => new DelegateCommand(OpenLog); }
/// <summary>
/// 打开日记
/// </summary>
public void OpenLog()
{
if (!System.IO.Directory.Exists(LocalFile.LogDir))
{
Growl.Info("暂时没有日志。");
return;
}
try
{
Folder.OpenFolder(LocalFile.LogDir);
}
catch (Exception)
{
Growl.Error("打开日志目录失败。");
}
}
public ICommand OpenHelpCommand { get => new DelegateCommand(OpenHelp); }
/// <summary>
/// 打开帮助
/// </summary>
public void OpenHelp()
{
if (!System.IO.File.Exists(LocalFile.DocPath))
{
Growl.Info("帮助文档正在书写中。");
return;
}
try
{
Folder.OpenFolderAndSelectedFile(LocalFile.DocPath);
}
catch (Exception)
{
Growl.Error("打开帮助文档失败。");
}
}
public ICommand OpenWeCommand { get => new DelegateCommand(OpenWe); }
/// <summary>
/// 打开关于
/// </summary>
public void OpenWe()
{
var aboutView = new AboutView();
aboutView.ShowDialog();
aboutView = null;
}
}
}

View File

@ -0,0 +1,41 @@
using HandyControl.Controls;
using MiniExcelLibs;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using SqlSugar;
using HandyControl.Data;
using System.Windows;
using Newtonsoft.Json.Linq;
using .Views.Controls;
using WCS.Model.ApiModel.User;
using .Api;
using WCS.Model;
using WCS.Model.ApiModel;
using System.Windows.Controls;
using WCS.Model.ApiModel.InterfaceRecord;
using WCS.BLL.DbModels;
using WCS.Model.ApiModel.MatBaseInfo;
namespace .ViewModel
{
public class MatBaseInfoAddOrUpdateViewModel : BindableBase
{
private bool isEnable;
public bool IsEnable
{
get { return isEnable; }
set
{
SetProperty(ref isEnable, value);
}
}
}
}

View File

@ -0,0 +1,470 @@
using HandyControl.Controls;
using MiniExcelLibs;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using SqlSugar;
using HandyControl.Data;
using System.Windows;
using Newtonsoft.Json.Linq;
using .Views.Controls;
using WCS.Model.ApiModel.User;
using .Api;
using WCS.Model;
using WCS.Model.ApiModel;
using System.Windows.Controls;
using WCS.Model.ApiModel.InterfaceRecord;
using WCS.BLL.DbModels;
using WCS.Model.ApiModel.MatBaseInfo;
using System.Collections.ObjectModel;
using HandyControl.Tools.Extension;
using .Tool;
namespace .ViewModel
{
public class MatBaseInfoViewModel : BindableBase
{
#region Property
private ObservableCollection<MatBaseInfoModel> dataGridItemSource;
public ObservableCollection<MatBaseInfoModel> DataGridItemSource
{
get { return dataGridItemSource; }
set
{
SetProperty(ref dataGridItemSource, value);
}
}
public MatBaseInfoModel selectedataGridItem;
public MatBaseInfoModel SelectedataGridItem
{
get { return selectedataGridItem; }
set
{
SetProperty(ref selectedataGridItem, value);
}
}
/// <summary>
/// 物料编码
/// </summary>
private string matCode;
public string MatCode
{
get { return matCode; }
set
{
SetProperty(ref matCode, value);
}
}
/// <summary>
/// 物料名称
/// </summary>
private string matName;
public string MatName
{
get { return matName; }
set
{
SetProperty(ref matName, value);
}
}
/// <summary>
/// 物料规格
/// </summary>
private string matSpec;
public string MatSpec
{
get { return matSpec; }
set
{
SetProperty(ref matSpec, value);
}
}
/// <summary>
/// 请求时间的类型
/// </summary>
private bool? isEnable;
public bool? IsEnable
{
get { return isEnable; }
set
{
SetProperty(ref isEnable, value);
}
}
#endregion
#region Command
public ICommand BtnResetCommand { get => new DelegateCommand(BtnReset); }
public void BtnReset()
{
MatCode = string.Empty;
MatName = string.Empty;
MatSpec = string.Empty;
IsEnable = null;
}
public ICommand BtnSearchCommand { get => new DelegateCommand(BtnSearchReset); }
public void BtnSearchReset()
{
BtnSearch(true);
}
public void BtnSearch(bool IsPageReset = true)
{
if (CurrentPage == 0 || IsPageReset)
{
CurrentPage = 1;
return;
}
#region
var dia = Dialog.Show(new TextDialog());
try
{
var body = new GetMatBaseInfoRequest()
{
MatCode = MatCode,
MatName = MatName,
MatSpec = MatSpec,
IsEnable = IsEnable,
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
PageNumber = CurrentPage,
PageSize = 10,
};
var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<MatBaseInfoModel>>(LocalFile.Config.ApiIpHost + "matBaseInfo/getMatBaseInfo", body, "POST");
if (Result != null && Result.Data != null && Result.Data.Lists != null)
{
DataGridItemSource = new ObservableCollection<MatBaseInfoModel>(Result.Data.Lists);
//DataGridItemSource = Result.Data.Lists;
MaxPage = Result.Data.MaxPage;
TotalCount = Result.Data.TotalCount;
}
}
catch (Exception ex)
{
Growl.Error("加载数据失败:" + ex.Message);
}
finally
{
dia.Close();
}
#endregion
}
/// <summary>
/// 导出数据为Excel文件
/// </summary>
public ICommand BtnExportCommand { get => new DelegateCommand(BtnExport); }
public async void BtnExport()
{
try
{
#region
Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
sfd.Title = "选择文件保存路径";
sfd.Filter = ".xlsx文件(*.xlsx)|*.xlsx";
sfd.FileName = "物料管理" + DateTime.Now.ToString("yyyyMMddhhmmss");
sfd.OverwritePrompt = true;
if (sfd.ShowDialog() != true)
{
return;
}
string path = sfd.FileName;
#endregion
var body = new GetMatBaseInfoRequest()
{
MatCode = MatCode,
MatName = MatName,
MatSpec = MatSpec,
IsEnable = IsEnable,
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
PageNumber = CurrentPage,
PageSize = 10,
};
await ApiHelp.PostDownloadFileAsync(path, System.Net.Http.HttpMethod.Post, LocalFile.Config.ApiIpHost + "matBaseInfo/exportMatBaseInfo", body);
Growl.Success("导出成功!");
}
catch (Exception ex)
{
Growl.Error("导出失败:" + ex.Message);
}
}
public ICommand BtnImportCommand { get => new DelegateCommand(BtnImport); }
public async void BtnImport()
{
try
{
#region
Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.Title = "选择模板";
ofd.Filter = ".xlsx文件(*.xlsx)|*.xlsx";
ofd.FileName = "物料管理" + DateTime.Now.ToString("yyyyMMddhhmmss");
ofd.Multiselect = false;
if (ofd.ShowDialog() != true)
{
return;
}
#endregion
//已经选择文件 调用接口进行导入数据
string path = ofd.FileName;
var body = new GetMatBaseInfoRequest()
{
MatCode = MatCode,
MatName = MatName,
MatSpec = MatSpec,
IsEnable = IsEnable,
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
PageNumber = CurrentPage,
PageSize = 10,
};
var result = await ApiHelp.PostImportFileAsync<ResponseCommon<List<string>>>(path, System.Net.Http.HttpMethod.Post,
LocalFile.Config.ApiIpHost + "matBaseInfo/importMatBaseInfo", LocalStatic.CurrentUser, LocalFile.Config.DeviceType);
if (result.Code == 200)
{
Growl.Success("成功导入!");
CurrentPage = 0;
}
else
{
if (result.Data != null && result.Data.Count > 0)
HandyControl.Controls.MessageBox.Show(result.Message + "\t\n" + String.Join("\t\n", result.Data));
else
HandyControl.Controls.MessageBox.Show(result.Message);
}
}
catch (Exception ex)
{
Growl.Error("导入失败:" + ex.Message);
}
}
/// <summary>
/// 物料新增操作
/// </summary>
public ICommand BtnAddCommand { get => new DelegateCommand(BtnAdd); }
public async void BtnAdd()
{
var addView = new MatBaseInfoAddOrUpdateView("新增物料数据");
addView.ShowDialog();
if (addView.DialogResult == true)
{
var matBaseInfo = addView.matBaseInfo;
matBaseInfo.ModifyTime = DateTime.Now;
matBaseInfo.ModifyUser = LocalStatic.CurrentUser;
var body = new AddMatBaseInfoRequest<MatBaseInfoModel>()
{
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
MatBaseInfo = matBaseInfo,
AddOrUpdate = AddOrUpdate.Add
};
var Result = ApiHelp.GetDataFromHttp<ResponseBase<UserModel>>(LocalFile.Config.ApiIpHost + "matBaseInfo/addOrUpdateMatBaseInfo", body, "POST");
if (Result != null && Result.Code == 200)
{
CurrentPage = 1;
Growl.Success("添加成功!");
}
else
{
Growl.Error($"{Result?.Message?.ToString()}");
//BtnAdd();
}
}
}
/// <summary>
/// 物料修改操作
/// </summary>
public ICommand BtnEditCommand { get => new DelegateCommand(BtnEdit); }
public async void BtnEdit()
{
//查询勾选的第一个数据
var matBaseInfo = DataGridItemSource?.Where(t => t.IsSelected == true).FirstOrDefault();
if (matBaseInfo == null)
{
Growl.Warning("请选择需要修改的数据!");
}
else
{
var addView = new MatBaseInfoAddOrUpdateView("修改物料数据", matBaseInfo);
addView.ShowDialog();
if (addView.DialogResult == true)
{
matBaseInfo = addView.matBaseInfo;
matBaseInfo.ModifyTime = DateTime.Now;
matBaseInfo.ModifyUser = LocalStatic.CurrentUser;
var body = new AddMatBaseInfoRequest<MatBaseInfoModel>()
{
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
MatBaseInfo = matBaseInfo,
AddOrUpdate = AddOrUpdate.Update
};
var Result = ApiHelp.GetDataFromHttp<ResponseBase<UserModel>>(LocalFile.Config.ApiIpHost + "matBaseInfo/addOrUpdateMatBaseInfo", body, "POST");
if (Result != null && Result.Code == 200)
{
CurrentPage = 1;
Growl.Success("修改成功!");
}
else
{
Growl.Error($"{Result?.Message?.ToString()}");
}
}
}
}
/// <summary>
/// 物料删除操作
/// </summary>
public ICommand BtnDeleteCommand { get => new DelegateCommand(BtnDelete); }
public async void BtnDelete()
{
Growl.Ask($"是否删除所有勾选得数据]!", isConfirmed =>
{
if (isConfirmed)
{
//查询勾选的第一个数据
var matBaseInfoIds = DataGridItemSource?.Where(t => t.IsSelected == true)
.Select(t => t.Id)
.ToList();
if (matBaseInfoIds == null)
{
Growl.Warning("请选择需要修改的数据!");
}
else
{
var body = new DeleteMatBaseInfosRequest()
{
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
MatBaseInfoIds = matBaseInfoIds,
};
var Result = ApiHelp.GetDataFromHttp<ResponseBase<UserModel>>(LocalFile.Config.ApiIpHost + "matBaseInfo/deleteMatBaseInfo", body, "POST");
if (Result != null && Result.Code == 200)
{
CurrentPage = 1;
Growl.Success("删除成功!" + Result?.Message);
}
else
{
Growl.Error($"{Result?.Message?.ToString()}");
}
}
}
return true;
});
}
public ICommand BtnPrintCommand { get => new DelegateCommand(BtnPrint); }
public async void BtnPrint()
{
PrintTender.PrintTag(new PrintClass()
{
MatQty = "123",
MatCode = "123",
MatBatch = "123",
MatName = "123",
MatSn = "123",
MatSpec = "123",
});
}
#endregion
#region PageOperation
private int currentPage;
public int CurrentPage
{
get { return currentPage; }
set
{
SetProperty(ref currentPage, value);
BtnSearch(false);
}
}
private int maxPage;
public int MaxPage
{
get { return maxPage; }
set { SetProperty(ref maxPage, value); }
}
//总数量
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set { SetProperty(ref totalCount, value); }
}
public ICommand BtnFirstPageCommand { get => new DelegateCommand(BtnFirstPage); }
public void BtnFirstPage()
{
CurrentPage = 1;
}
public ICommand BtnPrePageCommand { get => new DelegateCommand(BtnPrePage); }
public void BtnPrePage()
{
if (CurrentPage > 1)
{
CurrentPage--;
}
}
public ICommand BtnNextPageCommand { get => new DelegateCommand(BtnNextPage); }
public void BtnNextPage()
{
if (CurrentPage < MaxPage)
{
CurrentPage++;
}
}
public ICommand BtnLastPageCommand { get => new DelegateCommand(BtnLastPage); }
public void BtnLastPage()
{
if (CurrentPage != MaxPage)
{
CurrentPage = MaxPage;
}
}
#endregion
}
}

View File

@ -0,0 +1,336 @@
using HandyControl.Controls;
using MiniExcelLibs;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using SqlSugar;
using HandyControl.Data;
using System.Windows;
using Newtonsoft.Json.Linq;
using .Views.Controls;
using WCS.Model.ApiModel.User;
using .Api;
using WCS.Model;
using WCS.Model.ApiModel;
using System.Windows.Controls;
using WCS.Model.ApiModel.InterfaceRecord;
using HandyControl.Collections;
using WCS.Model.ApiModel.MatBaseInfo;
using WCS.Model.ApiModel.MatInventoryDetail;
namespace .ViewModel
{
public class MatInventoryDetailViewModel : BindableBase
{
public MatInventoryDetailViewModel()
{
//获取物料编码列表
//matCodes = DbHelp.db.Queryable<InventoryDetail>()
// .Select(t => new DataModel()
// {
// MatCode = t.MatCode
// })
// .Distinct()
// .ToList();
}
public void InitMatCode()
{
//调用接口更新!
Task.Run(() =>
{
var body = new GetMatCodeListRequest()
{
IsFromBaseData = false,
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
};
var Result = ApiHelp.GetDataFromHttp<ResponseCommon<List<string>>>(LocalFile.Config.ApiIpHost + "matBaseInfo/getMatCodeList", body, "POST");
if (Result != null && Result.Data != null && Result.Data.Count() > 0)
{
matCodes = Result.Data.Select(t => new DataModel()
{
MatCode = t
}).ToList();
}
});
}
#region Property
private List<MatInventoryDetailModel> dataGridItemSource;
public List<MatInventoryDetailModel> DataGridItemSource
{
get { return dataGridItemSource; }
set
{
SetProperty(ref dataGridItemSource, value);
}
}
/// <summary>
/// 物料编码
/// </summary>
private string matCode;
public string MatCode
{
get { return matCode; }
set
{
SetProperty(ref matCode, value);
FilterItems(value);
}
}
public ManualObservableCollection<DataModel> Items { get; set; } = new();
private List<DataModel> matCodes = new List<DataModel>();
private void FilterItems(string key)
{
//至少输入三个字符 避免删除或输入时界面变卡
if (string.IsNullOrEmpty(key) || key.Length < 3)
{
Items.Clear();
return;
}
key = key.ToUpper();
Items.CanNotify = false;
Items.Clear();
foreach (var matCode in matCodes)
{
if (matCode.MatCode.ToUpper().Contains(key))
{
Items.Add(matCode);
}
}
Items.CanNotify = true;
}
public class DataModel()
{
public string MatCode { get; set; }
}
/// <summary>
/// 物料名称
/// </summary>
private string matName;
public string MatName
{
get { return matName; }
set
{
SetProperty(ref matName, value);
}
}
/// <summary>
/// 物料批次
/// </summary>
private string matBatch;
public string MatBatch
{
get { return matBatch; }
set
{
SetProperty(ref matBatch, value);
}
}
/// <summary>
/// 库位
/// </summary>
private string storeCode;
public string StoreCode
{
get { return storeCode; }
set
{
SetProperty(ref storeCode, value);
}
}
/// <summary>
/// 物料条码
/// </summary>
private string matSN;
public string MatSN
{
get { return matSN; }
set
{
SetProperty(ref matSN, value);
}
}
#endregion
#region Command
public ICommand BtnResetCommand { get => new DelegateCommand(BtnReset); }
public void BtnReset()
{
MatCode = string.Empty;
MatName = string.Empty;
MatSN = string.Empty;
StoreCode = string.Empty;
}
public ICommand BtnSearchCommand { get => new DelegateCommand(BtnSearchReset); }
public void BtnSearchReset()
{
BtnSearch(true);
}
public void BtnSearch(bool IsPageReset = true)
{
if (CurrentPage == 0 || IsPageReset)
{
CurrentPage = 1;
return;
}
#region
var dia = Dialog.Show(new TextDialog());
try
{
var body = new GetMatInventoryDetailRequest()
{
MatName = MatName,
MatSN = MatSN,
MatBatch = MatBatch,
MatCode = MatCode,
StoreCode = StoreCode,
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
PageNumber = CurrentPage,
PageSize = 10,
};
var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<MatInventoryDetailModel>>(LocalFile.Config.ApiIpHost + "matInventoryDetail/getMatInventoryDetail", body, "POST");
if (Result != null && Result.Data != null && Result.Data.Lists != null)
{
DataGridItemSource = Result.Data.Lists;
MaxPage = Result.Data.MaxPage;
TotalCount = Result.Data.TotalCount;
}
}
catch (Exception ex)
{
Growl.Error("加载数据失败:" + ex.Message);
}
finally
{
dia.Close();
}
#endregion
}
public ICommand BtnExportCommand { get => new DelegateCommand(BtnExport); }
public async void BtnExport()
{
try
{
#region
Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
sfd.Filter = ".xlsx文件(*.xlsx)|*.xlsx";
sfd.FileName = "库存数据" + DateTime.Now.ToString("yyyyMMddhhmmss");
sfd.OverwritePrompt = true;
if (sfd.ShowDialog() != true)
{
return;
}
string path = sfd.FileName;
#endregion
#region
var body = new GetMatInventoryDetailRequest()
{
MatName = MatName,
MatSN = MatSN,
MatBatch = MatBatch,
MatCode = MatCode,
StoreCode = StoreCode,
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
PageNumber = CurrentPage,
PageSize = 10,
};
await ApiHelp.PostDownloadFileAsync(path, System.Net.Http.HttpMethod.Post, LocalFile.Config.ApiIpHost + "matInventoryDetail/exportMatInventoryDetail", body);
Growl.Success("导出成功!");
#endregion
}
catch (Exception ex)
{
Growl.Error("导出失败:" + ex.Message);
}
}
#endregion
#region PageOperation
private int currentPage;
public int CurrentPage
{
get { return currentPage; }
set
{
SetProperty(ref currentPage, value);
BtnSearch(false);
}
}
private int maxPage;
public int MaxPage
{
get { return maxPage; }
set { SetProperty(ref maxPage, value); }
}
//总数量
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set { SetProperty(ref totalCount, value); }
}
public ICommand BtnFirstPageCommand { get => new DelegateCommand(BtnFirstPage); }
public void BtnFirstPage()
{
CurrentPage = 1;
}
public ICommand BtnPrePageCommand { get => new DelegateCommand(BtnPrePage); }
public void BtnPrePage()
{
if (CurrentPage > 1)
{
CurrentPage--;
}
}
public ICommand BtnNextPageCommand { get => new DelegateCommand(BtnNextPage); }
public void BtnNextPage()
{
if (CurrentPage < MaxPage)
{
CurrentPage++;
}
}
public ICommand BtnLastPageCommand { get => new DelegateCommand(BtnLastPage); }
public void BtnLastPage()
{
if (CurrentPage != MaxPage)
{
CurrentPage = MaxPage;
}
}
#endregion
}
}

View File

@ -0,0 +1,173 @@
using LiveCharts;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace .ViewModel
{
public class OutputStatChartViewModel : BindableBase
{
public OutputStatChartViewModel()
{
Values1.CollectionChanged += Values_CollectionChanged;
Values2.CollectionChanged += Values_CollectionChanged;
}
void Values_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
IsZero = (Values1[0] + Values2[0]) == 0;
}
//本地保存路径
public static readonly string DailyStatisticsPath = System.IO.Path.Combine(LocalFile.DataDir, "outputStat");
//文件锁
static object lockObject = new object();
#region
public ChartValues<int> Values1 { get; set; } = new ChartValues<int>() { 10 };
public ChartValues<int> Values2 { get; set; } = new ChartValues<int>() { 2 };
public Func<ChartPoint, string> PointLabel { get; set; } = value => $"{value.Y}";
#endregion
private string Title_ = "当日生产统计";
/// <summary>
/// 标题
/// </summary>
public string Title { get => Title_; set { SetProperty(ref Title_, value); } }
private bool IsZero_ = true;
/// <summary>
/// 是否为0
/// </summary>
public bool IsZero { get => IsZero_; set { SetProperty(ref IsZero_, value); } }
private DateTime? StartTime_ = null;
/// <summary>
/// 开始时间
/// </summary>
public DateTime? StartTime
{
get => StartTime_;
set
{
StartTime_ = value;
Title = !value.HasValue ? "当日生产统计" : value.Value == DateTime.Now.Date ? "当日生产统计" : $"生产统计({value.Value.ToString(@"yyyy/MM/dd")})";
}
}
public void AddOkNg(int okNum, int ngNum)
{
if (okNum < 1 && ngNum < 1)
return;
if (StartTime == null)
return;
//重新计算
if (StartTime.Value.Date != DateTime.Now.Date)
Reset();
if (okNum > 0)
Values1[0] = Values1[0] + okNum;
if (ngNum > 0)
Values2[0] = Values2[0] + ngNum;
SaveData();
}
public void AddOk(int num = 1)
{
if (num < 1)
return;
if (StartTime == null)
return;
//重新计算
if (StartTime.Value.Date != DateTime.Now.Date)
Reset();
Values1[0] = Values1[0] + num;
SaveData();
}
public void AddNg(int num = 1)
{
if (num < 1)
return;
if (StartTime == null)
return;
//重新计算
if (StartTime.Value.Date != DateTime.Now.Date)
Reset();
Values2[0] = Values2[0] + num;
SaveData();
}
public void UpdataData()
{
try
{
if (!File.Exists(DailyStatisticsPath))
{
Values1[0] = 0;
Values2[0] = 0;
StartTime = DateTime.Now.Date;
}
else
{
JObject? jo;
lock (lockObject)
jo = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(DailyStatisticsPath, Encoding.UTF8));
if (jo == null)
{
Values1[0] = 0;
Values2[0] = 0;
StartTime = DateTime.Now.Date;
}
else
{
Values1[0] = jo.Value<int>("ok");
Values2[0] = jo.Value<int>("ng");
StartTime = jo.Value<DateTime>("dt");
}
}
}
catch (Exception)
{
}
}
public void SaveData()
{
try
{
var data = new { ok = Values1[0], ng = Values2[0], dt = StartTime };
lock (lockObject)
File.WriteAllText(DailyStatisticsPath, JsonConvert.SerializeObject(data), Encoding.UTF8);
}
catch (Exception)
{
}
}
public void Reset()
{
Values1[0] = 0;
Values2[0] = 0;
StartTime = DateTime.Now.Date;
}
}
}

View File

@ -0,0 +1,126 @@
using HandyControl.Controls;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WCS.Model;
namespace .ViewModel
{
//https://dandelioncloud.cn/article/details/1472765022102446082
public class RoleEditTreeViewModel : BindableBase, ITreeNode<RoleEditTreeViewModel>
{
private bool IsSelect_;
/// <summary>
/// 是否选择
/// </summary>
public bool IsSelect { get => IsSelect_; set { SetProperty(ref IsSelect_, value); Linkage(value); } }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 主键Id
/// </summary>
public object Id { get; set; }
/// <summary>
/// 父Id
/// </summary>
public object Pid { get; set; }
/// <summary>
/// 父级
/// </summary>
public RoleEditTreeViewModel Parent { get; set; }
/// <summary>
/// 子级
/// </summary>
public List<RoleEditTreeViewModel> Children { get; set; }
/// <summary>
/// 联动
/// </summary>
public void Linkage(bool newbool)
{
//父级增加联动
if (newbool && Parent != null)
Parent.IsSelect = true;
//子级联动
if (!newbool && Children != null)
foreach (var item in Children)
item.IsSelect = false;
}
/// <summary>
/// 得到数据
/// </summary>
/// <param name="select">选中的值</param>
/// <returns></returns>
public static List<RoleEditTreeViewModel> GetTreeViewModel(List<int> select)
{
//值,名称,父级,子级
List<Tuple<int, string, int?, List<int>>> quan = new List<Tuple<int, string, int?, List<int>>>();
List<RoleEditTreeViewModel> vmodel = new List<RoleEditTreeViewModel>();
//1解析枚举
{
Type type = typeof(AuthEnum);
var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public) ?? new FieldInfo[] { };
foreach (var field in fields)
{
var attr = field.GetCustomAttribute<EnumTreeAttribute>(false);
var attr1 = field.GetCustomAttribute<DescriptionAttribute>(false);
var v0 = Convert.ToInt32(field.GetRawConstantValue());
var v1 = attr1 == null ? field.Name : attr1.Description;
var v2 = (int?)attr?.Parent;
var v3 = attr?.Childs?.Select(o => (int)o)?.ToList();
quan.Add(new Tuple<int, string, int?, List<int>>(v0, v1, v2, (v3 ?? new List<int>())));
}
}
//2翻译数据
{
vmodel.AddRange(quan.Select(o => new RoleEditTreeViewModel()
{
Id = o.Item1,
Name = o.Item2,
Pid = 0,
IsSelect = select?.Contains(o.Item1) ?? false,
}));
//父子
foreach (var item in vmodel)
{
var f = quan.FirstOrDefault(o => o.Item1 == (int)item.Id)?.Item3;
if (f.HasValue)
{
item.Parent = vmodel.FirstOrDefault(o => (int)o.Id == f.Value);
item.Pid = item.Parent.Id;
}
var ff = quan.FirstOrDefault(o => o.Item1 == (int)item.Id)?.Item4;
if (ff != null && ff.Any())
{
foreach (var item2 in ff)
{
vmodel.FirstOrDefault(o => (int)o.Id == item2).Parent = item;
vmodel.FirstOrDefault(o => (int)o.Id == item2).Pid = item.Id;
}
}
}
}
//3数据转为树对象
vmodel = vmodel.ToTree();
return vmodel;
}
}
}

View File

@ -0,0 +1,147 @@
using HandyControl.Controls;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using SqlSugar;
using WCS.Model.ApiModel;
using HandyControl.Tools.Extension;
using .Views.Controls;
using WCS.Model.ApiModel.User;
using .Api;
using WCS.Model;
namespace .ViewModel
{
public class RoleViewModel : BindableBase
{
private List<RoleModel> dataList = new List<RoleModel>();
/// <summary>
/// 列表数据
/// </summary>
public List<RoleModel> DataList { get => dataList; set { SetProperty(ref dataList, value); } }
#region
private string info1;
public string Info1 { get => info1; set { SetProperty(ref info1, value); } }
#endregion
public ICommand UpdateListCommand { get => new DelegateCommand(UpdateList); }
/// <summary>
/// 更新信息
/// </summary>
public void UpdateList()
{
var dia = Dialog.Show(new TextDialog());
try
{
var body = new GetUsersRequest()
{
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
Info = Info1,
};
var Result = ApiHelp.GetDataFromHttp<ResponseBase<List<RoleModel>>>(LocalFile.Config.ApiIpHost + "user/getRoles", body, "POST");
if (Result != null && Result.Data != null)
{
DataList = Result.Data;
}
}
catch (Exception ex)
{
Growl.Error("加载数据失败:" + ex.Message);
}
finally
{
dia.Close();
}
}
public ICommand SeeCommand { get => new DelegateCommand<RoleModel>(See); }
public void See(RoleModel obj)
{
RoleEditView.Show(obj, CrudEnum.Read);
}
public ICommand AddCommand { get => new DelegateCommand(Add); }
public void Add()
{
var isUp = RoleEditView.Show(new RoleModel(), CrudEnum.Create);
if (isUp)
{
UpdateList();
Growl.Success("创建成功");
}
}
public ICommand UpdateCommand { get => new DelegateCommand<RoleModel>(Update); }
public void Update(RoleModel obj)
{
var isUp = RoleEditView.Show(obj, CrudEnum.Update);
if (isUp)
{
UpdateList();
Growl.Success("更新成功");
}
}
public ICommand DelCommand { get => new DelegateCommand<RoleModel>(Del); }
public void Del(RoleModel obj)
{
Growl.Ask($"是否删除角色[{obj.Name}]!", isConfirmed =>
{
if (isConfirmed)
{
//try
//{
// //var isContains = AuthDb1.db.Queryable<UserModel>().Select(o => o.RoleIds).ToList().SelectMany(o => o).Contains(obj.Id);
// //if (isContains)
// //{
// // Growl.Info($"此角色被用户使用中,无法删除");
// // return true;
// //}
// //AuthDb1.db.Deleteable(obj).ExecuteCommand();
//}
//catch (Exception ex)
//{
// Growl.Error($"删除失败:{ex.ToString()}");
// return true;
//}
try
{
var body = new AddRoleRequest<RoleModel>()
{
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
Role = obj,
AddOrUpdate = AddOrUpdate.Delete,
};
var Result = ApiHelp.GetDataFromHttp<ResponseCommon<object>>(LocalFile.Config.ApiIpHost + "user/addRole", body, "POST");
if (Result.Code == 200)
{
Growl.Success("删除成功");
UpdateList();
return true;
}
else
{
Growl.Error(Result?.Message);
return true;
}
}
catch (Exception ex)
{
Growl.Error($"删除失败:{ex.ToString()}");
return true;
}
}
else
return true;
});
}
}
}

View File

@ -0,0 +1,219 @@
using HandyControl.Controls;
using Microsoft.Win32;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;
using System.Windows.Input;
namespace .ViewModel
{
public class SetViewModel : BindableBase
{
private List<int> SaveLoginCountData_ = new List<int> { 3, 5, 7, 10 };
//记忆最大数量下拉框
public List<int> SaveLoginCountData { get => SaveLoginCountData_; set { SetProperty(ref SaveLoginCountData_, value); } }
private Dictionary<int, string> LogTimeData_ = new Dictionary<int, string>()
{
{ 30,"一月"},{ 91,"三月"},{ 182,"半年"},{ 365,"一年"},{ 1095,"三年"},{ -1,"永久"},
};
//日志缓存时间下拉框
public Dictionary<int, string> LogTimeData { get => LogTimeData_; set { SetProperty(ref LogTimeData_, value); } }
#region
private List<string> scannerComList;
public List<string> ScannerComList
{
get { return scannerComList; }
set
{
SetProperty(ref scannerComList, value);
}
}
private string selectedScannerCom;
public string SelectedScannerCom
{
get { return selectedScannerCom; }
set
{
SetProperty(ref selectedScannerCom, value);
}
}
private List<string> comList;
public List<string> COMList
{
get { return comList; }
set
{
SetProperty(ref comList, value);
}
}
private string selectedCOM;
public string SelectedCOM
{
get { return selectedCOM; }
set
{
SetProperty(ref selectedCOM, value);
}
}
private bool Powerboot_;
public bool Powerboot { get => Powerboot_; set { SetProperty(ref Powerboot_, value); } }
private bool StartupFull_;
public bool StartupFull { get => StartupFull_; set { SetProperty(ref StartupFull_, value); } }
private bool IsSaveLogin_;
public bool IsSaveLogin { get => IsSaveLogin_; set { SetProperty(ref IsSaveLogin_, value); } }
private int SaveLoginCount_;
public int SaveLoginCount { get => SaveLoginCount_; set { SetProperty(ref SaveLoginCount_, value); } }
private int SaveLogDay_;
public int SaveLogDay { get => SaveLogDay_; set { SetProperty(ref SaveLogDay_, value); } }
#endregion
/// <summary>
/// 刷新界面
/// </summary>
public void Update()
{
#region
try
{
LocalFile.UpdateConfig();
ScannerComList = LocalFile.Config.ScannerComList;
Powerboot = LocalFile.Config.Sys.Powerboot;
StartupFull = LocalFile.Config.Sys.StartupFull;
IsSaveLogin = LocalFile.Config.Sys.IsSaveLogin;
SaveLoginCount = LocalFile.Config.Sys.SaveLoginCount;
SaveLogDay = LocalFile.Config.Sys.SaveLogDay;
}
catch (Exception ex)
{
Growl.Info($"获取配置失败。{ex.Message}");
}
#endregion
#region
RefreshCOMList();
#endregion
}
public ICommand SaveCommand { get => new DelegateCommand(Save); }
/// <summary>
/// 保存
/// </summary>
public void Save()
{
try
{
LocalFile.Config.Sys.Powerboot = Powerboot;
LocalFile.Config.Sys.StartupFull = StartupFull;
LocalFile.Config.Sys.IsSaveLogin = IsSaveLogin;
LocalFile.Config.Sys.SaveLoginCount = SaveLoginCount;
LocalFile.Config.Sys.SaveLogDay = SaveLogDay;
LocalFile.Config.ScannerComList = ScannerComList;
LocalFile.SaveConfig();
Growl.Success($"保存成功。");
RunPowerboot(Powerboot);
}
catch (Exception ex)
{
LocalFile.UpdateConfig();
Growl.Error($"保存失败。{ex.Message}");
}
}
private void RunPowerboot(bool isPowerboot)
{
try
{
if (isPowerboot)
{
RegistryKey rgkRun = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (rgkRun == null)
rgkRun = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
rgkRun.SetValue(Path.GetFileNameWithoutExtension(LocalFile.AppName), "\"" + Path.Combine(LocalFile.AppDir, LocalFile.AppName) + "\"");
}
else
{
RegistryKey rgkRun = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (rgkRun == null)
rgkRun = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
rgkRun.DeleteValue(Path.GetFileNameWithoutExtension(LocalFile.AppName), false);
}
}
catch (Exception ex)
{
Logs.Write(ex);
}
}
public ICommand AddCOMCommand { get => new DelegateCommand(AddCOM); }
public void AddCOM()
{
//是否已选择COM号
if (SelectedCOM == null)
{
Growl.Warning("请选择串口!");
return;
}
//列表中是否存在
var isExsist = ScannerComList.Where(t => t == SelectedCOM).Any();
if (isExsist)
{
Growl.Warning($"已存在扫码枪{SelectedCOM}");
return;
}
//添加
ScannerComList.Add(SelectedCOM);
ScannerComList = ScannerComList.ToList();
}
public ICommand DeleteCOMCommand { get => new DelegateCommand(DeleteCOM); }
public void DeleteCOM()
{
//是否已选择COM号
if (SelectedScannerCom == null)
{
Growl.Warning("请在下方选择串口!");
return;
}
ScannerComList.RemoveAll(t => t == SelectedScannerCom);
ScannerComList = ScannerComList.ToList();
}
public ICommand RefreshCOMListCommand { get => new DelegateCommand(RefreshCOMList); }
public void RefreshCOMList()
{
try
{
COMList = SerialPort.GetPortNames().ToList();
}
catch
{
}
}
}
}

View File

@ -0,0 +1,170 @@
using Ping9719.WpfEx.Mvvm;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using WCS.Model;
using WCS.Model.ApiModel.Home;
using WCS.Model.ApiModel.StoreInfo;
using .Tool;
namespace .ViewModel
{
public class ShelfInfoAddOrUpdateViewModel : BindableBase
{
#region Property
public ShelfInfoAddOrUpdateViewModel()
{
ShelfTypeItems = GetBaseData.GetShelfType();
if (ShelfTypeItems != null && ShelfTypeItems.Count > 0)
SelectedShelfTypeItem = ShelfTypeItems.First();
}
public void SetValues(ShelfInfoModel shelfInfoModel)
{
if (shelfInfoModel != null)
{
ShelfId = shelfInfoModel.Id;
SelectedShelfTypeItem = shelfTypeItems.First(t => t.Id == shelfInfoModel.ShelfTypeId);
ShelfCode = shelfInfoModel.ShelfCode;
RowCounts = shelfInfoModel.Rowcounts;
ColumnCounts = shelfInfoModel.Columncounts;
LightId = shelfInfoModel.LightId;
ClientIp = shelfInfoModel.ClientIp;
GroupName = shelfInfoModel.GroupName;
IsBind = shelfInfoModel.IsBind;
BindShelfCode = shelfInfoModel.BindShelfCode;
}
}
public ShelfInfoModel GetValues()
{
return new ShelfInfoModel()
{
Id = ShelfId,
ShelfTypeId = SelectedShelfTypeItem.Id,
ShelfTypeName = SelectedShelfTypeItem.ShelfTypeName,
ShelfCode = ShelfCode,
Rowcounts = RowCounts,
Columncounts = ColumnCounts,
LightId = LightId,
ClientIp = ClientIp,
GroupName = GroupName,
IsBind = IsBind,
BindShelfCode = BindShelfCode,
};
}
private int shelfId;
public int ShelfId
{
get { return shelfId; }
set
{
SetProperty(ref shelfId, value);
}
}
private List<ShelfTypeModel> shelfTypeItems;
public List<ShelfTypeModel> ShelfTypeItems
{
get { return shelfTypeItems; }
set
{
SetProperty(ref shelfTypeItems, value);
}
}
private ShelfTypeModel selectedShelfTypeItem;
public ShelfTypeModel SelectedShelfTypeItem
{
get { return selectedShelfTypeItem; }
set
{
SetProperty(ref selectedShelfTypeItem, value);
}
}
private string shelfCode;
public string ShelfCode
{
get { return shelfCode; }
set
{
SetProperty(ref shelfCode, value);
}
}
private int rowCounts;
public int RowCounts
{
get { return rowCounts; }
set
{
SetProperty(ref rowCounts, value);
}
}
private int columnCounts;
public int ColumnCounts
{
get { return columnCounts; }
set
{
SetProperty(ref columnCounts, value);
}
}
private int lightId;
public int LightId
{
get { return lightId; }
set
{
SetProperty(ref lightId, value);
}
}
private string clientIp;
public string ClientIp
{
get { return clientIp; }
set
{
SetProperty(ref clientIp, value);
}
}
private string groupName;
public string GroupName
{
get { return groupName; }
set
{
SetProperty(ref groupName, value);
}
}
private bool isBind;
public bool IsBind
{
get { return isBind; }
set
{
SetProperty(ref isBind, value);
}
}
private string bindShelfCode;
public string BindShelfCode
{
get { return bindShelfCode; }
set
{
SetProperty(ref bindShelfCode, value);
}
}
#endregion
}
}

View File

@ -0,0 +1,287 @@
using HandyControl.Controls;
using MiniExcelLibs;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using .Views.Controls;
using .Api;
using WCS.Model;
using WCS.Model.ApiModel.Home;
using WCS.Model.ApiModel.StoreInfo;
using WCS.BLL.DbModels;
using WCS.Model.ApiModel.MatBaseInfo;
using WCS.Model.ApiModel.User;
using WCS.Model.ApiModel;
using Newtonsoft.Json.Bson;
namespace .ViewModel
{
public class ShelfInfoViewModel : BindableBase
{
public ShelfInfoViewModel()
{
}
#region Property
private List<ShelfInfoModel> dataGridItemSource;
public List<ShelfInfoModel> DataGridItemSource
{
get { return dataGridItemSource; }
set
{
SetProperty(ref dataGridItemSource, value);
}
}
private ShelfInfoModel selectedataGridItem;
public ShelfInfoModel SelectedataGridItem
{
get { return selectedataGridItem; }
set
{
SetProperty(ref selectedataGridItem, value);
}
}
/// <summary>
/// 物料批次
/// </summary>
private string shelfCode;
public string ShelfCode
{
get { return shelfCode; }
set
{
SetProperty(ref shelfCode, value);
}
}
private List<ShelfTypeModel> shelfTypeItems;
public List<ShelfTypeModel> ShelfTypeItems
{
get { return shelfTypeItems; }
set
{
SetProperty(ref shelfTypeItems, value);
}
}
public void InitShelfTypeItems()
{
//调用接口更新!
Task.Run(() =>
{
var body = new RequestBase()
{
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
};
var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<ShelfTypeModel>>(LocalFile.Config.ApiIpHost + "home/getShelfTypes", body, "POST");
if (Result != null && Result.Data != null && Result.Data.Lists.Count() > 0)
{
ShelfTypeItems = Result.Data.Lists;
}
});
}
private ShelfTypeModel selectedShelfTypeItem;
public ShelfTypeModel SelectedShelfTypeItem
{
get { return selectedShelfTypeItem; }
set
{
SetProperty(ref selectedShelfTypeItem, value);
}
}
#endregion
#region Command
public ICommand BtnResetCommand { get => new DelegateCommand(BtnReset); }
public void BtnReset()
{
SelectedShelfTypeItem = null;
ShelfCode = string.Empty;
}
public ICommand BtnSearchCommand { get => new DelegateCommand(BtnSearchReset); }
public void BtnSearchReset()
{
BtnSearch(true);
}
public void BtnSearch(bool IsPageReset = true)
{
if (CurrentPage == 0 || IsPageReset)
{
CurrentPage = 1;
return;
}
#region
var dia = Dialog.Show(new TextDialog());
try
{
var body = new GetShelvesRequest()
{
ShelfTypeId = SelectedShelfTypeItem == null ? 0 : SelectedShelfTypeItem.Id,
ShelfCode = ShelfCode,
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
PageNumber = CurrentPage,
PageSize = 10,
};
var Result = ApiHelp.GetDataFromHttp<PageQueryResponse<ShelfInfoModel>>(LocalFile.Config.ApiIpHost + "storeInfo/getShelves", body, "POST");
if (Result != null && Result.Data != null && Result.Data.Lists != null)
{
DataGridItemSource = Result.Data.Lists;
MaxPage = Result.Data.MaxPage;
TotalCount = Result.Data.TotalCount;
}
}
catch (Exception ex)
{
Growl.Error("加载数据失败:" + ex.Message);
}
finally
{
dia.Close();
}
#endregion
}
/// <summary>
/// 物料新增操作
/// </summary>
public ICommand BtnAddCommand { get => new DelegateCommand(BtnAdd); }
public async void BtnAdd()
{
var addView = new ShelfInfoAddOrUpdateView("新增货架");
addView.ShowDialog();
if (addView.DialogResult == true)
{
//添加或修改成功后重新查询
CurrentPage = 1;
}
}
public ICommand BtnEditCommand { get => new DelegateCommand(BtnEdit); }
public async void BtnEdit()
{
//查询勾选的第一个数据
var shelfInfo = DataGridItemSource?.Where(t => t.IsSelected == true).FirstOrDefault();
if (shelfInfo == null)
{
Growl.Warning("请选择需要修改的数据!");
}
else
{
var addView = new ShelfInfoAddOrUpdateView("修改货架", shelfInfo);
addView.ShowDialog();
if (addView.DialogResult == true)
{
CurrentPage = 1;
}
}
}
public ICommand BtnDeleteCommand { get => new DelegateCommand(BtnDelete); }
public void BtnDelete()
{
//查询勾选的第一个数据
var shelfInfo = DataGridItemSource?.Where(t => t.IsSelected == true).FirstOrDefault();
if (shelfInfo == null)
{
Growl.Warning("请选择需要删除的数据!");
}
else
{
var body = new AddShelfInfoRequest<ShelfInfoModel>()
{
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
ShelfInfo = shelfInfo,
AddOrUpdate = AddOrUpdate.Delete
};
var Result = ApiHelp.GetDataFromHttp<ResponseBase<object>>(LocalFile.Config.ApiIpHost + "storeInfo/addOrUpdateShelfInfo", body, "POST");
if (Result != null && Result.Code == 200)
{
Growl.Success("删除成功!");
CurrentPage = 1;
}
else
{
Growl.Error($"{Result?.Message?.ToString()}");
}
}
}
#endregion
#region PageOperation
private int currentPage;
public int CurrentPage
{
get { return currentPage; }
set
{
SetProperty(ref currentPage, value);
BtnSearch(false);
}
}
private int maxPage;
public int MaxPage
{
get { return maxPage; }
set { SetProperty(ref maxPage, value); }
}
//总数量
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set { SetProperty(ref totalCount, value); }
}
public ICommand BtnFirstPageCommand { get => new DelegateCommand(BtnFirstPage); }
public void BtnFirstPage()
{
CurrentPage = 1;
}
public ICommand BtnPrePageCommand { get => new DelegateCommand(BtnPrePage); }
public void BtnPrePage()
{
if (CurrentPage > 1)
{
CurrentPage--;
}
}
public ICommand BtnNextPageCommand { get => new DelegateCommand(BtnNextPage); }
public void BtnNextPage()
{
if (CurrentPage < MaxPage)
{
CurrentPage++;
}
}
public ICommand BtnLastPageCommand { get => new DelegateCommand(BtnLastPage); }
public void BtnLastPage()
{
if (CurrentPage != MaxPage)
{
CurrentPage = MaxPage;
}
}
#endregion
}
}

View File

@ -0,0 +1,44 @@
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WCS.Model.ApiModel;
namespace
{
public class UserInfoViewModel : BindableBase
{
private bool isLogin = false;
/// <summary>
/// 是否登录
/// </summary>
public bool IsLogin { get => isLogin; set { SetProperty(ref isLogin, value); } }
private string LoginName_;
/// <summary>
/// 登录名
/// </summary>
public string LoginName { get => LoginName_; set { SetProperty(ref LoginName_, value); } }
private object Auth_;
/// <summary>
/// 权限变化通知
/// </summary>
public object Auth { get => Auth_; set { SetProperty(ref Auth_, value); } }
private UserModel User_;
/// <summary>
/// 用户
/// </summary>
public UserModel User { get => User_; set { SetProperty(ref User_, value); LoginName = value?.LoginName ?? null; } }
private List<RoleModel> Roles_;
/// <summary>
/// 角色
/// </summary>
public List<RoleModel> Roles { get => Roles_; set { SetProperty(ref Roles_, value); Auth = new object(); } }
}
}

View File

@ -0,0 +1,137 @@
using HandyControl.Controls;
using MiniExcelLibs;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using SqlSugar;
using HandyControl.Data;
using System.Windows;
using Newtonsoft.Json.Linq;
using .Views.Controls;
using WCS.Model.ApiModel.User;
using .Api;
using WCS.Model;
using WCS.Model.ApiModel;
namespace .ViewModel
{
public class UserViewModel : BindableBase
{
private List<UserModel> dataList = new List<UserModel>();
/// <summary>
/// 列表数据
/// </summary>
public List<UserModel> DataList { get => dataList; set { SetProperty(ref dataList, value); } }
#region
private string info1;
public string Info1 { get => info1; set { SetProperty(ref info1, value); } }
#endregion
public ICommand UpdateListCommand { get => new DelegateCommand(UpdateList); }
/// <summary>
/// 更新信息
/// </summary>
public void UpdateList()
{
var dia = Dialog.Show(new TextDialog());
try
{
var body = new GetUsersRequest()
{
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
Info = Info1,
};
var Result = ApiHelp.GetDataFromHttp<ResponseBase<List<UserModel>>>(LocalFile.Config.ApiIpHost + "user/getUsers", body, "POST");
if (Result != null && Result.Data != null)
{
DataList = Result.Data;
}
}
catch (Exception ex)
{
Growl.Error("加载数据失败:" + ex.Message);
}
finally
{
dia.Close();
}
}
public ICommand SeeCommand { get => new DelegateCommand<UserModel>(See); }
public void See(UserModel obj)
{
UserEditView.Show(obj, CrudEnum.Read);
}
public ICommand AddCommand { get => new DelegateCommand(Add); }
public void Add()
{
var isUp = UserEditView.Show(new UserModel(), CrudEnum.Create);
if (isUp)
{
UpdateList();
Growl.Success("创建成功");
}
}
public ICommand UpdateCommand { get => new DelegateCommand<UserModel>(Update); }
public void Update(UserModel obj)
{
var isUp = UserEditView.Show(obj, CrudEnum.Update);
if (isUp)
{
UpdateList();
Growl.Success("更新成功");
}
}
public ICommand DelCommand { get => new DelegateCommand<UserModel>(Del); }
public void Del(UserModel obj)
{
Growl.Ask($"是否删除用户[{obj.LoginName}]!", isConfirmed =>
{
if (isConfirmed)
{
try
{
var body = new AddUserRequest<UserModel>()
{
UserName = LocalStatic.CurrentUser,
DeviceType = LocalFile.Config.DeviceType,
User = obj,
AddOrUpdate = AddOrUpdate.Delete
};
var Result = ApiHelp.GetDataFromHttp<ResponseBase<UserModel>>(LocalFile.Config.ApiIpHost + "user/addUser", body, "POST");
if (Result != null && Result.Code == 200)
{
UpdateList();
Growl.Success("删除成功");
}
else
{
Growl.Error($"删除失败:{Result.Message.ToString()}");
}
}
catch (Exception ex)
{
Growl.Error($"删除失败:{ex.ToString()}");
return true;
}
}
return true;
});
}
}
}