using System; using System.Linq; using DOAN.Model; using DOAN.Model.MES.dev; using DOAN.Model.MES.dev.Dto; using DOAN.Repository; using DOAN.Service.MES.dev.IService; using Infrastructure.Attribute; using Infrastructure.Extensions; using JinianNet.JNTemplate; using JinianNet.JNTemplate.Nodes; using Mapster; using Microsoft.AspNetCore.Authentication; using Newtonsoft.Json.Linq; using SqlSugar; using SqlSugar.IOC; namespace DOAN.Service.MES.dev { /// /// 任务执行Service业务层处理 /// [AppService( ServiceType = typeof(IDeviceTaskExecuteService), ServiceLifetime = LifeTime.Transient )] public class DeviceTaskExecuteService : BaseService, IDeviceTaskExecuteService { /// /// 查询任务执行列表 /// /// /// public PagedInfo GetList(DeviceTaskExecuteQueryDto parm) { var predicate = Expressionable .Create() .AndIF( !string.IsNullOrEmpty(parm.TaskName), it => it.TaskName.Contains(parm.TaskName) ) .AndIF( parm.TimeRange != null && (parm.TimeRange[0] > new DateTime(1990, 1, 1)), it => it.CreatedTime >= parm.TimeRange[0] ) .AndIF( parm.TimeRange != null && (parm.TimeRange[1] > new DateTime(1990, 1, 1)), it => it.CreatedTime <= parm.TimeRange[1] ) .AndIF(parm.Type > -1, it => it.Type == parm.Type) .AndIF(parm.Status > -1, it => it.Status == parm.Status); var response = Queryable() .OrderByDescending(x => x.Id) .Where(predicate.ToExpression()) .ToPage(parm); foreach (DeviceTaskExecuteDto item in response.Result) { if (item.StartTime > DateTime.MinValue && item.EndTime > DateTime.MinValue) { TimeSpan timeDifference = item.EndTime.Value - item.StartTime.Value; double minutes = timeDifference.TotalMinutes; double roundedMinutes = Math.Round(minutes, 1); item.ConsumeTime = roundedMinutes; } } return response; } /// /// 获取详情 /// /// /// public DeviceTaskExecute GetInfo(string Id) { var response = Queryable().Where(x => x.Id == Id).First(); return response; } /// /// 添加任务执行 /// /// /// public DeviceTaskExecute AddDeviceTaskExecute(DeviceTaskExecute model) { model.Id = SnowFlakeSingle.Instance.NextId().ToString(); return Context.Insertable(model).ExecuteReturnEntity(); } /// /// 修改任务执行 /// /// /// public int UpdateDeviceTaskExecute(DeviceTaskExecute model) { //var response = Update(w => w.Id == model.Id, it => new DeviceTaskExecute() //{ // TaskName = model.TaskName, // Type = model.Type, // DistributedTime = model.DistributedTime, // StartTime = model.StartTime, // EndTime = model.EndTime, // Status = model.Status, // Remark = model.Remark, // CreatedBy = model.CreatedBy, // CreatedTime = model.CreatedTime, // UpdatedBy = model.UpdatedBy, // UpdatedTime = model.UpdatedTime, //}); //return response; return Update(model, true); } public int Update_task_status(DeviceTaskExecuteQueryDto2 parm) { var response = Update( w => w.Id == parm.Id, it => new DeviceTaskExecute() { Status = parm.Status, UpdatedBy = parm.UpdatedBy, UpdatedTime = parm.UpdatedTime, } ); return response; } /// /// 清空任务执行 /// /// public bool TruncateDeviceTaskExecute() { var newTableName = $"device_task_execute_{DateTime.Now:yyyyMMdd}"; if (Queryable().Any() && !Context.DbMaintenance.IsAnyTable(newTableName)) { Context.DbMaintenance.BackupTable("device_task_execute", newTableName); } return Truncate(); } /// /// 导入任务执行 /// /// public (string, object, object) ImportDeviceTaskExecute(List list) { var x = Context .Storageable(list) .SplitInsert(it => !it.Any()) .SplitError(x => x.Item.Type.IsEmpty(), "任务类型(1是巡检,2是点检)不能为空") //.WhereColumns(it => it.UserName)//如果不是主键可以这样实现(多字段it=>new{it.x1,it.x2}) .ToStorage(); var result = x.AsInsertable.ExecuteCommand(); //插入可插入部分; string msg = $"插入{x.InsertList.Count} 更新{x.UpdateList.Count} 错误数据{x.ErrorList.Count} 不计算数据{x.IgnoreList.Count} 删除数据{x.DeleteList.Count} 总共{x.TotalList.Count}"; Console.WriteLine(msg); //输出错误信息 foreach (var item in x.ErrorList) { Console.WriteLine("错误" + item.StorageMessage); } foreach (var item in x.IgnoreList) { Console.WriteLine("忽略" + item.StorageMessage); } return (msg, x.ErrorList, x.IgnoreList); } /// /// 任务计划调度 扫描每日巡检任务 /// 保养和检查 /// /// public int ScanEveryTask() { int result = 0; List InitDataList = DbScoped.SugarScope.CopyNew() .Queryable() .Where(it => it.Status == 1) .Where(it => it.LifeCycleStart <= DateTime.Now) .Where(it => it.LifeCycleEnd >= DateTime.Now) .ToList(); // 今日时间 DateTime CurrentTime = new DateTime( DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0 ); //1. 扫描巡检 List deviceRouteInspectionPlan_execute_List = new List(); #region 1.1 每日类型处理 List RouteInspectionPlan_day_List = InitDataList .Where(it => it.ExcuteCycleType == 1) .ToList(); Console.WriteLine("每日类型处理" + RouteInspectionPlan_day_List.Count); if (RouteInspectionPlan_day_List != null && RouteInspectionPlan_day_List.Count > 0) { foreach (var item in RouteInspectionPlan_day_List) { //开始日期 DateTime start_cal = (DateTime)item.CreatedTime; start_cal = new DateTime( start_cal.Year, start_cal.Month, start_cal.Day, 0, 0, 0 ); //循环周期 int cycle_period = (int)item.DayNum; DateTime date = start_cal; do { date = date.AddDays(cycle_period); if (date == CurrentTime) { //今日要执行任务 deviceRouteInspectionPlan_execute_List.Add(item); break; } } while (date <= CurrentTime); } } #endregion #region 1.2 每周类型处理 List DeviceRouteInspectionPlan_week_list = InitDataList .Where(it => it.ExcuteCycleType == 2) .ToList(); Console.WriteLine("每周类型处理" + DeviceRouteInspectionPlan_week_list.Count); int dayofweek = (int)CurrentTime.DayOfWeek; if (CurrentTime.DayOfWeek == DayOfWeek.Sunday) { dayofweek = 7; } if ( DeviceRouteInspectionPlan_week_list != null && DeviceRouteInspectionPlan_week_list.Count > 0 ) { foreach (var item in DeviceRouteInspectionPlan_week_list) { string[] cycle_period = item.WeekList.Split(","); if (cycle_period.Length > 0) { for (int i = 0; i < cycle_period.Length; i++) { try { Console.WriteLine("cycle_period[i]=" + cycle_period[i]); if (dayofweek == Convert.ToInt32(cycle_period[i])) { deviceRouteInspectionPlan_execute_List.Add( (DeviceRouteInspectionPlan)item ); break; } } catch (FormatException ex) { Console.WriteLine("An error occurred: " + ex.Message); continue; } } } } } #endregion #region 1.3 每月类型处理 List DeviceRouteInspectionPlan_month_list = InitDataList .Where(it => it.ExcuteCycleType == 3) .ToList(); Console.WriteLine("每月类型处理" + DeviceRouteInspectionPlan_month_list.Count); if ( DeviceRouteInspectionPlan_month_list != null && DeviceRouteInspectionPlan_month_list.Count > 0 ) { foreach (var item in DeviceRouteInspectionPlan_month_list) { try { if (CurrentTime.Day == Convert.ToInt32(item.MonthDayList)) { deviceRouteInspectionPlan_execute_List.Add( (DeviceRouteInspectionPlan)item ); continue; } } catch (FormatException ex) { Console.WriteLine("An error occurred: " + ex.Message); continue; } } } #endregion // 插入数据库 List executes = new List(); if (deviceRouteInspectionPlan_execute_List.Count > 0) { foreach (var item in deviceRouteInspectionPlan_execute_List) { DeviceTaskExecute taskExecute = new DeviceTaskExecute(); taskExecute.Id = SnowFlakeSingle.Instance.NextId().ToString(); taskExecute.TaskName = item.Name; taskExecute.PlanId = item.Id; taskExecute.Type = 1; taskExecute.InnerType = item.InnerType; taskExecute.DistributedTime = DateTime.Now; taskExecute.Status = 0; taskExecute.CreatedTime = DateTime.Now; executes.Add(taskExecute); } if (executes.Count > 0) { result = Context.Insertable(executes).ExecuteCommand(); } } return result; } /// /// 派发点检任务 /// /// /// public int ExecutionTask_point(string id) { DevicePointInspectionPlan point = Context .Queryable() .Where(it => it.Id == id) .First(); DeviceTaskExecute taskExecute = new DeviceTaskExecute(); taskExecute.Id = SnowFlakeSingle.Instance.NextId().ToString(); taskExecute.TaskName = point.Name; taskExecute.PlanId = point.Id; taskExecute.Type = 2; taskExecute.DistributedTime = DateTime.Now; taskExecute.Status = 0; taskExecute.CreatedTime = DateTime.Now; return Context.Insertable(taskExecute).ExecuteCommand(); } /// /// 获取任务执行绑定的巡检任务和点检任务绑定的设备 /// public List AchieveTaskbindDevice(string id) { List resul = null; DeviceTaskExecute executeTask = Context .Queryable() .Where(it => it.Id == id) .First(); if (executeTask != null) { // 类型为巡检 if (executeTask.Type == 1) { resul = Context .Queryable() .LeftJoin((r, a) => r.FkDeviceAccountId == a.Id) .Where(r => r.FkRouteInspectionPlanId == executeTask.PlanId) .Select((r, a) => a) .ToList(); } // 类型为点检 else if (executeTask.Type == 2) { resul = Context .Queryable() .LeftJoin((p, a) => p.FkDeviceAccountId == a.Id) .Where(p => p.FkPointInspectionPlanId == executeTask.PlanId) .Select((p, a) => a) .ToList(); } } return resul; } /// /// 获取设备绑定的检查项 /// /// 设备id /// 计划id /// 计划类型 /// public List AchieveDevicebindInspect(int fk_device_id, string fkPlanId, int planType) { // 判断是保养/检查吗 int check_type = 1; if(planType == 1) { check_type= Context.Queryable().Where(it => it.Id == fkPlanId) .Select(it => it.InnerType.Value).First(); }else if (planType == 2) { check_type = Context.Queryable().Where(it => it.Id == fkPlanId) .Select(it => it.InnerType.Value).First(); } List resul = null; resul = Context .Queryable() .LeftJoin((r, i) => r.FkInspectId == i.Id) .Where(r => r.FkAccountId == fk_device_id) .Where((r,i)=>i.Type==check_type) .Select((r, i) => i) .ToList(); return resul; } /// /// 获取检查项绑定的检查表单 /// public List AchieveInspectbindForm(int fk_device_inspect_id) { List result = null; result = Context .Queryable() .Where(it => it.FkDeviceInspectId == fk_device_inspect_id) .ToList(); return result; } /// /// 获取表单结果 /// /// public List AchieveFormResult( DeviceTaskExecuteResult1QueryDto_TaskExecute query ) { List final_result_list = new List(); List resultList = Context .Queryable() .Where(it => it.PlanType == query.PlanType) .Where(it => it.FkPlanId == query.FkPlanId) .Where(it => it.FkDeviceId == query.FkDeviceId) .Where(it => it.FkInspectId == query.FkInspectId) .ToList(); if (resultList.Count == 0) { //初始化结果表 List configlist = Context .Queryable() .Where(it => it.FkDeviceInspectId == query.FkInspectId) .ToList(); if (configlist.Count > 0) { List addResultList = new List(); string PlanName = Context .Queryable() .Where(it => it.Id == query.FkPlanId) .First() ?.Name; string DeviceName = Context .Queryable() .Where(it => it.Id == query.FkDeviceId) .First() ?.DeviceName; string InspectName = Context .Queryable() .Where(it => it.Id == query.FkInspectId) .First() ?.Name; foreach (DeviceFormConfig config in configlist) { DeviceTaskExecuteResult result1 = new DeviceTaskExecuteResult(); result1.Id = SnowFlakeSingle.Instance.NextId().ToString(); result1.PlanType = query.PlanType; result1.FkPlanId = query.FkPlanId; result1.PlanName = PlanName; result1.FkDeviceId = query.FkDeviceId; result1.DeviceName = DeviceName; result1.FkInspectId = query.FkInspectId; result1.InspectName = InspectName; result1.FormType = config.Type; result1.FormTitle = config.Title; result1.FormName = config.Content; addResultList.Add(result1); //生成返回结果 } Context.Insertable(addResultList).ExecuteCommand(); // 处理初始化返回 if (addResultList.Count > 0) { // 1 取出所有的类别 int?[] FormTypeArray = addResultList .Select(it => it.FormType) .Distinct() .ToArray(); //2. 分别处理类别 for (int i = 0; i < FormTypeArray.Length; i++) { var temp = addResultList .Where(it => it.FormType == FormTypeArray[i]) .ToList(); DeviceTaskExecuteResult1_result item = new DeviceTaskExecuteResult1_result(); item.Id = temp[0].Id; item.Title = temp[0].FormTitle; item.Type = temp[0].FormType; item.Value = ""; item.Children = addResultList .Where(it => it.FormType == FormTypeArray[i]) .Select(it => it.FormName) .Distinct() .ToArray(); item.Value = item.Children[0]; final_result_list.Add(item); } } } } else if (resultList.Count > 0) { // 直接从结果表中获取 if (resultList.Count > 0) { // 1 取出所有的类别 int?[] FormTypeArray = resultList .Select(it => it.FormType) .Distinct() .ToArray(); //2. 分别处理类别 for (int i = 0; i < FormTypeArray.Length; i++) { var temp = resultList.Where(it => it.FormType == FormTypeArray[i]).ToList(); DeviceTaskExecuteResult1_result item = new DeviceTaskExecuteResult1_result(); item.Id = temp[0].Id; item.Title = temp[0].FormTitle; item.Type = temp[0].FormType; item.Value = ""; item.Children = resultList .Where(it => it.FormType == FormTypeArray[i]) .Select(it => it.FormName) .Distinct() .ToArray(); List FormResultArray = resultList .Where(it => it.FormType == FormTypeArray[i]) .ToList(); if (FormResultArray.Count == 1) { item.Value = FormResultArray[0].FormName; } else if (FormResultArray.Count > 1) { string[] str = new string[FormResultArray.Count]; for (int ii = 0; ii < str.Length; ii++) { str[i] = FormResultArray[ii].FormName; } item.Value = string.Join(", ", str).ToString(); } else { item.Value = item.Children[0]; } final_result_list.Add(item); } } } return final_result_list; } /// /// 获取表单结果2 /// 结果表只存选中的结果,多选也只有一个结果 /// /// public List AchieveFormResult2( DeviceTaskExecuteResult1QueryDto_TaskExecute query ) { List final_result_list = new List(); // 获取 设备检查项 所有表单类型 List all_config_list = Context .Queryable() .Where(it => it.FkDeviceInspectId == query.FkInspectId) .ToList(); int?[] config_type = all_config_list.Select(it => it.Type).Distinct().ToArray(); DevicePointInspectionPlan handle_point_plan = Context .Queryable() .Where(it => it.Id == query.FkPlanId) .First(); DeviceRouteInspectionPlan handle_rounte_plan = Context .Queryable() .Where(it => it.Id == query.FkPlanId) .First(); DeviceAccount deviceAccount = Context .Queryable() .Where(it => it.Id == query.FkDeviceId) .First(); DeviceInspect inspect = Context .Queryable() .Where(it => it.Id == query.FkInspectId) .First(); if (config_type.Length > 0) { for (int i = 0; i < config_type.Length; i++) { //在结果表里查看是否有结果 DeviceTaskExecuteResult executeResult = Context .Queryable() .Where(it => it.FkTaskId == query.FkTaskId) .Where(it => it.PlanType == query.PlanType) .Where(it => it.FkPlanId == query.FkPlanId) .Where(it => it.FkDeviceId == query.FkDeviceId) .Where(it => it.FkInspectId == query.FkInspectId) .Where(it => it.FormType == config_type[i]) .First(); if (executeResult != null) { DeviceTaskExecuteResult1_result item = new() { Id = executeResult.Id, Title = executeResult.FormTitle, Value = executeResult.FormName, Type = executeResult.FormType, Children = all_config_list .Where(it => it.Type == config_type[i]) .Select(it => it.Content) .ToArray() }; final_result_list.Add(item); } else { DeviceTaskExecuteResult insertData = new() { Id = SnowFlakeSingle.Instance.NextId().ToString(), FkTaskId = query.FkTaskId, PlanType = query.PlanType, FkPlanId = query.FkPlanId }; //点检 if (query.PlanType == 2) { insertData.FkPlanId = query.FkPlanId; insertData.PlanName = handle_point_plan?.Name; insertData.InnerType = handle_point_plan?.InnerType; } else if (query.PlanType == 1) { //巡检 insertData.FkPlanId = query.FkPlanId; insertData.PlanName = handle_rounte_plan?.Name; insertData.ExcuteCycleType = handle_rounte_plan?.ExcuteCycleType; insertData.InnerType = handle_rounte_plan?.InnerType; } insertData.FkDeviceId = query.FkDeviceId; insertData.DeviceName = deviceAccount.DeviceName; insertData.FkInspectId = query.FkInspectId; insertData.InspectName = inspect.Name; insertData.FormType = config_type[i]; insertData.FormTitle = all_config_list .Where(it => it.Type == config_type[i]) .Select(it => it.Title) .First(); Context.Insertable(insertData).ExecuteReturnIdentity(); DeviceTaskExecuteResult1_result item = new() { Id = insertData.Id, Title = insertData.FormTitle, Value = "", Type = insertData.FormType, Children = all_config_list .Where(it => it.Type == config_type[i]) .Select(it => it.Content) .ToArray() }; final_result_list.Add(item); } } } return final_result_list; } /// /// 更新结果表单 /// /// /// public int UpdateFormResult(DeviceTaskExecuteResultDto result) { //if (!string.IsNullOrEmpty(result.taskExecute_id)) // Context.Updateable().Where(it => it.Id == result.taskExecute_id).SetColumns(it => it.Person == result.UpdatedBy).ExecuteCommand(); result.Person = result.UpdatedBy; DeviceTaskExecuteResult item = result.Adapt(); return Context .Updateable(item) .IgnoreColumns(true) .EnableDiffLogEvent("更新结果表单") .ExecuteCommand(); } /// /// 增加任务开始时间 /// /// /// public int AddDeviceTaskExecute(string Id, string name) { DateTime dateTime = DateTime.Now; return Context .Updateable() .Where(it => it.Id == Id) .Where(it => it.StartTime == null) .SetColumns(it => it.StartTime == dateTime) .SetColumns(it => it.Person == name) .ExecuteCommand(); } /// /// 增加任务完成时间 /// /// /// public int AddTaskFinallyTime(string Id) { DateTime dateTime = DateTime.Now; return Context .Updateable() .Where(it => it.Id == Id) .SetColumns(it => it.EndTime == dateTime) .ExecuteCommand(); } } }