using Aucma.Core.Scanner;
using Aucma.Scada.HikRobot;
using Aucma.Scada.Model.domain;
using HighWayIot.Common;
using HighWayIot.Config;
using HighWayIot.Log4net;
using HighWayIot.Repository.service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using static Aucma.Scada.Business.InStoreTaskHandle;
namespace Aucma.Scada.Business
{
///
/// 入库业务逻辑
///
public sealed class InStoreBusiness
{
#region 单例实现
private static readonly Lazy lazy = new Lazy(() => new InStoreBusiness());
public static InStoreBusiness Instance
{
get
{
return lazy.Value;
}
}
#endregion
#region 对象引用
private LogHelper logHelper = LogHelper.Instance;
private AppConfig appConfig = AppConfig.Instance;
private RegisterServices registerServices = RegisterServices.Instance;
private InStoreTaskHandle taskHandle = InStoreTaskHandle.Instance;
#endregion
#region 接口引用
///
/// 货道信息
///
private IBaseSpaceInfoService _spaceInfoService;
///
/// 实时任务
///
private IRealTaskInfoService _taskInfoService;
private IBaseSpaceDetailService _baseSpaceDetailService;
private IBaseBomInfoService _baseBomInfoService;
private IRecordInStoreService _recordInStore;
private IPrintBarCodeServices _printBarCodeServices;
// 过点数据表
private IMaterialCompletionServices _iMaterialCompletionServices;
private IProductPlanInfoService _productPlanInfoServices;
#endregion
#region 委托事件
///
/// 初始化入库任务
///
///
public delegate void RefreshInStoreTask(RealTaskInfo taskInfos, bool isFinsih = false);
public event RefreshInStoreTask RefreshInStoreTaskEvent;
///
/// 扫码信息刷新
///
///
///
///
///
public delegate void RefreshScanMateriaCode(string materialCode, string materialName, string spaceName, string materialType);
public event RefreshScanMateriaCode RefreshScanMateriaCodeEvent;
///
/// 日志信息刷新
///
///
public delegate void RefreshLogMessage(string message);
public event RefreshLogMessage RefreshLogMessageEvent;
#endregion
#region 变量定义
private int shellNoReadFlag = 0;
private int linerNoReadFlag = 0;
#endregion
private InStoreBusiness()
{
_spaceInfoService = registerServices.GetService();
_taskInfoService = registerServices.GetService();
_baseSpaceDetailService = registerServices.GetService();
_baseBomInfoService = registerServices.GetService();
_recordInStore = registerServices.GetService();
_printBarCodeServices = registerServices.GetService();
_productPlanInfoServices = registerServices.GetService();
_iMaterialCompletionServices = registerServices.GetService();
// taskHandle.InStoreFinsihEvent += InStoreFinish;
taskHandle.InStoreAnswerEvent += InStoreAnswer;
MvCodeHelper.MessageNoReadEvent += MessageNoRead;
MvCodeHelper.RefreshMaterialCodeStrEvent += InStore;
MvCodeHelper.RefreshLogMessageEvent += PrintLogInfoMessage;
StartPassDown();
//Task.Run(() =>
//{
// Thread.Sleep(5000);
// InStore("B24031383025017990002", appConfig.shellHikRobotIp);
//});
}
///
/// 扫码器通知有货物但是没扫上条码
///
private void MessageNoRead(string storeCode)
{
if (storeCode == appConfig.shellStoreCode)
{
shellNoReadFlag = 1;
// 刷新界面提示信息
PrintLogInfoMessage("箱壳扫码器未扫上条码");
}
else
{
linerNoReadFlag = 1;
PrintLogInfoMessage("内胆扫码器未扫上条码");
}
}
///
/// 入库
///
///
///
private void InStore(string materialCode, string scannerIp)
{
try
{
string storeCode = string.Empty;
if (appConfig.shellHikRobotIp.Equals(scannerIp))
{
storeCode = appConfig.shellStoreCode;
}
else
{
storeCode = appConfig.linerStoreCode;
}
if (materialCode == "1111111111111111111111")
{
PrintLogInfoMessage("空板经过:" + storeCode);
}
else
{
PrintLogInfoMessage($"扫码成功,物料码:{materialCode}");
}
string materialType = SubStringMaterialCode(materialCode);
#region Delete By wenjy 2023-10-30 11:41:00 取消通过数据库获取货道数量、在途量,改为通过PLC获取货道信息
//var spaceInfo = _spaceInfoService.InStoreGetSpaceInfoByMaterialType(storeCode, materialType);
#endregion
var spaceInfo = GetSpaceInfoByMaterialType(storeCode, materialType);
if (spaceInfo != null)
{
PrintLogInfoMessage($"匹配货道:{spaceInfo.spaceName}");
if (materialType == "1111111111")
{ // 空板只有在空白货道的时候占据货道,否则只入不占据货道
if (string.IsNullOrEmpty(spaceInfo.materialType))
{
spaceInfo.materialType = materialType;
}
}
else
{
spaceInfo.materialType = materialType;
spaceInfo.typeNameA = GetMaterialName(materialType);
}
RefreshScanMateriaCodeEvent?.Invoke(materialCode, GetMaterialName(materialType), spaceInfo.spaceName, storeCode); //刷新界面扫码信息
var result = CreateInStoreTask(spaceInfo, materialCode); //创建入库任务
if (result)
{
#region 2023-12-15 更新过点数据,插入记录到MATERIAL_COMPLETION表
//PrintBarCode print =_printBarCodeServices.query(materialCode);
//string planCode = _productPlanInfoServices.GetPlanCode(print.OrderCode, appConfig.stationCode);
//MaterialCompletion completion = new MaterialCompletion();
//completion.OrderCode = print.OrderCode;
//completion.MaterialBarcode = materialCode;
//completion.MaterialCode = print.MaterialCode;
//completion.MaterialName = print.MaterialName;
//completion.StationName = appConfig.stationCode;
//completion.CompleteDate = DateTime.Now;
//completion.planCode = planCode;
//_iMaterialCompletionServices.Add(completion);
#endregion
//spaceInfo.onRouteAmount += 1; //通过PLC获取货道信息(在库、在途数量)时不需要修改在途数量
Console.WriteLine(JsonChange.Instance.ModeToJson(spaceInfo));
_spaceInfoService.UpdateSpaceInfo(spaceInfo);
}
}
else
{
//报警停线
PrintLogInfoMessage($"物料码:{materialCode};未匹配到可用货道");
}
}
catch (Exception ex)
{
PrintLogErrorMessage("入库业务异常", ex);
}
}
///
/// 创建入库任务
///
///
private bool CreateInStoreTask(BaseSpaceInfo spaceInfo, string materialCode)
{
bool result = false;
#region 任务赋值
RealTaskInfo realTaskInfo = new RealTaskInfo();
realTaskInfo.taskType = 1;
realTaskInfo.taskCode = System.Guid.NewGuid().ToString("N").Substring(0, 6);
realTaskInfo.storeCode = spaceInfo.storeCode;
realTaskInfo.spaceCode = spaceInfo.spaceCode;
realTaskInfo.materialType = spaceInfo.materialType;
realTaskInfo.materialCode = materialCode;
realTaskInfo.planAmount = 1;
realTaskInfo.taskStatus = 1;
realTaskInfo.createTime = DateTime.Now;
#endregion
result = _taskInfoService.AddTaskInfo(realTaskInfo);
if (result)
{
PrintLogInfoMessage("入库任务创建成功");
RefreshInStoreTaskEvent?.Invoke(realTaskInfo);
result = true;
}
else
{
PrintLogInfoMessage("入库任务创建失败");
}
return result;
}
#region 轮询获取入库任务下发至PLC,等待PLC执行反馈,完成后再次下发
private SemaphoreSlim shellSemaphore = new SemaphoreSlim(0);
private SemaphoreSlim linerSemaphore = new SemaphoreSlim(0);
///
/// 任务下发
///
private void StartPassDown()
{
Task.Run(() =>
{
while (true)
{
PassDownShellTask();
Thread.Sleep(2000);
}
});
Task.Run(() =>
{
while (true)
{
PassDownLinerTask();
Thread.Sleep(2000);
}
});
}
///
/// 依次获取箱壳任务队列进行下发
///
///
///
private void PassDownShellTask()
{
try
{
RealTaskInfo taskInfo = _taskInfoService.GetTaskInfoByStoreCode(appConfig.shellStoreCode, appConfig.instoreTaskType);
if (taskInfo != null)
{
shellNoReadFlag = 1;
int result = taskHandle.SendShellTask_InStore(taskInfo);
if (result == 1)
{
PrintLogInfoMessage($"箱壳入库任务:{taskInfo.taskCode};下发成功,等待PLC执行反馈");
shellSemaphore.Wait(); //一直堵塞直到信号量释放
shellNoReadFlag = 0;
PrintLogInfoMessage($"箱壳入库任务:{taskInfo.taskCode};开始执行");
taskInfo.taskStatus = 2;
_taskInfoService.UpdateTaskInfo(taskInfo);
RefreshInStoreTaskEvent?.Invoke(taskInfo);
}
else if (result == 2)
{
PrintLogInfoMessage("箱壳入库任务下发失败,PLC接收任务未就绪");
}
else
{
PrintLogInfoMessage($"箱壳入库任务:{taskInfo.taskCode};下发失败,请排除PLC连接");
}
}
//else
//{ // 没有任务且没有noRead条件下,读plc判断是否有空板
// if (shellNoReadFlag == 0)
// {
// if (taskHandle.ReadShellAnswer()==1)
// {
// Console.WriteLine("应答字1,当空板处理");
// // 空板入库处理 所有空板默认箱体码1111111111111111111111
// InStore("1111111111111111111111", appConfig.shellHikRobotIp);
// }
// }
//}
}
catch (Exception ex)
{
PrintLogErrorMessage("依次获取箱壳任务队列进行下发逻辑异常", ex);
}
}
///
/// 依次获取内胆任务队列进行下发
///
private void PassDownLinerTask()
{
try
{
lock (string.Empty)
{
RealTaskInfo taskInfo = _taskInfoService.GetTaskInfoByStoreCode(appConfig.linerStoreCode, appConfig.instoreTaskType);
if (taskInfo != null)
{
linerNoReadFlag = 1;
int result = taskHandle.SendLinerTask_InStore(taskInfo);
if (result == 1)
{
PrintLogInfoMessage($"内胆入库任务:{taskInfo.taskCode};下发成功,等待PLC执行反馈");
linerSemaphore.Wait(); //一直堵塞直到信号量释放
linerNoReadFlag = 0;
PrintLogInfoMessage($"内胆入库任务:{taskInfo.taskCode};开始执行");
taskInfo.taskStatus = 2;
_taskInfoService.UpdateTaskInfo(taskInfo);
RefreshInStoreTaskEvent?.Invoke(taskInfo);
}
else if (result == 2)
{
// PrintLogInfoMessage("内胆入库任务下发失败,PLC接收任务未就绪");
}
else
{
PrintLogInfoMessage($"内胆入库任务:{taskInfo.taskCode};下发失败,请排除PLC连接");
}
}
//else
//{
// // 没有任务且没有noRead条件下,读plc判断是否有空板
// if (linerNoReadFlag == 0)
// {
// if (taskHandle.ReadLinerAnswer() == 1)
// {
// // 空板入库处理 所有空板默认箱体码1111111111111111111111
// InStore("1111111111111111111111", appConfig.linerHikRobotIp);
// }
// }
//}
}
}
catch (Exception ex)
{
PrintLogErrorMessage("依次获取内胆任务队列进行下发逻辑异常", ex);
}
}
#endregion
///
/// 入库应答,PLC收到入库任务后进行应答
///
///
///
private void InStoreAnswer(string storeCode, string taskCode)
{
if (storeCode == appConfig.shellStoreCode)
{
PrintLogInfoMessage("箱壳应答成功,自动释放信号量,进行下发新任务");
shellSemaphore.Release();
}
else
{
PrintLogInfoMessage("内胆应答成功,自动释放信号量,进行下发新任务");
linerSemaphore.Release();
}
// 入库完成
InStoreFinish(storeCode, taskCode);
}
///
/// 入库完成
///
///
///
private void InStoreFinish(string storeCode, string taskCode)
{
if (storeCode == appConfig.shellStoreCode)
{
PrintLogInfoMessage($"箱壳任务:{taskCode};执行完成");
InStoreFinishHandle(taskCode, appConfig.shellStoreCode);
}
else
{
PrintLogInfoMessage($"内胆任务:{taskCode};执行完成");
InStoreFinishHandle(taskCode, appConfig.linerStoreCode);
}
}
///
/// 入库完成逻辑处理
///
///
///
///
private void InStoreFinishHandle(string taskCode, string storeCode)
{
try
{
var taskInfo = _taskInfoService.GetTaskInfoByTaskCode(taskCode, storeCode);
if (taskInfo != null)
{
var spaceInfo = _spaceInfoService.GetSpaceInfoBySpaceCode(taskInfo.storeCode, taskInfo.spaceCode);
if (spaceInfo != null)
{
// taskHandle.WritePlc(spaceInfo.storeCode, spaceInfo.spaceCode, true);
// spaceInfo.spaceStock = spaceInfo.spaceStock + 1;
// spaceInfo.onRouteAmount -= 1;
//读取PLC获取货道信息:存放数量、在途数量,
#region Add By wenjy 2023-10-30 13:44:00 通过PLC获取货道信息
// var item = taskHandle.ReadSpaceInfoByPlc(spaceInfo);
// spaceInfo.spaceStock = item.spaceStock;
// spaceInfo.spaceStock = spaceInfo.spaceStock + 1;
// spaceInfo.onRouteAmount = item.onRouteAmount;
// spaceInfo.spaceStatus = item.spaceStatus;
#endregion
// _spaceInfoService.UpdateSpaceInfo(spaceInfo);
#region 添加货道明细
BaseSpaceDetail spaceDetail = new BaseSpaceDetail();
spaceDetail.materialType = taskInfo.materialType;
spaceDetail.materialCode = taskInfo.materialCode;
spaceDetail.materialName = GetMaterialName(taskInfo.materialType);
spaceDetail.storeCode = spaceInfo.storeCode;
spaceDetail.spaceCode = spaceInfo.spaceCode;
spaceDetail.materialAmount = 1;
spaceDetail.createTime = DateTime.Now;
spaceDetail.detailCode = System.Guid.NewGuid().ToString("N").Substring(0, 10);
_baseSpaceDetailService.InsertSpaceDetail(spaceDetail);
#endregion
#region 添加入库记录
RecordInstore recordInstore = new RecordInstore();
recordInstore.storeCode = taskInfo.storeCode;
recordInstore.spaceCode = taskInfo.spaceCode;
recordInstore.materialCode = taskInfo.materialCode;
recordInstore.materialType = taskInfo.materialType;
recordInstore.materialName = GetMaterialName(taskInfo.materialType);
recordInstore.inStoreAmount = 1;
recordInstore.inStoreTime = DateTime.Now;
recordInstore.barcodeCode = taskInfo.materialCode;
_recordInStore.InsertRecordInStore(recordInstore);
#endregion
}
//清除任务信息
_taskInfoService.DeleteTaskInfo(taskCode, storeCode);
}
RefreshInStoreTaskEvent?.Invoke(taskInfo, true);
}
catch (Exception ex)
{
PrintLogErrorMessage("入库完成逻辑处理异常", ex);
}
}
///
/// 截取条码
///
///
///
private string SubStringMaterialCode(string materialCode)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(materialCode))
{
result = materialCode.Substring(7, 10);
}
return result;
}
///
/// 获取已创建的所有入库任务
///
///
public List GetInStoreTask()
{
return _taskInfoService.GetTaskInfosByStoreCode(new string[] { appConfig.shellStoreCode, appConfig.linerStoreCode }, appConfig.instoreTaskType);
}
///
/// 通过BOM获取物料名称
///
///
///
public string GetMaterialName(string materialType)
{
string materialName = string.Empty;
var info = _baseBomInfoService.GetBomInfoByMaterialCode(materialType);
if (info != null)
{
materialName = info.materialName;
}
if (materialType == "1111111111")
{
materialName = "空板";
}
return materialName;
}
///
/// 获取仓库物料库存
///
///
public List GetStock()
{
List infos = _spaceInfoService.GetSpaceInfosByTwoStoreCode(appConfig.shellStoreCode, appConfig.linerStoreCode);
return infos;
}
///
/// 获取仓库物料库存20240223弃用
///
///
public List GetMaterialStock()
{
return _spaceInfoService.GetMaterialStock(appConfig.shellStoreCode, appConfig.linerStoreCode);
}
#region 通过PLC读取货道信息:在库、在途、货道状态
///
/// 通过PLC读取货道信息(在途数量、在库数量、货道状态)
///
///
///
///
private BaseSpaceInfo GetSpaceInfoByMaterialType(string storeCode, string materialType)
{
BaseSpaceInfo result = null;
try
{
List info = _spaceInfoService.GetBaseSpaceInfosByMaterialType(storeCode, materialType);
if (info != null)
{
if (info.Count > 0)
{
result = GetSpaceInfosByPlc(info);
if (result == null)
{
var list = _spaceInfoService.GetEmptySpaceInfo(storeCode);
result = GetSpaceInfosByPlc(list);
}
}
}
}
catch (Exception ex)
{
PrintLogErrorMessage("货道信息读取异常", ex);
}
return result;
}
///
/// 读取PLC货道信息
///
///
///
private BaseSpaceInfo GetSpaceInfosByPlc(List info)
{
BaseSpaceInfo result = null;
if (info != null)
{
if (info.Count > 0)
{
foreach (BaseSpaceInfo item in info)
{
var spaceInfo = taskHandle.ReadSpaceInfoByPlc(item);
item.spaceStock = spaceInfo.spaceStock;
item.onRouteAmount = spaceInfo.onRouteAmount;
item.spaceStatus = spaceInfo.spaceStatus;
PrintLogInfoMessage($"通过PLC读取货道信息,货道:{spaceInfo.spaceName};在库数量:{item.spaceStock};在途数量:{item.onRouteAmount};货道状态:{item.spaceStatus}");
}
var list = info.Where(x => x.spaceStock > 0 ? x.spaceCapacity > (x.spaceStock + x.onRouteAmount) : 1 == 1 && x.spaceStatus == 1).ToList();
if (list.Count > 0)
{
result = list.OrderByDescending(x => x.spaceStock).First();
}
}
}
return result;
}
#endregion
#region 日志输出
///
/// 日志输出,界面刷新同时记录文件
///
///
private void PrintLogInfoMessage(string message)
{
RefreshLogMessageEvent?.Invoke(message);
logHelper.Info(message);
}
///
/// 异常日志输出
///
///
///
private void PrintLogErrorMessage(string message, Exception ex = null)
{
RefreshLogMessageEvent?.Invoke(message);
logHelper.Error(message, ex);
}
#endregion
///
/// 截取两个逗号之间的字符串
///
///
///
static string GetSubstringBetweenCommas(string input)
{
// 找到第一个逗号的位置
int firstCommaIndex = input.IndexOf(',');
if (firstCommaIndex != -1)
{
// 找到第二个逗号的位置
int secondCommaIndex = input.IndexOf(',', firstCommaIndex + 1);
if (secondCommaIndex != -1)
{
// 使用Substring截取第一个逗号和第二个逗号之间的字符
return input.Substring(firstCommaIndex + 1, secondCommaIndex - firstCommaIndex - 1);
}
else
{
return null ;
}
}
else
{
return null ;
}
}
}
}