using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using APT.BaseData.Domain.Enums;
using APT.MS.Domain.Entities.HM;
using Microsoft.AspNetCore.JsonPatch.Operations;
using System.Threading.Tasks;
using System.Diagnostics.Eventing.Reader;
using APT.BaseData.Services.Services.FM;

namespace APT.FO.WebApi.Controllers.Api.FO
{
    [Route("api/FO/FOPreShiftMeetingRecord")]
    public class PreShiftMeetingRecordController : AuthorizeApiController<T_FO_PRE_SHIFT_MEETING_RECORD>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }

        public PreShiftMeetingRecordController(IPFCodeRuleService coderuleService, IFMNotificationTaskService notificationTaskService, IFMDepartmentService departmentService)
        {
            CodeRuleService = coderuleService;
            NotificationTaskService = notificationTaskService;
            DepartmentService = departmentService;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FO_PRE_SHIFT_MEETING_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var users = entity.Nav_Users.Where(t => t.USER_ID != Guid.Empty);
                var files = entity.Nav_Files;
                entity.Nav_Users = null;
                entity.Nav_Files = null;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                T_FM_NOTIFICATION_TASK finishNotice = null;
                List<T_FM_NOTIFICATION_TASK> sendNotices = null;
                if (entity.PRE_MEETING_STATUS >= FOPreMeetingStatusEnum.签到中)
                {
                    throw new Exception("你已提交,请勿重复提交!");
                }

                if (users == null || users.Count(t => t.IS_DELETED == false) == 0)
                {
                    throw new Exception("通知人员不能为空");
                }
                if (entity.DEPARTMENT_ID == null)
                {
                    var user = GetEntity<T_FM_USER>(t => t.ID == userID);
                    if (user != null)
                        entity.DEPARTMENT_ID = user.DEPARTMENT_ID;
                }
                if (entity.USER_ID == null)
                {
                    entity.USER_ID = userID;
                }
                var TeamName = "";
                if (entity.TEAM_ID != null)
                {
                    TeamName = GetEntity<T_FM_TEAM>(entity.TEAM_ID.ToString()).NAME;
                }
                else
                {
                    var currTeam = GetEntity<T_FM_TEAM>(t => t.DEPARTMENT_ID == entity.DEPARTMENT_ID);
                    entity.TEAM_ID = currTeam.ID;
                    TeamName = currTeam.NAME;
                }
                if (entity.NAME == null)
                {
                    entity.NAME = DateTime.Now.Date.ToString("yyyyMMdd") + TeamName + "-班前会议";
                }
                var isRepeat = GetCount<T_FO_PRE_SHIFT_MEETING_RECORD>(t => t.NAME == entity.NAME && t.PRE_MEETING_STATUS > 0 && t.CLASS_ID == entity.CLASS_ID&&t.USER_ID==entity.USER_ID, new BaseFilter(entity.ORG_ID));
                if (isRepeat > 0)
                {
                    throw new Exception("检测到班前会议数据重复，请联系管理员!");
                }
                //20230913新增同步人员排班
                List<T_FM_DEPARTMENT_SCHEDULING_DETAIL> addSchedulings = new List<T_FM_DEPARTMENT_SCHEDULING_DETAIL>();
                List<Guid> delSchedulings = new List<Guid>();

                if (entity.DEPARTMENT_SCHEDULING_ID != null)
                {
                    var shiftClass = GetEntities<T_FM_DEPARTMENT_SCHEDULING_DETAIL>(t => t.DEPARTMENT_SCHEDULING_ID == entity.DEPARTMENT_SCHEDULING_ID, new BaseFilter(entity.ORG_ID), new string[] { "Nav_Person.Nav_User" });
                    var delUsers = users.Where(t => t.IS_DELETED == true).Select(t => t.USER_ID);
                    var addUsers = users.Where(t => t.CREATE_TIME > entity.CREATE_TIME).Select(t => t.USER_ID);
                    foreach (var user in addUsers)
                    {
                        var addDetails = shiftClass.FirstOrDefault(t => t.Nav_Person.Nav_User.ID == user);
                        if (addDetails == null)
                        {
                            T_FM_DEPARTMENT_SCHEDULING_DETAIL addScheduling = new T_FM_DEPARTMENT_SCHEDULING_DETAIL();
                            addScheduling.PERSON_ID = (Guid)GetEntity<T_FM_USER>(t => t.ID == user).PERSON_ID;
                            addScheduling.DEPARTMENT_SCHEDULING_ID = (Guid)entity.DEPARTMENT_SCHEDULING_ID;
                            addScheduling.ORG_ID = entity.ORG_ID;
                            addSchedulings.Add(addScheduling);
                        }
                    }
                    delSchedulings = shiftClass.Where(t => delUsers.Contains(t.Nav_Person.Nav_User.ID)).Select(t => t.ID).ToList();
                }
                if (entity.RATE.Equals("SaveAndNotify"))
                {
                    var meetingTime = DateTime.Now;
                    //meetingTime = DateTime.Parse("2023-06-15 06:30:00");
                    if (entity.START_TIME!= DateTime.MinValue && entity.START_TIME.AddMinutes(-15) >= meetingTime)
                    {
                        throw new Exception("班前会议需等到" + entity.START_TIME.AddMinutes(-15) + "后提交!");
                    }
                    entity.MEETING_TIME = meetingTime;
                    entity.PRE_MEETING_STATUS = FOPreMeetingStatusEnum.签到中;
                    //直接处理班组长已签到,并修改通知状态
                    var chargeUser = users.Where(t => t.USER_ID == userID && t.DEAL_STATUS == (int)FOUserShiftStatusEnum.待处理);
                    foreach (var user in chargeUser)
                    {
                        user.DEAL_STATUS = (int)FOUserShiftStatusEnum.已处理;
                    }
                    //新增的消息通知
                    var title = TeamName + entity.MEETING_TIME.Date.ToString("yyyyMMdd") + "-班前会议签到";
                    var noChargeUsers = users.Where(i => i.USER_ID != userID && i.IS_DELETED == false).Select(t => t.USER_ID);
                    BaseFilter filter = new BaseFilter(entity.ORG_ID);
                    filter.SelectField = new string[] { "ID", "NAME" };
                    var allusers = GetEntities<T_FM_USER>(t => noChargeUsers.Contains(t.ID), filter);
                    List<Guid> userIds = new List<Guid>();
                    List<string> userNames = new List<string>();
                    List<string> titles = new List<string>();
                    List<Guid> dataIds = new List<Guid>();
                    foreach (var user in noChargeUsers)
                    {
                        userIds.Add(user);
                        userNames.Add(allusers.FirstOrDefault(t => t.ID == user).NAME);
                    }
                    if (noChargeUsers.Count() == 0)
                    {
                        entity.PRE_MEETING_STATUS = FOPreMeetingStatusEnum.归档;
                    }
                    var endTime = DateTime.Now.AddHours(1);
                    if (entity.START_TIME != DateTime.MinValue)
                    {
                        endTime = entity.START_TIME.AddHours(1);
                    }
                    sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(title, entity.ID, entity.ORG_ID, userIds, userNames, DateTime.Now, endTime, (int)FMNoticeTypeEnum.消息, "FO003_SHOWPRINT");
                    var taskId = entity.TaskID;
                    if (taskId == Guid.Empty)
                    {
                        var task = GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == userID
                && i.NOTICE_STATUS == FMNoticeStatusEnum.未处理.GetInt() && i.SOURCE_FORMCODE == "FO003");
                        if (task != null)
                        {
                            taskId = task.ID;
                        }
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "FO003_SHOWPRINT");
                    }
                }
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (users.Any())
                        BantchSaveEntityNoCommit(users);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (sendNotices != null && sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                    if (delSchedulings.Any())
                        BantchDeleteEntityNoCommit<T_FM_DEPARTMENT_SCHEDULING_DETAIL>(delSchedulings);
                    if (addSchedulings.Any())
                        BantchAddEntityNoCommit(addSchedulings);
                });
                return true;
            });
        }

        /// <summary>
        /// 获取个人的班组前会议活动
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetPreShiftMeetingRecord")]
        public JsonActionResult<bool> GetPreShiftMeetingRecord([FromBody] T_FO_PRE_SHIFT_MEETING_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var model = GetEntity<T_FO_PRE_SHIFT_MEETING_RECORD>(entity.ID.ToString());
                if (model.PRE_MEETING_STATUS != FOPreMeetingStatusEnum.签到中)
                    return false;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var count = GetCount<T_FO_PRE_SHIFT_MEETING_RECORD_USER>(t => t.PRE_SHIFT_MEETING_RECORD_ID == entity.ID && t.USER_ID == userID && t.DEAL_STATUS == 0, new BaseFilter(APT.Infrastructure.Api.AppContext.CurrentSession.OrgId));
                if (count > 0)  //该用户在该记录中是否参与且未同意则显示同意按钮
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
        }


        /// <summary>
        /// 班前会议签到同意
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("PersonalAgree")]
        public JsonActionResult<bool> PersonalAgree([FromBody] T_FO_PRE_SHIFT_MEETING_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var users = GetEntities<T_FO_PRE_SHIFT_MEETING_RECORD_USER>(t => t.PRE_SHIFT_MEETING_RECORD_ID == entity.ID, new BaseFilter(orgId));
                var currUsers = users.Where(t => t.USER_ID == userID);
                foreach (var user in currUsers)
                {
                    user.DEAL_STATUS = (int)FOUserShiftStatusEnum.已处理;
                    user.MODIFY_TIME = DateTime.Now;
                }
                T_FO_PRE_SHIFT_MEETING_RECORD model = null;
                var todoCount = users.Count(t => t.DEAL_STATUS == 0);
                if (todoCount == 0)
                {
                    model = GetEntity<T_FO_PRE_SHIFT_MEETING_RECORD>(entity.ID.ToString());
                    model.PRE_MEETING_STATUS = FOPreMeetingStatusEnum.归档;
                    model.IS_RUN = WFDisableStatusEnum.是;
                }
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID);
                }
                var eventRecords = new List<T_FO_JOB_EVENT_RECORD>();
                var jobs = new List<T_FO_CRUCIAL_LICENSE_JOB>();
                var notices = new List<T_FM_NOTIFICATION_TASK>();
                var persons = new List<T_FO_JOB_EVENT_PERSON>();
                var details = new List<T_FO_JOB_EVENT_DETAIL>();
                var flows = new List<T_FO_JOB_EVENT_FLOW>();
                var measures = new List<T_FO_JOB_EVENT_MEASURE>();
                var jobDetails = new List<T_FO_CRUCIAL_LICENSE_SAFE_CONFIRM>();
                var jobFlows = new List<T_FO_CRUCIAL_LICENSE_SAFE_MEASURE>();
                var jobMeasures = new List<T_FO_CRUCIAL_LICENSE_DEAL_MEASURE>();
                var temp = GetEntity<T_FO_PRE_SHIFT_MEETING_RECORD>(entity.ID.ToString());
                var curentUser = users.Where(t => t.USER_ID == userID).ToList();
                GetAutoNext(temp, curentUser, ref eventRecords, ref jobs, ref notices);
                if (eventRecords != null && eventRecords.Any())
                {
                    eventRecords.ForEach(t =>
                    {
                        if (t.Nav_JobEventPerson != null && t.Nav_JobEventPerson.Any())
                            persons.AddRange(t.Nav_JobEventPerson);
                        if (t.Nav_Details != null && t.Nav_Details.Any())
                            details.AddRange(t.Nav_Details);
                        if (t.Nav_Flow != null && t.Nav_Flow.Any())
                            flows.AddRange(t.Nav_Flow);
                        if (t.Nav_Measure != null && t.Nav_Measure.Any())
                            measures.AddRange(t.Nav_Measure);
                    });
                }
                if (jobs != null && jobs.Any())
                {
                    jobs.ForEach(t =>
                    {
                        if (t.Nav_SafeConfirms != null && t.Nav_SafeConfirms.Any())
                            jobDetails.AddRange(t.Nav_SafeConfirms);
                        if (t.Nav_SafeMeasures != null && t.Nav_SafeMeasures.Any())
                            jobFlows.AddRange(t.Nav_SafeMeasures);
                        if (t.Nav_DealMeasures != null && t.Nav_DealMeasures.Any())
                            jobMeasures.AddRange(t.Nav_DealMeasures);
                    });
                }
                UnifiedCommit(() =>
                {
                    if (currUsers != null && currUsers.Any() && task != null)
                    {
                        BantchUpdateEntityNoCommit(currUsers, "DEAL_STATUS", "MODIFY_TIME");
                        UpdateEntityNoCommit(task);
                    }
                    if (model != null)
                    {
                        UpdateEntityNoCommit(model, "PRE_MEETING_STATUS", "IS_RUN");
                    }
                    if (eventRecords != null && eventRecords.Any())
                        BantchSaveEntityNoCommit(eventRecords);
                    if (jobs != null && jobs.Any())
                        BantchSaveEntityNoCommit(jobs);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (persons != null && persons.Any())
                    {
                        persons = persons.Where(t => t.USER_ID != null && !t.IS_DELETED).ToList();
                        this.BantchSaveEntityNoCommit(persons);
                    }
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (flows != null && flows.Any())
                        this.BantchSaveEntityNoCommit(flows);
                    if (measures != null && measures.Any())
                        this.BantchSaveEntityNoCommit(measures);
                    if (jobDetails != null && jobDetails.Any())
                        this.BantchSaveEntityNoCommit(jobDetails);
                    if (jobFlows != null && jobFlows.Any())
                        this.BantchSaveEntityNoCommit(jobFlows);
                    if (jobMeasures != null && jobMeasures.Any())
                        this.BantchSaveEntityNoCommit(jobMeasures);
                });
                return true;
            });
        }
        /// <summary>
        /// 返回作业活动记录和关键许可工作票
        /// <returns></returns>
        private void GetAutoNext(T_FO_PRE_SHIFT_MEETING_RECORD model, List<T_FO_PRE_SHIFT_MEETING_RECORD_USER> modelUsers, ref List<T_FO_JOB_EVENT_RECORD> eventRecords, ref List<T_FO_CRUCIAL_LICENSE_JOB> jobs, ref List<T_FM_NOTIFICATION_TASK> notices)
        {
            //取排班中所有人
            if (model != null && modelUsers != null && modelUsers.Any())
            {
                model.ORG_ID = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                //人员
                var userIds = modelUsers.Select(t => t.USER_ID).ToList();
                //找出所有岗位
                var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID), new BaseFilter(model.ORG_ID), "Nav_Person");
                var postionIds = users.Where(x => x.Nav_Person.POST_ID != null).Select(t => t.Nav_Person.POST_ID).Distinct().ToList();
                if (postionIds.Any())
                {
                    //岗位对应的作业环节ID
                    var links = this.GetEntities<T_HM_OPERATION_LINK_POST>(t => postionIds.Contains(t.POST_ID), new BaseFilter(model.ORG_ID), "Nav_OperationLink").ToList();
                    var linkIds = links.Select(m => m.OPERATION_LINK_ID).Distinct().ToList();
                    //作业库中取作业环节（周期为每日作业）
                    var operationTemps = this.GetEntities<T_HM_OPERATION_LINK>(t => linkIds.Contains(t.ID) && t.STATUS == (int)STATUSEnum.启用 && t.CYCLE_TYPE == HMCycleTypeEnum.Day, new BaseFilter(model.ORG_ID), new string[] { "Nav_WorkPermitType", "Nav_OperationStep", "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures" }).Distinct().ToList();
                    var operations = operationTemps.Where(x => x.Nav_OperationStep != null).GroupBy(t => new { t.Nav_OperationStep.NAME }).Select(w => w.OrderBy(m => m.CREATE_TIME).FirstOrDefault()).Distinct().ToList();
                    if (operations != null && operations.Any())
                    {
                        //岗位对应多个作业环节
                        foreach (var postId in postionIds)
                        {
                            var linkId = links.Where(t => t.POST_ID == postId).Select(m => m.OPERATION_LINK_ID).Distinct().ToList();
                            var operation = operations.Where(t => linkId.Contains(t.ID)).Distinct().ToList();
                            //多个作业环节判断关键许可一般
                            if (operation != null && operation.Any())
                            {
                                //许可作业、非许可的关键任务
                                var crucialAndLicenses = operation.Where(t => (t.Nav_WorkPermitType != null && t.Nav_WorkPermitType.NAME != "无") || (t.Nav_WorkPermitType != null && t.Nav_WorkPermitType.NAME == "无" && t.IS_IMPORTANT == (int)ISImportantEnum.是)).ToList();
                                //非许可非关键的一般任务
                                var ordinarys = operation.Where(t => (t.Nav_WorkPermitType == null || (t.Nav_WorkPermitType != null && t.Nav_WorkPermitType.NAME == "无")) && t.IS_IMPORTANT == (int)ISImportantEnum.否).Distinct().ToList();
                                //触发关键许可作业票
                                if (crucialAndLicenses != null && crucialAndLicenses.Any())
                                {
                                    //通知到该岗位的所有人
                                    var noticesUserIds = users.Where(t => t.Nav_Person.POST_ID == postId).Select(m => m.ID).Distinct().ToList();
                                    var UserNames = new List<string>();
                                    var user = users.Where(t => noticesUserIds.Contains(t.ID));
                                    foreach (var u in noticesUserIds)
                                    {
                                        var current = user.FirstOrDefault(t => t.ID == u);
                                        UserNames.Add(current?.NAME);
                                    }
                                    //触发关键许可作业票
                                    List<T_FO_CRUCIAL_LICENSE_JOB> job = InsertJob(model, crucialAndLicenses);
                                    if (job != null && job.Any())
                                    {
                                        //发消息
                                        List<T_FM_NOTIFICATION_TASK> notice = new List<T_FM_NOTIFICATION_TASK>();
                                        //发消息
                                        job.ForEach(t =>
                                        {
                                            if (t.OPERATION_STEP_ID != null)
                                            {
                                                var noticeTemp = NotificationTaskService.InsertUserNoticeTaskModels("关键许可作业票-" + t.Nav_OperationStep?.NAME + "(" + model.MEETING_TIME.Date.ToString("yyyyMMdd") + ")", t.ID, model.ORG_ID, noticesUserIds, UserNames, DateTime.Now,
                                               model.END_TIME, (int)FMNoticeTypeEnum.消息, "FO017");
                                                notice.AddRange(noticeTemp);
                                                t.Nav_OperationStep = null;
                                            }
                                        });
                                        notices.AddRange(notice);
                                        jobs.AddRange(job);
                                    }
                                }
                                if (ordinarys != null && ordinarys.Any())
                                {
                                    //通知到该岗位的所有人
                                    var noticesUserIds = users.Where(t => t.Nav_Person.POST_ID == postId).Select(m => m.ID).Distinct().ToList();
                                    var UserNames = new List<string>();
                                    var user = users.Where(t => noticesUserIds.Contains(t.ID));
                                    foreach (var u in noticesUserIds)
                                    {
                                        var current = user.FirstOrDefault(t => t.ID == u);
                                        UserNames.Add(current?.NAME);
                                    }
                                    //触发一般作业活动记录表
                                    List<T_FO_JOB_EVENT_RECORD> eventRecord = InsertEventRecord(model, ordinarys, noticesUserIds);
                                    if (eventRecord != null && eventRecord.Any())
                                    {
                                        List<T_FM_NOTIFICATION_TASK> notice = new List<T_FM_NOTIFICATION_TASK>();
                                        //发消息
                                        eventRecord.ForEach(t =>
                                        {
                                            if (t.OPERATION_STEP_ID != null)
                                            {
                                                var noticeTemp = NotificationTaskService.InsertUserNoticeTaskModels("作业活动记录表(一般作业)-" + t.Nav_OperationStep?.NAME + "(" + model.MEETING_TIME.Date.ToString("yyyyMMdd") + ")", t.ID, model.ORG_ID, noticesUserIds, UserNames, DateTime.Now,
                                                 model.END_TIME, (int)FMNoticeTypeEnum.消息, "FO015");
                                                notice.AddRange(noticeTemp);
                                                t.Nav_OperationStep = null;
                                            }
                                        });
                                        notices.AddRange(notice);
                                        eventRecords.AddRange(eventRecord);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 作业活动记录表（一般）
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private List<T_FO_JOB_EVENT_RECORD> InsertEventRecord(T_FO_PRE_SHIFT_MEETING_RECORD entity, List<T_HM_OPERATION_LINK> operations, List<Guid> noticesUserIds)
        {
            var records = new List<T_FO_JOB_EVENT_RECORD>();
            if (operations != null && operations.Any())
            {
                //取审批流水码
                var sysFilter = new SystemCodeFilter();
                sysFilter.CodeType = (int)PFCodeRuleType.一般作业活动记录表编号;
                sysFilter.Count = operations.Count;
                sysFilter.OrgId = entity.ORG_ID;
                var codes = CodeRuleService.NewGenSerial(sysFilter);
                var codeList = codes.Split(new char[] { ',' });
                var index = 0;
                foreach (var stepName in operations)
                {
                    //var operationFirst = operations.FirstOrDefault(t => t.Nav_SafeConfirms.Count > 0 && t.Nav_SafeMeasures.Count > 0 && t.Nav_DealMeasures.Count > 0);
                    T_FO_JOB_EVENT_RECORD record = new T_FO_JOB_EVENT_RECORD();
                    //主表
                    record.CODE = codeList[index];
                    record.ORG_ID = entity.ORG_ID;
                    record.OPERATION_STEP_ID = stepName?.OPERATION_STEP_ID;
                    record.Nav_OperationStep = stepName?.Nav_OperationStep;
                    record.SHIFT_MEETING_RECORD_ID = entity.ID;
                    record.JOB_DATE = entity.START_TIME + "-" + entity.END_TIME;
                    //作业人员表
                    if (noticesUserIds != null && noticesUserIds.Any())
                    {
                        record.Nav_JobEventPerson = new List<T_FO_JOB_EVENT_PERSON>();
                        noticesUserIds.ForEach(t =>
                        {
                            T_FO_JOB_EVENT_PERSON person = new T_FO_JOB_EVENT_PERSON();
                            person.USER_ID = t;
                            person.JOB_EVENT_RECORD_ID = record.ID;
                            person.ORG_ID = entity.ORG_ID;
                            record.Nav_JobEventPerson.Add(person);
                        });
                    }
                    //作业前安全确认
                    if (stepName != null && stepName.Nav_SafeConfirms != null && stepName.Nav_SafeConfirms.Any())
                    {
                        record.Nav_Details = new List<T_FO_JOB_EVENT_DETAIL>();
                        stepName.Nav_SafeConfirms.ForEach(t =>
                        {
                            T_FO_JOB_EVENT_DETAIL detail = new T_FO_JOB_EVENT_DETAIL();
                            detail.JOB_EVENT_RECORD_ID = record.ID;
                            detail.SafeConfirmsStr = t.NAME;
                            detail.IS_CONFIRM = false;
                            detail.ORG_ID = t.ORG_ID;
                            detail.NUM = t.NUM;
                            record.Nav_Details.Add(detail);
                        });
                    }
                    //作业流程及安全措施
                    if (stepName != null && stepName.Nav_SafeMeasures != null && stepName.Nav_SafeMeasures.Any())
                    {
                        record.Nav_Flow = new List<T_FO_JOB_EVENT_FLOW>();
                        stepName.Nav_SafeMeasures.ForEach(t =>
                        {
                            T_FO_JOB_EVENT_FLOW detail = new T_FO_JOB_EVENT_FLOW();
                            detail.JOB_EVENT_RECORD_ID = record.ID;
                            detail.SafeMeasuresStr = t.NAME;
                            detail.IS_CONFIRM = false;
                            detail.ORG_ID = t.ORG_ID;
                            detail.NUM = t.NUM;
                            record.Nav_Flow.Add(detail);
                        });
                    }
                    //作业后处理措施
                    if (stepName != null && stepName.Nav_DealMeasures != null && stepName.Nav_DealMeasures.Any())
                    {
                        record.Nav_Measure = new List<T_FO_JOB_EVENT_MEASURE>();
                        stepName.Nav_DealMeasures.ForEach(t =>
                        {
                            T_FO_JOB_EVENT_MEASURE detail = new T_FO_JOB_EVENT_MEASURE();
                            detail.JOB_EVENT_RECORD_ID = record.ID;
                            detail.DealMeasuresStr = t.NAME;
                            detail.IS_CONFIRM = false;
                            detail.ORG_ID = t.ORG_ID;
                            detail.NUM = t.NUM;
                            record.Nav_Measure.Add(detail);
                        });
                    }
                    records.Add(record);
                    index++;
                }
            }
            return records;
        }
        /// <summary>
        /// 关键许可作业票
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private List<T_FO_CRUCIAL_LICENSE_JOB> InsertJob(T_FO_PRE_SHIFT_MEETING_RECORD entity, List<T_HM_OPERATION_LINK> operations)
        {
            var jobs = new List<T_FO_CRUCIAL_LICENSE_JOB>();
            if (operations != null && operations.Any())
            {
                //取审批流水码
                var sysFilter = new SystemCodeFilter();
                sysFilter.CodeType = (int)PFCodeRuleType.关键许可作业票编号;
                sysFilter.Count = operations.Count;
                sysFilter.OrgId = entity.ORG_ID;
                var codes = CodeRuleService.NewGenSerial(sysFilter);
                var codeList = codes.Split(new char[] { ',' });
                var index = 0;
                foreach (var operation in operations)
                {
                    T_FO_CRUCIAL_LICENSE_JOB job = new T_FO_CRUCIAL_LICENSE_JOB();
                    //主表
                    job.CODE = codeList[index];
                    job.ORG_ID = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                    job.APPLY_USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    job.SHIFT_MEETING_RECORD_ID = entity.ID;
                    job.IS_AUTO = (int)ISImportantEnum.是;
                    job.OPERATION_STEP_ID = operation?.OPERATION_STEP_ID;
                    job.Nav_OperationStep = operation?.Nav_OperationStep;
                    job.AUDIT_LEVEL = operation.AUDIT_LEVEL;
                    //作业前安全确认
                    if (operation != null && operation.Nav_SafeConfirms != null && operation.Nav_SafeConfirms.Any())
                    {
                        job.Nav_SafeConfirms = new List<T_FO_CRUCIAL_LICENSE_SAFE_CONFIRM>();
                        operation.Nav_SafeConfirms.ForEach(t =>
                        {
                            T_FO_CRUCIAL_LICENSE_SAFE_CONFIRM detail = new T_FO_CRUCIAL_LICENSE_SAFE_CONFIRM();
                            detail.CRUCIAL_LICENSE_JOB_ID = job.ID;
                            detail.NAME = t.NAME;
                            detail.ORG_ID = t.ORG_ID;
                            detail.NUM = t.NUM;
                            job.Nav_SafeConfirms.Add(detail);
                        });
                    }
                    //作业流程及安全措施
                    if (operation != null && operation.Nav_SafeMeasures != null && operation.Nav_SafeMeasures.Any())
                    {
                        job.Nav_SafeMeasures = new List<T_FO_CRUCIAL_LICENSE_SAFE_MEASURE>();
                        operation.Nav_SafeMeasures.ForEach(t =>
                        {
                            T_FO_CRUCIAL_LICENSE_SAFE_MEASURE detail = new T_FO_CRUCIAL_LICENSE_SAFE_MEASURE();
                            detail.CRUCIAL_LICENSE_JOB_ID = job.ID;
                            detail.NAME = t.NAME;
                            detail.ORG_ID = t.ORG_ID;
                            detail.NUM = t.NUM;
                            job.Nav_SafeMeasures.Add(detail);
                        });
                    }
                    //作业后处理措施
                    if (operation != null && operation.Nav_DealMeasures != null && operation.Nav_DealMeasures.Any())
                    {
                        job.Nav_DealMeasures = new List<T_FO_CRUCIAL_LICENSE_DEAL_MEASURE>();
                        operation.Nav_DealMeasures.ForEach(t =>
                        {
                            T_FO_CRUCIAL_LICENSE_DEAL_MEASURE detail = new T_FO_CRUCIAL_LICENSE_DEAL_MEASURE();
                            detail.CRUCIAL_LICENSE_JOB_ID = job.ID;
                            detail.NAME = t.NAME;
                            detail.ORG_ID = t.ORG_ID;
                            detail.NUM = t.NUM;
                            job.Nav_DealMeasures.Add(detail);
                        });
                    }
                    jobs.Add(job);
                    index++;
                }
            }
            return jobs;
        }
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_FO_PRE_SHIFT_MEETING_RECORD> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_FO_PRE_SHIFT_MEETING_RECORD>();
            var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var admiId = this.GetEntity<T_FM_USER>(t => t.CODE.Contains("admin") && t.ENABLE_STATUS == 0)?.ID;
            var currDep = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value;
            var AH = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人" || t.Nav_ApproveRole.NAME == "安环部安全员");
            Guid? AHDepartment = Guid.Empty;
            if (AH != null)
            {
                AHDepartment = AH.DEPARTMENT_ID;
            }
            if (loginUserId == null || loginUserId == admiId || currDep == AHDepartment)
            {
                result = this.GetOrderPageEntities<T_FO_PRE_SHIFT_MEETING_RECORD>(null, pageFilter);
            }
            else
            {
                var loginDepartmentId = this.GetEntity<T_FM_USER>(t => t.ID == loginUserId && t.ENABLE_STATUS == 0)?.DEPARTMENT_ID;
                List<Guid> departmentId = new List<Guid>();
                departmentId.Add((Guid)loginDepartmentId);
                List<Guid> departmentIds = new List<Guid>() { currDep };
                DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, departmentId, ref departmentIds);
                if (departmentIds != null && departmentIds.Any())
                {
                    result = this.GetOrderPageEntities<T_FO_PRE_SHIFT_MEETING_RECORD>(t => (departmentIds.Contains((Guid)t.Nav_Team.DEPARTMENT_ID)), pageFilter);//|| dataIds.Contains(t.ID)
                }
                else
                    result.Data = null;
            }
            return result;
        }
    }
}
