using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.IServices;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using APT.BaseData.Domain.IServices.FM;
using APT.MS.Domain.Enums;
using APT.MS.Domain.Entities.HM;
using InfluxData.Net.InfluxDb.Models.Responses;
using NPOI.SS.Formula.Functions;
using APT.BaseData.Services.DomainServices;
using log4net.Filter;
using Castle.Core.Internal;
using APT.WebApi.Models;

namespace APT.PP.WebApi.Controllers.Api.PP
{
    /// <summary>
    /// 生成班前会议
    /// </summary>
    [Route("api/PP/FOController")]
    [TypeFilter(typeof(CustomActionFilterAttribute))]
    public class FOController : AuthorizeApiController<T_FM_BASE_CONFIG>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }

        public FOController(IFMNotificationTaskService notificationTaskService, IPFCodeRuleService codeRuleService)
        {
            NotificationTaskService = notificationTaskService;
            this.CodeRuleService = codeRuleService;
        }
        /// <summary>
        /// 生成班前会议
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("CreatePreShiftMeeting")]
        public JsonActionResult<bool> CreatePreShiftMeeting([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                BaseFilter teamFilter = new BaseFilter(filter.GetOrgId());
                var noFinishTeamActivitys = GetEntities<T_FM_NOTIFICATION_TASK>(t => t.NOTICE_STATUS == 0 && t.SOURCE_FORMCODE == "FO010"&&t.CREATE_TIME>DateTime.Now.AddMonths(-1), teamFilter);
                var noFinishTeamActivityIDs = noFinishTeamActivitys.Select(t => t.SOURCE_DATA_ID);
                var teamActivitys = GetEntities<T_FO_TEAM_ACTIVITY>(t => noFinishTeamActivityIDs.Contains(t.ID)&&t.TA_STATUS== (int)FOTeamActivityState.已归档, teamFilter);
                var finishedTeamActivitys = teamActivitys.Select(t => t.ID);
                var updateFinishTeamActivity = noFinishTeamActivitys.Where(t => finishedTeamActivitys.Contains((Guid)t.SOURCE_DATA_ID));
                foreach(var item in updateFinishTeamActivity)
                {
                    item.NOTICE_STATUS = 1;
                }
                BantchUpdateEntity(updateFinishTeamActivity);

                List<T_FO_PRE_SHIFT_MEETING_RECORD> listRecord = new List<T_FO_PRE_SHIFT_MEETING_RECORD>();
                List<T_FO_PRE_SHIFT_MEETING_RECORD_USER> listUser = new List<T_FO_PRE_SHIFT_MEETING_RECORD_USER>();
                DateTime dt = DateTime.Now;
                if (filter.Parameter1 != null)
                {
                    dt = DateTime.Parse(filter.Parameter1);
                }
                //dt = Convert.ToDateTime("2022-03-01 23:00:00");
                DateTime minTime = dt.AddMinutes(0);
                DateTime maxTime = dt.AddMinutes(60);
                var classFilter = new BaseFilter(filter.GetOrgId());
                classFilter.Include = new string[] { "Nav_Team.Nav_ChargePerson.Nav_User", "Nav_DepartmentSchedulingDetail.Nav_Person.Nav_User" };
                var shiftClassList = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING>(s => s.START_TIME > minTime && s.START_TIME <= maxTime && !s.RUN_STATUS && s.START_TIME != s.END_TIME, classFilter).ToList();
                var schedullingIds = shiftClassList.Select(t => t.ID).Distinct().ToList();
                var baseFilter = new BaseFilter(filter.GetOrgId());
                var noticeTitles = new List<string>();
                var noticeUserIds = new List<Guid>();
                var noticeUserNames = new List<string>();
                var noticeDataIds = new List<Guid>();
                if (shiftClassList.Count > 0)
                {
                    foreach (var shift in shiftClassList)
                    {
                        shift.RUN_STATUS = true;
                        //查出当前班组
                        var currentTeam = shift.Nav_Team;
                        //当前班组的人员
                        var currentTeamUsers = shift.Nav_DepartmentSchedulingDetail;

                        if (currentTeamUsers.Count() > 0)
                        {
                            T_FO_PRE_SHIFT_MEETING_RECORD record = new T_FO_PRE_SHIFT_MEETING_RECORD(); ;
                            record.ID = Guid.NewGuid();
                            record.ORG_ID = filter.GetOrgId();
                            record.CLASS_ID = shift.CLASS_ID;
                            record.DEPARTMENT_ID = shift.DEPARTMENT_ID;
                            record.TEAM_ID = shift.TEAM_ID;
                            record.USER_ID = currentTeam.Nav_ChargePerson.Nav_User.ID;
                            record.START_TIME = shift.START_TIME;
                            record.END_TIME = shift.END_TIME;
                            record.NAME = dt.Date.ToString("yyyyMMdd") + currentTeam.NAME + "-" + "班前会议";
                            record.DEPARTMENT_SCHEDULING_ID = shift.ID;
                            foreach (var person in currentTeamUsers)
                            {
                                if (person.Nav_Person.Nav_User != null && person.Nav_Person.Nav_User.ENABLE_STATUS == 0)
                                {
                                    T_FO_PRE_SHIFT_MEETING_RECORD_USER rUser = new T_FO_PRE_SHIFT_MEETING_RECORD_USER();
                                    rUser.ORG_ID = filter.OrgId;
                                    rUser.PRE_SHIFT_MEETING_RECORD_ID = record.ID;
                                    rUser.USER_ID = person.Nav_Person.Nav_User.ID;
                                    listUser.Add(rUser);
                                }
                            }
                            listRecord.Add(record);
                            noticeTitles.Add(dt.Date.ToString("yyyyMMdd") + currentTeam.NAME + "-" + "班前会议");
                            noticeDataIds.Add(record.ID);
                            noticeUserIds.Add(currentTeam.Nav_ChargePerson.Nav_User.ID);
                            noticeUserNames.Add(currentTeam.Nav_ChargePerson.Nav_User.NAME);
                        }
                    }
                    NotificationTaskService.SendNotificationTask(noticeTitles, noticeDataIds, filter.GetOrgId(), noticeUserIds, noticeUserNames, shiftClassList[0].START_TIME.AddHours(-1), shiftClassList[0].START_TIME.AddHours(1), (int)FMNoticeTypeEnum.消息, "FO003", () =>
                    {
                        if (listRecord.Any())
                            this.BantchAddEntityNoCommit(listRecord);
                        if (listUser.Any())
                            this.BantchAddEntityNoCommit(listUser);
                        if (shiftClassList.Any())
                            this.BantchUpdateEntityNoCommit(shiftClassList, "RUN_STATUS");
                    });
                }
                return true;
            });
        }


        /// <summary>
        /// 班组安全活动记录
        /// </summary>
        [HttpPost, Route("CreateTeamActivity")]
        public JsonActionResult<bool> CreateTeamActivity([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var sync = GetEntity<T_FM_SYNC_TASK>(t => t.INTERFACE_ADDRESS == "PP/FOController/CreateTeamActivity");
                if (sync != null)
                {
                    var nextDate = sync.UPDATE_SUCCES_TIME.Value.AddDays(6);
                    if (sync.UPDATE_SUCCES_TIME == null || DateTime.Now > nextDate)
                    {
                        sync.UPDATE_SUCCES_TIME = DateTime.Now;
                    }
                    else
                    {
                        return true;
                    }
                }
                var baseFilter = new BaseFilter(filter.GetOrgId());
                baseFilter.SelectField = new string[] { "NAME", "Nav_ChargePerson.Nav_User" };   //指定字段，包括导航属性
                var teams = this.GetEntities<T_FM_TEAM>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.CHARGE_PERSON_ID!=null, baseFilter).ToList();
                var teamActivityRecords = GetEntities<T_FO_TEAM_ACTIVITY>(t => t.ACTIVITY_TIME.Year == DateTime.Now.Year && t.ACTIVITY_TIME.Month == DateTime.Now.Month, new BaseFilter(filter.GetOrgId()));

                if (teams.Count > 0)    //判断是否有记录
                {

                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.班组安全记录;
                    sysFilter.Count = teams.Count;
                    sysFilter.OrgId = filter.GetOrgId();
                    var codes = CodeRuleService.NewGenSerial(sysFilter);
                    var codeList = codes.Split(new char[] { ',' });
                    var index = 0;
                    var noticeTitles = new List<string>();
                    var noticeUserIds = new List<Guid>();
                    var noticeDataIds = new List<Guid>();
                    var noticeUserNames = new List<string>();
                    List<T_FO_TEAM_ACTIVITY> records = new List<T_FO_TEAM_ACTIVITY>();
                    List<T_FO_TEAM_ACTIVITY_USER> listUser = new List<T_FO_TEAM_ACTIVITY_USER>();

                    foreach (var rs in teams)   //按班组记录集进行循环
                    {
                        var teamActivityRecord = teamActivityRecords.Where(t => t.TEAM_ID == rs.ID);
                        //2023-6-8 一个月只生成4次记录
                        if ((teamActivityRecord.Count() >= 4))
                        {
                            continue;
                        }
                        //班组安全活动记录主表赋值-----------------------------------------------------------------
                        T_FO_TEAM_ACTIVITY record = new T_FO_TEAM_ACTIVITY();
                        record.ID = Guid.NewGuid();
                        record.ORG_ID = filter.GetOrgId();
                        record.CODE = codeList[index];
                        record.TITLE = rs.NAME + "-班组安全活动";
                        record.ADDRESS = "";
                        record.NOTE_AKER_ID = rs.Nav_ChargePerson.Nav_User.ID;
                        record.TEAM_ID = rs.ID;
                        record.ACTIVITY_CONTENT = "";
                        record.DURATION = "";
                        record.TA_STATUS = 0;
                        index++;

                        //默认将班组下面全部人员写入班组安全活动用户子表----------------------------------------

                        var userFilter = new BaseFilter(filter.GetOrgId());
                        userFilter.Include = new string[] { "Nav_Person.Nav_User" };
                        var teamUsers = this.GetEntities<T_FM_TEAM_PERSON>(t => t.TEAM_ID == rs.ID, userFilter).ToList();
                        if (teamUsers.Count() > 0)
                        {
                            foreach (var rsUsers in teamUsers)
                            {
                                T_FO_TEAM_ACTIVITY_USER rUser = new T_FO_TEAM_ACTIVITY_USER();
                                rUser.ID = Guid.NewGuid();
                                rUser.ORG_ID = filter.OrgId;
                                rUser.TEAM_ACTIVITY_ID = record.ID;
                                rUser.USER_ID = rsUsers.Nav_Person.Nav_User.ID;
                                rUser.ATTEND_STATUS = 1;
                                rUser.SIGN_IN_STATUS = 0;
                                listUser.Add(rUser);
                            }
                        }

                        //写消息表赋值-----------------------------------------------------------
                        noticeTitles.Add(rs.NAME + " 班组安全活动记录表");
                        noticeUserIds.Add(rs.Nav_ChargePerson.Nav_User.ID);     //关联到T_FM_USER表的登录人
                        noticeUserNames.Add(rs.Nav_ChargePerson.Nav_User.CODE + " " + rs.Nav_ChargePerson.Nav_User.NAME);
                        noticeDataIds.Add(record.ID);
                        records.Add(record);
                    }
                    //写消息表---------------------------------------------------------------
                    NotificationTaskService.SendNotificationTask(noticeTitles, noticeDataIds, filter.GetOrgId(), noticeUserIds, noticeUserNames, DateTime.Parse(DateTime.Now.ToShortDateString() + " 08:00:00"), DateTime.Parse(DateTime.Now.AddDays(6).ToShortDateString() + " 23:59:59"), 0, "FO010", () =>
                    {
                        this.BantchAddEntityNoCommit(records);             //写入班组安全活动记录主表
                        this.BantchAddEntityNoCommit(listUser);     //批量写入班组安全活动记录人员子表
                        UpdateEntityNoCommit(sync);
                    });
                }
                return true;
            });
        }


        /// <summary>
        /// 创建岗位当班记录
        /// </summary>
        [HttpPost, Route("CreateCurrentClassRecord")]
        public JsonActionResult<bool> CreateCurrentClassRecord([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                //消息
                List<T_FO_CURRENT_CLASS_RECORD> listRecord = new List<T_FO_CURRENT_CLASS_RECORD>();
                List<T_FO_CURRENT_CLASS_RECORD_USER> listUser = new List<T_FO_CURRENT_CLASS_RECORD_USER>();
                List<T_FM_NOTIFICATION_TASK> sendNotices = new List<T_FM_NOTIFICATION_TASK>();

                //获取班组排班计划(结束时间前一小时) 半小时触发判断一次
                DateTime dt = DateTime.Now;
                if (filter.Parameter1 != null)
                {
                    dt = DateTime.Parse(filter.Parameter1);
                }
                //dt = Convert.ToDateTime("2022-03-03 07:10:00");
                DateTime minTime = dt.AddMinutes(0);
                DateTime maxTime = dt.AddMinutes(90);
                string todayShortDate = dt.ToShortDateString();
                DateTime shortToday = Convert.ToDateTime(todayShortDate + " 00:00:00");
                DateTime longToday = shortToday.AddDays(2);
                var baseFilter = new BaseFilter(filter.GetOrgId());
                var sheduleFilter = new BaseFilter(filter.GetOrgId());
                List<DataOrder> dataorder = new List<DataOrder>();
                DataOrder do1 = new DataOrder();
                do1.Field = "START_TIME";
                dataorder.Add(do1);
                sheduleFilter.Orders = dataorder;
                //取出最近要下班的班组
                var shiftClassList = GetEntities<T_FM_DEPARTMENT_SCHEDULING>(t => t.END_TIME > minTime && t.END_TIME < maxTime && t.SHIFT_CLASS_RUN_STATUS == false && t.START_TIME != t.END_TIME, sheduleFilter, new string[] { "Nav_Class", "Nav_DepartMent", "Nav_DepartmentCalendarConfig", "Nav_Team.Nav_ChargePerson.Nav_User", "Nav_DepartmentSchedulingDetail.Nav_Person.Nav_User", "Nav_DepartmentSchedulingDetail.Nav_Person.Nav_Post" }).ToList();
                try
                {
                    if (shiftClassList != null && shiftClassList.Count > 0)
                    {

                        foreach (var shift in shiftClassList)
                        {
                            shift.SHIFT_CLASS_RUN_STATUS = true;
                        }
                        //取出未来2天所有的排班
                        var shiftClassListAll = GetOrderEntities<T_FM_DEPARTMENT_SCHEDULING>(t => t.START_TIME >= dt && t.DATE_TIME < longToday && t.START_TIME != t.END_TIME, sheduleFilter, new string[] { "Nav_DepartmentCalendarConfig", "Nav_DepartmentCalendarConfig" }).ToList();
                        Guid nextClassID = Guid.Empty;
                        foreach (var shiftClass in shiftClassList)
                        {
                            //循环排班,按每个班取出这个班有哪些人
                            var teamUsers = shiftClass.Nav_DepartmentSchedulingDetail;
                            //取出该班所有人的岗位信息
                            var teamPostIdAll = teamUsers.Where(i => i.Nav_Person.POST_ID != null).Select(i => i.Nav_Person.Nav_Post.ID).Distinct().ToList();
                            var teamPostAll = teamUsers.Where(i => i.Nav_Person.POST_ID != null).Select(i => i.Nav_Person.Nav_Post).ToList();


                            //判断is_handover,true的话记录下个班班组的id
                            if (shiftClass.Nav_DepartmentCalendarConfig.IS_HANDOVER)
                            {
                                var nextClassTemp = shiftClassListAll.FirstOrDefault(t => t.DEPARTMENT_ID == shiftClass.DEPARTMENT_ID && t.START_TIME >= shiftClass.END_TIME && t.Nav_DepartmentCalendarConfig.IS_HANDOVER == true && t.Nav_DepartmentCalendarConfig.CALENDAR_ID == shiftClass.Nav_DepartmentCalendarConfig.CALENDAR_ID);
                                if (nextClassTemp != null)
                                {
                                    nextClassID = nextClassTemp.ID;
                                }
                            }
                            if (teamPostIdAll != null && teamPostIdAll.Count() > 0)
                            {
                                //按岗位循环
                                foreach (var teamPost in teamPostIdAll)
                                {
                                    var postUsers = teamUsers.Where(i => i.Nav_Person.POST_ID == teamPost).ToList();
                                    var dataId = Guid.NewGuid();
                                    T_FO_CURRENT_CLASS_RECORD currentClassRecord = new T_FO_CURRENT_CLASS_RECORD();
                                    currentClassRecord.ID = dataId;
                                    currentClassRecord.ORG_ID = filter.GetOrgId();
                                    currentClassRecord.DEPARTMENT_POST_ID = teamPost;
                                    currentClassRecord.DEPARTMENT_ID = shiftClass.DEPARTMENT_ID;
                                    currentClassRecord.CLASS_ID = shiftClass.CLASS_ID;
                                    currentClassRecord.RECORD_DATE = shiftClass.END_TIME;
                                    var postName = teamPostAll.FirstOrDefault(i => i.ID == teamPost);
                                    currentClassRecord.NAME = DateTime.Now.Date.ToString("yyyyMMdd") + shiftClass.Nav_Team.NAME + "-" + postName.NAME + "当班工作记录";
                                    currentClassRecord.CHARGE_USER_ID = shiftClass.Nav_Team.Nav_ChargePerson.Nav_User.ID;
                                    currentClassRecord.NEXT_CLASS_TEAM_ID = nextClassID;
                                    currentClassRecord.CLASS_TEAM_ID = (Guid)shiftClass.TEAM_ID;
                                    currentClassRecord.SUPPLIES_STATUS = (int)FOShiftRecordStatusEnum.正常;
                                    currentClassRecord.SUPPLIES_USED = (int)WFDisableStatusEnum.是;
                                    listRecord.Add(currentClassRecord);
                                    foreach (var post in postUsers)
                                    {
                                        if (post.Nav_Person.Nav_User != null && post.Nav_Person.Nav_User.ENABLE_STATUS == 0)
                                        {
                                            T_FO_CURRENT_CLASS_RECORD_USER currentClassRecordUser = new T_FO_CURRENT_CLASS_RECORD_USER();
                                            currentClassRecordUser.ORG_ID = filter.GetOrgId();
                                            currentClassRecordUser.CURRENT_CLASS_RECORD_ID = currentClassRecord.ID;
                                            currentClassRecordUser.USER_ID = post.Nav_Person.Nav_User.ID;
                                            listUser.Add(currentClassRecordUser);
                                            //发送通知消息
                                            var sendNotice = NotificationTaskService.InsertUserNoticeTaskModel(DateTime.Now.Date.ToString("yyyyMMdd") + shiftClass.Nav_Team.NAME + "-" + postName.NAME + " 当班工作记录",
                                                currentClassRecord.ID, filter.GetOrgId(), post.Nav_Person.Nav_User.ID, post.Nav_Person.Nav_User.NAME, dt, currentClassRecord.RECORD_DATE.AddHours(1.5), 1, "FO005");
                                            sendNotices.Add(sendNotice);
                                        }
                                    }
                                }
                            }
                        }
                        UnifiedCommit(() =>
                        {
                            if (sendNotices.Any())
                                this.BantchAddEntityNoCommit(sendNotices);
                            if (listRecord.Any())
                                this.BantchAddEntityNoCommit(listRecord);
                            if (listUser.Any())
                                this.BantchAddEntityNoCommit(listUser);
                            if (shiftClassList.Any())
                                this.BantchUpdateEntityNoCommit(shiftClassList, "SHIFT_CLASS_RUN_STATUS");
                        });
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            });

        }
        /// <summary>
        /// 根据每日的班前会议、人员的岗位触发每日作业
        /// </summary>
        [HttpPost, Route("CreateDailyJobs")]
        public JsonActionResult<bool> CreateDailyJobs([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var jobs = new List<T_FO_CRUCIAL_LICENSE_JOB>();
                var records = new List<T_FO_JOB_EVENT_RECORD>();
                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>();
                DateTime dt = DateTime.Now;
                //DateTime maxTime = dt.AddMinutes(-30);
                var newFilter = new BaseFilter(filter.OrgId);
                //newFilter.SelectField = new List<string> { "ID", "START_TIME", "IS_RUN", "Nav_Users" };
                //newFilter.Include = new string[] { "Nav_Users" };
                //取班前会议 开始时间等于今天且开会时间1小时后 未跑批的数据 && 
                var preShiftMeetings = this.GetEntities<T_FO_PRE_SHIFT_MEETING_RECORD>(t => t.MEETING_TIME.Date == dt.Date && t.START_TIME.TimeOfDay < dt.TimeOfDay && t.IS_RUN == 0 && t.PRE_MEETING_STATUS != 0, new BaseFilter(filter.OrgId), new string[] { "Nav_Users" });
                if (preShiftMeetings != null && preShiftMeetings.Any())
                {
                    preShiftMeetings.ForEach(t => { t.IS_RUN = WFDisableStatusEnum.是; });
                    //提前取出所有人员，所有岗位，所有作业
                    var allUserIds = preShiftMeetings.SelectMany(t => t.Nav_Users).Select(m => m.USER_ID).Distinct().ToList();
                    //岗位
                    newFilter.SelectField = new List<string> { "ID", "NAME", "Nav_Person" };
                    var userList = this.GetEntities<T_FM_USER>(t => allUserIds.Contains(t.ID) && t.ENABLE_STATUS == 0, newFilter);
                    var allPostIds = userList.Where(t => t.Nav_Person != null).Select(m => m.Nav_Person.POST_ID).Distinct().ToList();
                    //所有岗位对应的每日作业
                    newFilter.SelectField = new List<string> { "POST_ID", "OPERATION_LINK_ID" };
                    var operationLinks = this.GetEntities<T_HM_OPERATION_LINK_POST>(t => allPostIds.Contains(t.POST_ID), newFilter);
                    var linkIds = operationLinks.Select(t => t.OPERATION_LINK_ID).Distinct().ToList();
                    //每日作业
                    newFilter.SelectField = new List<string> { "ID", "OPERATION_STEP_ID", "IS_IMPORTANT", "Nav_OperationStep", "Nav_WorkPermitType", "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures" };
                    var links = this.GetEntities<T_HM_OPERATION_LINK>(t => linkIds.Contains(t.ID) && t.CYCLE_TYPE == HMCycleTypeEnum.Day, newFilter);
                    foreach (var pre in preShiftMeetings)
                    {
                        //当前班前会的人员
                        var userTempIds = pre.Nav_Users.Select(t => t.USER_ID).Distinct().ToList();
                        //人员岗位
                        var postTempIds = userList.Where(t => userTempIds.Contains(t.ID) && t.Nav_Person != null).Select(m => m.Nav_Person.POST_ID).Distinct().ToList();
                        //遍历所有岗位，将岗位对应的作业发给对应的人员上
                        if (postTempIds != null && postTempIds.Any())
                        {
                            foreach (var item in postTempIds)
                            {
                                //岗位下的所有作业
                                var opLinkIds = operationLinks.Where(t => t.POST_ID == item).Select(m => m.OPERATION_LINK_ID).Distinct().ToList();
                                var stepIds = links.Where(t => opLinkIds.Contains(t.ID)).Select(m => m.OPERATION_STEP_ID).Distinct().ToList();
                                //岗位下的所有人
                                var userIds = userList.Where(t => userTempIds.Contains(t.ID) && t.Nav_Person != null && t.Nav_Person.POST_ID == item).Select(m => m.ID).Distinct().ToList();
                                List<string> userNames = new List<string>();
                                foreach (var user in userIds)
                                {
                                    var first = userList.FirstOrDefault(t => t.ID == user);
                                    userNames.Add(first.NAME);
                                }
                                //循环每个作业发给所有人
                                if (stepIds != null && stepIds.Any())
                                {
                                    foreach (var step in stepIds)
                                    {
                                        //判断是关键作业还是一般作业
                                        var link = links.FirstOrDefault(t => opLinkIds.Contains(t.ID) && t.OPERATION_STEP_ID == step);
                                        //许可作业、非许可的关键任务
                                        if (link != null && (link.Nav_WorkPermitType != null && link.Nav_WorkPermitType.NAME != "无") || (link.Nav_WorkPermitType != null && link.Nav_WorkPermitType.NAME == "无" && link.IS_IMPORTANT == (int)ISImportantEnum.是))
                                        {
                                            //取审批流水码
                                            var sysFilter = new SystemCodeFilter();
                                            sysFilter.CodeType = (int)PFCodeRuleType.关键许可作业票编号;
                                            sysFilter.Count = 1;
                                            sysFilter.OrgId = link.ORG_ID;
                                            var codes = CodeRuleService.NewGenSerial(sysFilter);
                                            var codeList = codes.Split(new char[] { ',' });
                                            T_FO_CRUCIAL_LICENSE_JOB job = new T_FO_CRUCIAL_LICENSE_JOB();
                                            //主表
                                            job.CODE = codeList[0];
                                            job.ORG_ID = link.ORG_ID;
                                            job.APPLY_USER_ID = userIds.FirstOrDefault();
                                            job.IS_AUTO = (int)ISImportantEnum.是;
                                            job.OPERATION_STEP_ID = link.OPERATION_STEP_ID;
                                            job.AUDIT_LEVEL = link.AUDIT_LEVEL;
                                            jobs.Add(job);
                                            //作业前安全确认
                                            if (link != null && link.Nav_SafeConfirms != null && link.Nav_SafeConfirms.Any())
                                            {
                                                link.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;
                                                    jobDetails.Add(detail);
                                                });
                                            }
                                            //作业流程及安全措施
                                            if (link != null && link.Nav_SafeMeasures != null && link.Nav_SafeMeasures.Any())
                                            {
                                                link.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;
                                                    jobFlows.Add(detail);
                                                });
                                            }
                                            //作业后处理措施
                                            if (link != null && link.Nav_DealMeasures != null && link.Nav_DealMeasures.Any())
                                            {
                                                link.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;
                                                    jobMeasures.Add(detail);
                                                });
                                            }
                                            var noticeTemp = NotificationTaskService.InsertUserNoticeTaskModels("关键许可作业票 - " + link?.Nav_OperationStep?.NAME + "(" + dt.Date.ToString("yyyyMMdd") + ")", job.ID, link.ORG_ID, userIds, userNames, DateTime.Now,
                                            DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO017");
                                            notices.AddRange(noticeTemp);
                                        }
                                        //非许可非关键的一般任务
                                        if (link != null && (link.Nav_WorkPermitType == null || (link.Nav_WorkPermitType != null && link.Nav_WorkPermitType.NAME == "无")) && link.IS_IMPORTANT == (int)ISImportantEnum.否)
                                        {
                                            //取审批流水码
                                            var sysFilter = new SystemCodeFilter();
                                            sysFilter.CodeType = (int)PFCodeRuleType.一般作业活动记录表编号;
                                            sysFilter.Count = 1;
                                            sysFilter.OrgId = link.ORG_ID;
                                            var codes = CodeRuleService.NewGenSerial(sysFilter);
                                            var codeList = codes.Split(new char[] { ',' });
                                            T_FO_JOB_EVENT_RECORD record = new T_FO_JOB_EVENT_RECORD();
                                            //主表
                                            record.CODE = codeList[0];
                                            record.ORG_ID = link.ORG_ID;
                                            record.OPERATION_STEP_ID = link.OPERATION_STEP_ID;
                                            record.JOB_DATE = DateTime.Now.Date.ToString();
                                            records.Add(record);
                                            //作业人员表
                                            if (userIds != null && userIds.Any())
                                            {
                                                userIds.ForEach(t =>
                                                {
                                                    if (t != null)
                                                    {
                                                        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 = link.ORG_ID;
                                                        persons.Add(person);
                                                    }
                                                });
                                            }
                                            //作业前安全确认
                                            if (link != null && link.Nav_SafeConfirms != null && link.Nav_SafeConfirms.Any())
                                            {
                                                link.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;
                                                    details.Add(detail);
                                                });
                                            }
                                            //作业流程及安全措施
                                            if (link != null && link.Nav_SafeMeasures != null && link.Nav_SafeMeasures.Any())
                                            {
                                                link.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;
                                                    flows.Add(detail);
                                                });
                                            }
                                            //作业后处理措施
                                            if (link != null && link.Nav_DealMeasures != null && link.Nav_DealMeasures.Any())
                                            {
                                                link.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;
                                                    measures.Add(detail);
                                                });
                                            }
                                            var noticeTemp = NotificationTaskService.InsertUserNoticeTaskModels("作业活动记录表(一般作业)-" + link?.Nav_OperationStep?.NAME + "(" + dt.Date.ToString("yyyyMMdd") + ")", record.ID, link.ORG_ID, userIds, userNames, DateTime.Now,
                                            DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO015");
                                            notices.AddRange(noticeTemp);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                UnifiedCommit(() =>
                {
                    if (preShiftMeetings != null && preShiftMeetings.Any())
                        BantchSaveEntityNoCommit(preShiftMeetings);
                    if (records != null && records.Any())
                        BantchSaveEntityNoCommit(records);
                    if (jobs != null && jobs.Any())
                        BantchSaveEntityNoCommit(jobs);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (persons != null && persons.Any())
                        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>
        /// 关键许可工作票子表数据同步
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("ExecuteJob")]
        public JsonActionResult<bool> ExecuteJob([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var dt = DateTime.Now.Date.AddDays(3);
                //最近一天
                DateTime week = dt.AddDays(-8).Date;
                if (!string.IsNullOrEmpty(filter.Parameter1))
                {
                    if (!filter.Parameter1.Contains("|"))
                        throw new Exception("必须传入开始日期和结束日期，以|符号分隔");
                    var temp = filter.Parameter1.Split("|");
                    if (temp[1].Length == 0)
                        throw new Exception("必须传入开始日期和结束日期，以|符号分隔");
                    week = DateTime.Parse(temp[0]);
                    dt = DateTime.Parse(temp[1]);
                }
                List<T_FO_CRUCIAL_LICENSE_SAFE_CONFIRM> confirmList = new List<T_FO_CRUCIAL_LICENSE_SAFE_CONFIRM>();
                List<T_FO_CRUCIAL_LICENSE_SAFE_MEASURE> measureList = new List<T_FO_CRUCIAL_LICENSE_SAFE_MEASURE>();
                List<T_FO_CRUCIAL_LICENSE_DEAL_MEASURE> dealList = new List<T_FO_CRUCIAL_LICENSE_DEAL_MEASURE>();
                List<Guid> deleteId1s = new List<Guid>();
                List<Guid> deleteId2s = new List<Guid>();
                List<Guid> deleteId3s = new List<Guid>();
                var jobFilter = new BaseFilter(filter.GetOrgId());
                jobFilter.IgnoreDataRule = true;
                jobFilter.SelectField = new List<string> { "CODE", "OPERATION_STEP_ID", "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures" };
                var jobs = this.GetEntities<T_FO_CRUCIAL_LICENSE_JOB>(t => t.IS_PUBLISH != 0 && t.CREATE_TIME >= week.Date && t.CREATE_TIME <= dt.Date, jobFilter);
                if (jobs != null && jobs.Any())
                {
                    var stepIds = jobs.Select(t => t.OPERATION_STEP_ID).Distinct().ToList();
                    var stepInfos = this.GetEntities<T_HM_OPERATION_LINK>(t => stepIds.Contains(t.OPERATION_STEP_ID), new BaseFilter(filter.OrgId), new string[] { "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures" });
                    foreach (var item in jobs)
                    {
                        if (item.Nav_SafeConfirms == null || !item.Nav_SafeConfirms.Any() || string.IsNullOrEmpty(item.Nav_SafeConfirms.FirstOrDefault().NAME))
                        {
                            if (item.Nav_SafeConfirms.Any())
                                deleteId1s.AddRange(item.Nav_SafeConfirms.Select(t => t.ID));
                            var stepInfo = stepInfos.FirstOrDefault(t => t.OPERATION_STEP_ID == item.OPERATION_STEP_ID);
                            if (stepInfo != null && stepInfo.Nav_SafeConfirms != null && stepInfo.Nav_SafeConfirms.Any())
                            {
                                foreach (var con in stepInfo.Nav_SafeConfirms)
                                {
                                    T_FO_CRUCIAL_LICENSE_SAFE_CONFIRM confirm = new T_FO_CRUCIAL_LICENSE_SAFE_CONFIRM();
                                    confirm.ORG_ID = con.ORG_ID;
                                    confirm.CODE = con.CODE;
                                    confirm.NUM = con.NUM;
                                    confirm.NAME = con.NAME;
                                    confirm.CRUCIAL_LICENSE_JOB_ID = item.ID;
                                    confirmList.Add(confirm);
                                }
                            }
                        }
                        if (item.Nav_SafeMeasures == null || !item.Nav_SafeMeasures.Any() || string.IsNullOrEmpty(item.Nav_SafeMeasures.FirstOrDefault().NAME))
                        {
                            if (item.Nav_SafeConfirms.Any())
                                deleteId2s.AddRange(item.Nav_SafeMeasures.Select(t => t.ID));
                            var stepInfo = stepInfos.FirstOrDefault(t => t.OPERATION_STEP_ID == item.OPERATION_STEP_ID);
                            if (stepInfo != null && stepInfo.Nav_SafeMeasures != null && stepInfo.Nav_SafeMeasures.Any())
                            {
                                foreach (var con in stepInfo.Nav_SafeMeasures)
                                {
                                    T_FO_CRUCIAL_LICENSE_SAFE_MEASURE confirm = new T_FO_CRUCIAL_LICENSE_SAFE_MEASURE();
                                    confirm.ORG_ID = con.ORG_ID;
                                    confirm.CODE = con.CODE;
                                    confirm.NUM = con.NUM;
                                    confirm.NAME = con.NAME;
                                    confirm.CRUCIAL_LICENSE_JOB_ID = item.ID;
                                    measureList.Add(confirm);
                                }
                            }
                        }
                        if (item.Nav_DealMeasures == null || !item.Nav_DealMeasures.Any() || string.IsNullOrEmpty(item.Nav_DealMeasures.FirstOrDefault().NAME))
                        {
                            if (item.Nav_SafeConfirms.Any())
                                deleteId3s.AddRange(item.Nav_DealMeasures.Select(t => t.ID));
                            var stepInfo = stepInfos.FirstOrDefault(t => t.OPERATION_STEP_ID == item.OPERATION_STEP_ID);
                            if (stepInfo != null && stepInfo.Nav_DealMeasures != null && stepInfo.Nav_DealMeasures.Any())
                            {
                                foreach (var con in stepInfo.Nav_DealMeasures)
                                {
                                    T_FO_CRUCIAL_LICENSE_DEAL_MEASURE confirm = new T_FO_CRUCIAL_LICENSE_DEAL_MEASURE();
                                    confirm.ORG_ID = con.ORG_ID;
                                    confirm.CODE = con.CODE;
                                    confirm.NUM = con.NUM;
                                    confirm.NAME = con.NAME;
                                    confirm.CRUCIAL_LICENSE_JOB_ID = item.ID;
                                    dealList.Add(confirm);
                                }
                            }
                        }
                    }
                }
                UnifiedCommit(() =>
                {
                    if (confirmList != null && confirmList.Any())
                        BantchSaveEntityNoCommit(confirmList);
                    if (measureList != null && measureList.Any())
                        BantchSaveEntityNoCommit(measureList);
                    if (dealList != null && dealList.Any())
                        BantchSaveEntityNoCommit(dealList);
                    if (deleteId1s != null && deleteId1s.Any())
                        BantchDeleteEntityNoCommit<T_FO_CRUCIAL_LICENSE_SAFE_CONFIRM>(deleteId1s);
                    if (deleteId2s != null && deleteId2s.Any())
                        BantchDeleteEntityNoCommit<T_FO_CRUCIAL_LICENSE_SAFE_MEASURE>(deleteId2s);
                    if (deleteId3s != null && deleteId3s.Any())
                        BantchDeleteEntityNoCommit<T_FO_CRUCIAL_LICENSE_DEAL_MEASURE>(deleteId3s);
                });
                return true;
            });
        }

        /// <summary>
        /// 作业活动记录表数据同步
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("ExecuteJobActivity")]
        public JsonActionResult<bool> ExecuteJobActivity([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var dt = DateTime.Now.Date.AddDays(1);
                //最近一周
                DateTime week = dt.AddDays(-2).Date;
                if (!string.IsNullOrEmpty(filter.Parameter1))
                {
                    if (!filter.Parameter1.Contains("|"))
                        throw new Exception("必须传入开始日期和结束日期，以|符号分隔");
                    var temp = filter.Parameter1.Split("|");
                    if (temp[1].Length == 0)
                        throw new Exception("必须传入开始日期和结束日期，以|符号分隔");
                    week = DateTime.Parse(temp[0]);
                    dt = DateTime.Parse(temp[1]);
                }
                List<T_FO_JOB_ACTIVITY_DETAIL> confirmList = new List<T_FO_JOB_ACTIVITY_DETAIL>();
                List<T_FO_JOB_ACTIVITY_FLOW> measureList = new List<T_FO_JOB_ACTIVITY_FLOW>();
                List<T_FO_JOB_ACTIVITY_MEASURE> dealList = new List<T_FO_JOB_ACTIVITY_MEASURE>();
                List<Guid> deleteId1s = new List<Guid>();
                List<Guid> deleteId2s = new List<Guid>();
                List<Guid> deleteId3s = new List<Guid>();
                var jobFilter = new BaseFilter(filter.GetOrgId());
                jobFilter.IgnoreDataRule = true;
                jobFilter.SelectField = new List<string> { "OPERATION_STEP_ID", "Nav_Details", "Nav_Flow", "Nav_Measure" };
                var jobs = this.GetEntities<T_FO_JOB_ACTIVITY_RECORD>(t => t.CREATE_TIME >= week.Date && t.CREATE_TIME <= dt.Date, jobFilter);
                if (jobs != null && jobs.Any())
                {
                    var stepIds = jobs.Select(t => t.OPERATION_STEP_ID).Distinct().ToList();
                    var stepInfos = this.GetEntities<T_HM_OPERATION_LINK>(t => stepIds.Contains(t.OPERATION_STEP_ID), new BaseFilter(filter.OrgId), new string[] { "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures" });
                    foreach (var item in jobs)
                    {
                        if (item.Nav_Details == null || !item.Nav_Details.Any() || string.IsNullOrEmpty(item.Nav_Details.FirstOrDefault().SafeConfirmsStr))
                        {
                            if (item.Nav_Details.Any())
                                deleteId1s.AddRange(item.Nav_Details.Select(t => t.ID));
                            var stepInfo = stepInfos.FirstOrDefault(t => t.OPERATION_STEP_ID == item.OPERATION_STEP_ID);
                            if (stepInfo.Nav_SafeConfirms != null && stepInfo.Nav_SafeConfirms.Any())
                            {
                                foreach (var con in stepInfo.Nav_SafeConfirms)
                                {
                                    T_FO_JOB_ACTIVITY_DETAIL confirm = new T_FO_JOB_ACTIVITY_DETAIL();
                                    confirm.ORG_ID = con.ORG_ID;
                                    confirm.NUM = con.NUM;
                                    confirm.SafeConfirmsStr = con.NAME;
                                    confirm.JOB_ACTIVITY_RECORD_ID = item.ID;
                                    confirmList.Add(confirm);
                                }
                            }
                        }
                        if (item.Nav_Flow == null || !item.Nav_Flow.Any() || string.IsNullOrEmpty(item.Nav_Flow.FirstOrDefault().SafeMeasuresStr))
                        {
                            if (item.Nav_Flow.Any())
                                deleteId2s.AddRange(item.Nav_Flow.Select(t => t.ID));
                            var stepInfo = stepInfos.FirstOrDefault(t => t.OPERATION_STEP_ID == item.OPERATION_STEP_ID);
                            if (stepInfo.Nav_SafeMeasures != null && stepInfo.Nav_SafeMeasures.Any())
                            {
                                foreach (var con in stepInfo.Nav_SafeMeasures)
                                {
                                    T_FO_JOB_ACTIVITY_FLOW confirm = new T_FO_JOB_ACTIVITY_FLOW();
                                    confirm.ORG_ID = con.ORG_ID;
                                    confirm.NUM = con.NUM;
                                    confirm.SafeMeasuresStr = con.NAME;
                                    confirm.JOB_ACTIVITY_RECORD_ID = item.ID;
                                    measureList.Add(confirm);
                                }
                            }
                        }
                        if (item.Nav_Measure == null || !item.Nav_Measure.Any() || string.IsNullOrEmpty(item.Nav_Measure.FirstOrDefault().DealMeasuresStr))
                        {
                            if (item.Nav_Measure.Any())
                                deleteId3s.AddRange(item.Nav_Measure.Select(t => t.ID));
                            var stepInfo = stepInfos.FirstOrDefault(t => t.OPERATION_STEP_ID == item.OPERATION_STEP_ID);
                            if (stepInfo.Nav_DealMeasures != null && stepInfo.Nav_DealMeasures.Any())
                            {
                                foreach (var con in stepInfo.Nav_DealMeasures)
                                {
                                    T_FO_JOB_ACTIVITY_MEASURE confirm = new T_FO_JOB_ACTIVITY_MEASURE();
                                    confirm.ORG_ID = con.ORG_ID;
                                    confirm.NUM = con.NUM;
                                    confirm.DealMeasuresStr = con.NAME;
                                    confirm.JOB_ACTIVITY_RECORD_ID = item.ID;
                                    dealList.Add(confirm);
                                }
                            }
                        }
                    }
                }
                UnifiedCommit(() =>
                {
                    if (deleteId1s != null && deleteId1s.Any())
                        BantchDeleteEntityNoCommit<T_FO_JOB_ACTIVITY_DETAIL>(deleteId1s);
                    if (deleteId2s != null && deleteId2s.Any())
                        BantchDeleteEntityNoCommit<T_FO_JOB_ACTIVITY_FLOW>(deleteId2s);
                    if (deleteId3s != null && deleteId3s.Any())
                        BantchDeleteEntityNoCommit<T_FO_JOB_ACTIVITY_MEASURE>(deleteId3s);
                    if (confirmList != null && confirmList.Any())
                        BantchSaveEntityNoCommit(confirmList);
                    if (measureList != null && measureList.Any())
                        BantchSaveEntityNoCommit(measureList);
                    if (dealList != null && dealList.Any())
                        BantchSaveEntityNoCommit(dealList);
                });
                return true;
            });
        }
    }
}
