using Admin.Core.IService; using Admin.Core.Model; using Admin.Core.Model.Model_New; using Admin.Core.Model.ViewModels; using Admin.Core.Service; using Aucma.Core.BoxFoam.Config; using Aucma.Core.HwPLc; using log4net; using Microsoft.Extensions.DependencyInjection; using Microsoft.JSInterop; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Timers; using static ICSharpCode.SharpZipLib.Zip.ExtendedUnixData; namespace Aucma.Core.BoxFoam.Business { /// /// 新箱体发泡班组信息切换 /// public class TeamSwitchBusiness { private static readonly Lazy lazy = new Lazy(() => new TeamSwitchBusiness()); private readonly log4net.ILog log = LogManager.GetLogger(typeof(TeamSwitchBusiness)); private AppConfig appConfig = AppConfig.Instance; private readonly IBoxFoamPlanServices _boxFoamPlanServices; private readonly IBoxFoamDataServices _oldBoxFoamDataServices; private readonly IBoxFoamDataRecordServices _boxFoamDataRecordServices; private readonly IBaseBomInfoServices? _baseBomInfoServices; public List listTime; public static TeamSwitchBusiness Instansece { get { return lazy.Value; } } public TeamSwitchBusiness() { _boxFoamPlanServices = App.ServiceProvider.GetService(); _oldBoxFoamDataServices = App.ServiceProvider.GetService(); _boxFoamDataRecordServices = App.ServiceProvider.GetService(); _baseBomInfoServices = App.ServiceProvider.GetService(); listTime = _baseBomInfoServices.getTwoTime().Result; } /// /// 启动班组切换监听 /// public void startListen(List teamList) { Task.Run(() => { while (true) { try { if (teamList.Count == 1) //单班 { if (appConfig.LoginDate != DateTime.Now.ToString("yyyy-MM-dd") || appConfig.TeamCode != teamList[0].TeamCode) { bool flag = UpdateShiftInfo(1); if (flag) { appConfig.TeamCode = teamList[0].TeamCode; appConfig.TeamName = teamList[0].TeamName; appConfig.LoginDate = DateTime.Now.ToString("yyyy-MM-dd"); } } } else if (teamList.Count == 2) //双班检测 { var currentDate = DateTime.Now; // 判断当前时间属于哪个班组 BaseTeamMembers currentTeam = GetCurrentTeam(teamList, currentDate, out int lastFlag); if (lastFlag == 0) //正常班组时间内 { bool inHalfFlag = IsInHalfHour(currentTeam, currentDate); if (inHalfFlag) { if (currentTeam.TeamCode != appConfig.TeamCode || appConfig.LoginDate != DateTime.Now.ToString("yyyy-MM-dd")) {//判断切班清产量 // 清空PLC数据 bool flag; if (currentTeam.Classes == 1) { flag = UpdateShiftInfo(1); } else { flag = UpdateShiftInfo(2); } if (flag) { appConfig.TeamCode = currentTeam.TeamCode; appConfig.TeamName = currentTeam.TeamName; appConfig.LoginDate = DateTime.Now.ToString("yyyy-MM-dd"); } } } } } }catch (Exception ex) { log.Error(ex); } finally { Thread.Sleep(1000*5); } } }); } //public void Init() //{ // // DayShiftInfoCut(); // // NightShiftInfoCut(); //} ///// ///// 白班信息切换 ///// //private void DayShiftInfoCut() //{ // DateTime now = DateTime.Now; // DateTime scheduledTime; // if (listTime == null) // { // listTime = _baseBomInfoServices.getTwoTime().Result; // } // if (listTime != null) // { // scheduledTime = listTime[0].startTime; // } // else // { // scheduledTime = new DateTime(now.Year, now.Month, now.Day, 08, 00, 00); // } // if (now > scheduledTime) // { // scheduledTime = scheduledTime.AddDays(1); // } // TimeSpan timeToGo = scheduledTime - now; // int dueTime = (int)timeToGo.TotalMilliseconds; // System.Timers.Timer timer = new System.Timers.Timer(); // timer.Elapsed += DayShiftTimerCallback; // timer.AutoReset = true; // timer.Interval = dueTime; // timer.Start(); //} //private void DayShiftTimerCallback(object sender, ElapsedEventArgs e) //{ // DateTime scheduledTime; // Console.WriteLine("切换为白班!"); // UpdateShiftInfo(1); // #region 重新定义Timer,进行第二天执行 // DateTime now = DateTime.Now; // if (listTime == null) // { // listTime = _baseBomInfoServices.getTwoTime().Result; // } // if (listTime != null) // { // scheduledTime = listTime[0].startTime; // } // else // { // scheduledTime = new DateTime(now.Year, now.Month, now.Day, 08, 00, 00); // } // if (now > scheduledTime) // { // scheduledTime = scheduledTime.AddDays(1); // } // TimeSpan timeToGo = scheduledTime - now; // int dueTime = (int)timeToGo.TotalMilliseconds; // System.Timers.Timer timer = (System.Timers.Timer)sender; // timer.Elapsed += DayShiftTimerCallback; // timer.AutoReset = true; // timer.Interval = dueTime; // timer.Start(); // #endregion //} ///// ///// 夜班班组切换 ///// //private void NightShiftInfoCut() //{ // DateTime now = DateTime.Now; // DateTime scheduledTime; // if (listTime == null) // { // listTime = _baseBomInfoServices.getTwoTime().Result; // } // if (listTime != null) // { // scheduledTime = listTime[0].endTime; // } // else // { // scheduledTime = new DateTime(now.Year, now.Month, now.Day, 20, 00, 00); // } // if (now > scheduledTime) // { // scheduledTime = scheduledTime.AddDays(1); // } // TimeSpan timeToGo = scheduledTime - now; // int dueTime = (int)timeToGo.TotalMilliseconds; // System.Timers.Timer timer = new System.Timers.Timer(); // timer.Elapsed += NightShiftTimerCallback; // timer.AutoReset = true; // timer.Interval = dueTime; // timer.Start(); //} //private void NightShiftTimerCallback(object sender, ElapsedEventArgs e) //{ // DateTime scheduledTime; // Console.WriteLine("切换为夜班!"); // UpdateShiftInfo(2); // #region 重新定义Timer,进行第二天执行 // DateTime now = DateTime.Now; // if (listTime == null) // { // listTime = _baseBomInfoServices.getTwoTime().Result; // } // if (listTime != null) // { // scheduledTime = listTime[0].endTime; // } // else // { // scheduledTime = new DateTime(now.Year, now.Month, now.Day, 20, 00, 00); // } // if (now > scheduledTime) // { // scheduledTime = scheduledTime.AddDays(1); // } // TimeSpan timeToGo = scheduledTime - now; // int dueTime = (int)timeToGo.TotalMilliseconds; // System.Timers.Timer timer = (System.Timers.Timer)sender; // timer.Elapsed += NightShiftTimerCallback; // timer.AutoReset = true; // timer.Interval = dueTime; // timer.Start(); // #endregion //} /// /// 班组切换 /// /// 班组类型:1-白班;2-夜班 public bool UpdateShiftInfo(int shiftType) { log.Warn($"{(shiftType == 1 ? "白班" : "夜班")}班组切换,开始处理切换逻辑"); Console.WriteLine($"{(shiftType == 1 ? "白班" : "夜班")}班组切换,开始处理切换逻辑"); try { #region Add By wenjy 2024-03-30 10:56:00 清空PLC产量,写true保持500毫秒后写false bool result = ClearPlcOutPut("1"); if (!result) { // plc状态不对,直接返回 return result; } Task.Run(() => { Thread.Sleep(3000); ClearPlcOutPut("0"); }); #endregion //小时统计报表数据存至记录表,清空小时统计报表 var hourDataList = _oldBoxFoamDataServices.Query(x => x.ProductLineCode == "CX_02" && x.StationCode == "1005"); List hourRecordList = new List(); if (hourDataList != null) { foreach (var item in hourDataList) { BoxFoamDataRecord hourRecord = new BoxFoamDataRecord(); hourRecord.OrderCode = item.OrderCode; hourRecord.ProductLineCode = item.ProductLineCode; hourRecord.Fixturestatus = item.Production; hourRecord.CuringTimeSettingValue = item.CuringTimeSettingValue; hourRecord.ActualValue = item.ActualValue; hourRecord.AnHour = item.AnHour; hourRecord.TwoHour = item.TwoHour; hourRecord.ThreeHour = item.ThreeHour; hourRecord.FourHour = item.FourHour; hourRecord.FiveHour = item.FiveHour; hourRecord.SixHour = item.SixHour; hourRecord.SevenHour = item.SevenHour; hourRecord.EightHour = item.EightHour; hourRecord.NineHour = item.NineHour; hourRecord.TenHour = item.TenHour; hourRecord.ElevenHour = item.ElevenHour; hourRecord.TwelveHour = item.TwelveHour; hourRecord.BoxFixturesideplate = item.BoxFixturesideplate; hourRecord.BoxClosebetatemperature = item.BoxClosebetatemperature; hourRecord.BoxBeat = item.BoxBeat; hourRecord.CreateTime = DateTime.Now; hourRecordList.Add(hourRecord); bool deleteFlag = _oldBoxFoamDataServices.DeleteAsync(item).Result; if (deleteFlag) { log.Warn($"{item.Fixtureboxtype}:小时数据清除成功"); } else { log.Warn($"{item.Fixtureboxtype}:小时数据清除失败"); } } } int addFlag = _boxFoamDataRecordServices.AddAsync(hourRecordList).Result; if (addFlag > 0) { log.Warn("班组切换小时数据记录保存成功"); } else { log.Warn("班组切换小时数据记录保存失败"); } //当班计划,班组计划设为0 var planInfoList = _boxFoamPlanServices.QueryAsync(x => x.ProductLineCode == "CX_02" && x.StationCode == "1005" && x.ShiftType == 1).Result; if (planInfoList != null) { foreach (var plan in planInfoList) { plan.ShiftType = 0; bool updateFlag = _boxFoamPlanServices.UpdateAsync(plan).Result; if (updateFlag) { log.Warn($"计划:{plan.OrderCode},班组切换标识更新成功"); if (plan.PlanAmount > plan.CompleteAmount) { plan.PlanAmount = plan.PlanAmount - plan.CompleteAmount; plan.CompleteAmount = 0; plan.ShiftType = 1; int saveFlag = _boxFoamPlanServices.AddAsync(plan).Result; if (saveFlag > 0) { log.Warn($"计划:{plan.OrderCode},剩余计划:{plan.PlanAmount},未完成进行顺延,执行成功"); } else { log.Warn($"计划:{plan.OrderCode},剩余计划:{plan.PlanAmount},未完成进行顺延,执行失败"); } } } else { log.Warn($"计划:{plan.OrderCode},班组切换标识更新失败"); } } } return true; } catch (Exception ex) { log.Warn($"{(shiftType == 1 ? "白班" : "夜班")}班组切换,切换逻辑处理异常:{ex.Message}"); return false; } } /// /// 清空PLC产量数据 /// /// private bool ClearPlcOutPut(string value) { try { bool result = false; var obj1 = PlcHelper.siemensList.FirstOrDefault(d => d.EquipName.Equals("foamLine1Plc")); if (obj1 != null && obj1.plc.IsConnected) { var flag = obj1.plc.WriteInt16("DB16.DBW40", value);//换班 数据清空 log.Warn($"班组切换清空A区产量数据写{value}:{(flag == true ? "成功" : "失败")}"); Console.WriteLine($"班组切换清空A区产量数据写{value}:{(flag == true ? "成功" : "失败")}"); } else { return false; } var obj2 = PlcHelper.siemensList.FirstOrDefault(d => d.EquipName.Equals("foamLine2Plc")); if (obj2 != null && obj2.plc.IsConnected) { bool flag = obj2.plc.WriteInt16("DB16.DBW40", value);//换班 数据清空 log.Warn($"班组切换清空B区产量数据写{value}:{(flag == true ? "成功" : "失败")}"); Console.WriteLine($"班组切换清空B区产量数据写{value}:{(flag == true ? "成功" : "失败")}"); } else { return false; } result = true; return result; }catch (Exception ex) { return false; } } #region 班组时间判断算法 /// /// lastFlag=0代表当前时间段属于某个班组,这个时候需要判断是否清除plc数据 /// lastFlag=1代表当前时间段不属于任意一个班组,属于中间值,这个时候登录无需清除plc数据 /// /// /// /// public BaseTeamMembers GetCurrentTeam(List teamList, DateTime currentDate, out int lastFlag) { lastFlag = 0; BaseTeamMembers currentTeam = null; // 遍历所有班组 foreach (var team in teamList) { if (TryParseTime(team.StartTime, team.EndTime, out var startTime, out var endTime)) { // 检查当前时间是否在班组的正常范围内 if (IsTimeInRange(currentDate.TimeOfDay, startTime, endTime)) { return team; } } } currentTeam = IsTimeWithinEndTimeBuffer(currentDate.TimeOfDay, teamList); lastFlag = 1; // 如果没有匹配的班组,返回 null return currentTeam; } private bool TryParseTime(string startTime, string endTime, out TimeSpan start, out TimeSpan end) { if (TimeSpan.TryParse(startTime, out start) && TimeSpan.TryParse(endTime, out end)) { return true; } start = default; end = default; return false; } private bool IsTimeInRange(TimeSpan currentTime, TimeSpan startTime, TimeSpan endTime) { // 处理跨越两天的班组 if (startTime <= endTime) { return currentTime >= startTime && currentTime < endTime; } else { return currentTime >= startTime || currentTime < endTime; } } private BaseTeamMembers IsTimeWithinEndTimeBuffer(TimeSpan currentTime, List teamList) { // 计算当前时间与班组结束时间之间的时间差 TimeSpan.TryParse(teamList[0].EndTime, out TimeSpan endtime0); TimeSpan.TryParse(teamList[1].EndTime, out TimeSpan endtime1); TimeSpan timeDiff0; TimeSpan timeDiff1; if(currentTime>= endtime0) { timeDiff0 = currentTime - endtime0; } else { timeDiff0 = endtime0 - currentTime; } if (currentTime >= endtime1) { timeDiff1 = currentTime - endtime1; } else { timeDiff1 = endtime1 - currentTime; } if(timeDiff0 < timeDiff1) { return teamList[0]; } else { return teamList[1]; } } /// /// 是否在当前班次开班半小时以内 /// /// public bool IsInHalfHour(BaseTeamMembers team, DateTime currentDate) { try { TimeSpan startTime = TimeSpan.Parse(team.StartTime); TimeSpan halfHour = TimeSpan.FromMinutes(30); //次日凌晨 if (team.Classes == 2 && currentDate.TimeOfDay < startTime) { return false; } if (currentDate.TimeOfDay - startTime <= halfHour) { return true; } return false; }catch (Exception ex) { return false; } } #endregion } }