using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.SE;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using MySqlX.XDevAPI.Common;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.FO.WebApi.Controllers
{
    /// <summary>
    /// 作业活动记录（关键和许可）
    /// </summary>
    [Route("api/FO/FOJobActivityRecord")]
    public partial class JobActivityRecordController : AuthorizeApiController<T_FO_JOB_ACTIVITY_RECORD>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        /// <summary>
        /// FOPreOperSch
        /// </summary>
        /// <param name="codeRuleService"></param>
        public JobActivityRecordController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMDepartmentService departmentService)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            DepartmentService = departmentService;
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEditOld")]
        public JsonActionResult<T_FO_JOB_ACTIVITY_RECORD> GetEditOld([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                //filter.Include.Clear();
                //filter.Include.Add("Nav_CreateUser");
                //filter.Include.Add("Nav_OperationStep");
                //filter.Include.Add("Nav_JobActivityPerson");
                //filter.Include.Add("Nav_JobActivityPerson.Nav_User");
                //filter.Include.Add("Nav_JobActivityPerson.Nav_User.Nav_Department");
                //filter.Include.Add("Nav_JobName");
                //filter.Include.Add("Nav_Details");
                //filter.Include.Add("Nav_Details.Nav_Files");
                //filter.Include.Add("Nav_Details.Nav_Files.Nav_ImgFile");
                //filter.Include.Add("Nav_Details.Nav_Files.Nav_ImgFile.Nav_File");
                //filter.Include.Add("Nav_Flow");
                //filter.Include.Add("Nav_Flow.Nav_Files");
                //filter.Include.Add("Nav_Flow.Nav_Files.Nav_ImgFile");
                //filter.Include.Add("Nav_Flow.Nav_Files.Nav_ImgFile.Nav_File");
                //filter.Include.Add("Nav_Measure");
                //filter.Include.Add("Nav_Measure.Nav_Files");
                //filter.Include.Add("Nav_Measure.Nav_Files.Nav_ImgFile");
                //filter.Include.Add("Nav_Measure.Nav_Files.Nav_ImgFile.Nav_File");
                //return WitEntity(null, filter);
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("060010");
                var result = this.GetEntity<T_FO_JOB_ACTIVITY_RECORD>(id, new string[] { "Nav_CreateUser", "Nav_OperationStep",
            "Nav_JobActivityPerson","Nav_JobActivityPerson.Nav_User","Nav_JobActivityPerson.Nav_User.Nav_Department","Nav_JobActivityPerson.Nav_RelatedUser","Nav_JobName","Nav_Details",
                "Nav_Details.Nav_Files","Nav_Details.Nav_Files.Nav_ImgFile","Nav_Details.Nav_Files.Nav_ImgFile.Nav_File",
            "Nav_Flow","Nav_Flow.Nav_Files","Nav_Flow.Nav_Files.Nav_ImgFile","Nav_Flow.Nav_Files.Nav_ImgFile.Nav_File",
                "Nav_Measure","Nav_Measure.Nav_Files","Nav_Measure.Nav_Files.Nav_ImgFile","Nav_Measure.Nav_Files.Nav_ImgFile.Nav_File"});
                if (result != null)
                {
                    if (result.Nav_Details != null && result.Nav_Details.Any())
                        result.Nav_Details = result.Nav_Details.OrderBy(t => t.NUM).ThenBy(m => m.SafeConfirmsStr).ToList();
                    if (result.Nav_Flow != null && result.Nav_Flow.Any())
                        result.Nav_Flow = result.Nav_Flow.OrderBy(t => t.NUM).ThenBy(m => m.SafeMeasuresStr).ToList();
                    if (result.Nav_Measure != null && result.Nav_Measure.Any())
                        result.Nav_Measure = result.Nav_Measure.OrderBy(t => t.NUM).ThenBy(m => m.DealMeasuresStr).ToList();
                }
                return result;
            });
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_FO_JOB_ACTIVITY_RECORD> GetEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("060010");
            //    var result = this.GetEntity<T_FO_JOB_ACTIVITY_RECORD>(id, new string[] { "Nav_CreateUser", "Nav_OperationStep",
            //"Nav_JobActivityPerson","Nav_JobActivityPerson.Nav_User","Nav_JobActivityPerson.Nav_User.Nav_Department","Nav_JobActivityPerson.Nav_RelatedUser","Nav_JobName","Nav_Details",
            //    "Nav_Details.Nav_Files","Nav_Details.Nav_Files.Nav_ImgFile","Nav_Details.Nav_Files.Nav_ImgFile.Nav_File",
            //"Nav_Flow","Nav_Flow.Nav_Files","Nav_Flow.Nav_Files.Nav_ImgFile","Nav_Flow.Nav_Files.Nav_ImgFile.Nav_File",
            //    "Nav_Measure","Nav_Measure.Nav_Files","Nav_Measure.Nav_Files.Nav_ImgFile","Nav_Measure.Nav_Files.Nav_ImgFile.Nav_File"});
                var entity = this.GetEntity<T_FO_JOB_ACTIVITY_RECORD>(id,  "Nav_CreateUser", "Nav_OperationStep", "Nav_JobName.Nav_MonitorUser.Nav_UserSignFiles.Nav_ImgFile.Nav_File");
                if (entity != null)
                {
                    var newFilter = new BaseFilter(filter.OrgId);
                    newFilter.SelectField = new List<string> { "ID", "DEAL_STATUS", "JOB_ACTIVITY_RECORD_ID", "JOB_DOCUMENT", "USER_ID", "RELATED_USER_ID", "Nav_User.NAME", "Nav_User.CODE", "Nav_User.Nav_Department", "Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File", "Nav_RelatedUser.NAME", "Nav_RelatedUser.Nav_Signs.Nav_ImgFile.Nav_File" };
                    var persons = this.GetEntities<T_FO_JOB_ACTIVITY_PERSON>(t => t.JOB_ACTIVITY_RECORD_ID == entity.ID, newFilter).ToList();
                    entity.Nav_JobActivityPerson = persons;
                    newFilter.SelectField = new List<string> { "ID", "NUM", "JOB_ACTIVITY_RECORD_ID", "SafeConfirmsStr", "IS_CONFIRM", "Nav_Files.Nav_ImgFile.Nav_File" };
                    var safeConfirms = this.GetEntities<T_FO_JOB_ACTIVITY_DETAIL>(t => t.JOB_ACTIVITY_RECORD_ID == entity.ID, newFilter).ToList();
                    entity.Nav_Details = safeConfirms.OrderBy(t => t.NUM).ThenBy(m => m.SafeConfirmsStr).ToList();
                    newFilter.SelectField = new List<string> { "ID", "NUM", "JOB_ACTIVITY_RECORD_ID", "SafeMeasuresStr", "IS_CONFIRM", "Nav_Files.Nav_ImgFile.Nav_File" };
                    var safeMeasures = this.GetEntities<T_FO_JOB_ACTIVITY_FLOW>(t => t.JOB_ACTIVITY_RECORD_ID == entity.ID, newFilter).ToList();
                    entity.Nav_Flow = safeMeasures.OrderBy(t => t.NUM).ThenBy(m => m.SafeMeasuresStr).ToList();
                    newFilter.SelectField = new List<string> { "ID", "NUM", "JOB_ACTIVITY_RECORD_ID", "DealMeasuresStr", "IS_CONFIRM", "Nav_Files.Nav_ImgFile.Nav_File" };
                    var dealMeasures = this.GetEntities<T_FO_JOB_ACTIVITY_MEASURE>(t => t.JOB_ACTIVITY_RECORD_ID == entity.ID, newFilter).ToList();
                    entity.Nav_Measure = dealMeasures.OrderBy(t => t.NUM).ThenBy(m => m.DealMeasuresStr).ToList();
                    //if (result.Nav_Details != null && result.Nav_Details.Any())
                    //    result.Nav_Details = result.Nav_Details.OrderBy(t => t.NUM).ThenBy(m => m.SafeConfirmsStr).ToList();
                    //if (result.Nav_Flow != null && result.Nav_Flow.Any())
                    //    result.Nav_Flow = result.Nav_Flow.OrderBy(t => t.NUM).ThenBy(m => m.SafeMeasuresStr).ToList();
                    //if (result.Nav_Measure != null && result.Nav_Measure.Any())
                    //    result.Nav_Measure = result.Nav_Measure.OrderBy(t => t.NUM).ThenBy(m => m.DealMeasuresStr).ToList();
                }
                return entity;
            });
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("FullGet")]
        public JsonActionResult<T_FO_JOB_ACTIVITY_RECORD> FullGet([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                T_FO_JOB_ACTIVITY_RECORD main = null;
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (!string.IsNullOrEmpty(id))
                {
                    main = this.GetEntity<T_FO_JOB_ACTIVITY_RECORD>(id, false, "Nav_CreateUser", "Nav_OperationStep", "Nav_JobActivityPerson", "Nav_JobActivityPerson.Nav_User",
                        "Nav_JobActivityPerson.Nav_User.Nav_Department", "Nav_JobName", "Nav_Details", "Nav_Details.Nav_Files", "Nav_Details.Nav_Files.Nav_ImgFile",
                        "Nav_Flow", "Nav_Flow.Nav_Files", "Nav_Flow.Nav_Files.Nav_ImgFile", "Nav_Measure", "Nav_Measure.Nav_Files", "Nav_Measure.Nav_Files.Nav_ImgFile");
                    if (main != null)
                    {
                        if (main.Nav_Details != null && main.Nav_Details.Any())
                            main.Nav_Details = main.Nav_Details.OrderBy(t => t.NUM).ThenBy(m => m.SafeConfirmsStr).ToList();
                        if (main.Nav_Flow != null && main.Nav_Flow.Any())
                            main.Nav_Flow = main.Nav_Flow.OrderBy(t => t.NUM).ThenBy(m => m.SafeMeasuresStr).ToList();
                        if (main.Nav_Measure != null && main.Nav_Measure.Any())
                            main.Nav_Measure = main.Nav_Measure.OrderBy(t => t.NUM).ThenBy(m => m.DealMeasuresStr).ToList();
                    }
                }
                return main;
            });
        }
        /// <summary>
        /// 新增修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FO_JOB_ACTIVITY_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                List<T_FO_JOB_ACTIVITY_FILE> file = new List<T_FO_JOB_ACTIVITY_FILE>();
                List<T_FO_JOB_ACTIVITY_FLOW_FILE> flowFile = new List<T_FO_JOB_ACTIVITY_FLOW_FILE>();
                List<T_FO_JOB_ACTIVITY_MEASURE_FILE> measureFile = new List<T_FO_JOB_ACTIVITY_MEASURE_FILE>();
                T_SE_TRAIN_NOTIFY notify = null;
                var users = entity.Nav_JobActivityPerson.Where(t => t.USER_ID != null && !t.IS_DELETED).ToList();
                entity.Nav_JobActivityPerson = null;
                var details = entity.Nav_Details;
                entity.Nav_Details = null;
                var flows = entity.Nav_Flow;
                entity.Nav_Flow = null;
                var measures = entity.Nav_Measure;
                entity.Nav_Measure = null;
                entity.DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                users.ForEach(t => {
                    t.Nav_User = null;
                    t.Nav_RelatedUser = null;
                    t.ORG_ID = entity.ORG_ID;
                    t.JOB_ACTIVITY_RECORD_ID = entity.ID;
                });
                if (details != null && details.Any())
                {
                    details.ForEach(t =>
                    {
                        if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify") && !t.IS_CONFIRM)
                        {
                            this.ThrowError("060001");
                        }
                        t.ORG_ID = entity.ORG_ID;
                        t.JOB_ACTIVITY_RECORD_ID = entity.ID;
                        if (t.Nav_Files != null && t.Nav_Files.Any())
                        {
                            t.Nav_Files.ForEach(x =>
                            {
                                x.ORG_ID = entity.ORG_ID;
                                x.T_FO_JOB_ACTIVITY_DETAIL_ID = t.ID;
                                file.Add(x);
                            });
                        }
                        t.Nav_Files = null;
                    });
                }
                else
                {
                    if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                    {
                        this.ThrowError("060007");
                    }
                }
                if (flows != null && flows.Any())
                {
                    flows.ForEach(t =>
                    {
                        if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify") && !t.IS_CONFIRM)
                        {
                            this.ThrowError("060003");
                        }
                        t.ORG_ID = entity.ORG_ID;
                        t.JOB_ACTIVITY_RECORD_ID = entity.ID;
                        if (t.Nav_Files != null && t.Nav_Files.Any())
                        {
                            t.Nav_Files.ForEach(x =>
                            {
                                x.ORG_ID = entity.ORG_ID;
                                x.T_FO_JOB_ACTIVITY_FLOW_ID = t.ID;
                                flowFile.Add(x);
                            });
                        }
                        t.Nav_Files = null;
                    });
                }
                else
                {
                    if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                    {
                        this.ThrowError("060008");
                    }
                }
                if (measures != null && measures.Any())
                {
                    measures.ForEach(t =>
                    {
                        if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify") && !t.IS_CONFIRM)
                        {
                            this.ThrowError("060005");
                        }
                        t.ORG_ID = entity.ORG_ID;
                        t.JOB_ACTIVITY_RECORD_ID = entity.ID;
                        if (t.Nav_Files != null && t.Nav_Files.Any())
                        {
                            t.Nav_Files.ForEach(x =>
                            {
                                x.ORG_ID = entity.ORG_ID;
                                x.T_FO_JOB_ACTIVITY_MEASURE_ID = t.ID;
                                measureFile.Add(x);
                            });
                        }
                        t.Nav_Files = null;
                    });
                }
                else
                {
                    if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                    {
                        this.ThrowError("060009");
                    }
                }
                entity.FORM_STATUS = (int)FOTeamActivityState.草稿;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                List<T_SE_TRAIN_NOTIFY_PERSONS> persons = new List<T_SE_TRAIN_NOTIFY_PERSONS>();
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    entity.FORM_STATUS = (int)FOTeamActivityState.已归档;
                    DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, entity.ORG_ID.Value, DateTime.Now, null, null);
                    //新增的消息通知
                    if (users != null && users.Any())
                    {
                        if (entity.IS_OUTSOURCE == true && entity.RELATED_ID != null)
                        {
                            entity.FORM_STATUS = (int)FOTeamActivityState.已归档;
                            users.ForEach(t => t.DEAL_STATUS = 1);
                        }
                        else
                        {
                            entity.FORM_STATUS = (int)FOTeamActivityState.签到中;
                            users.ForEach(t => { 
                                if (t.USER_ID == userID)
                                    t.DEAL_STATUS = 1;
                            });
                            var userIds = users.Where(x=>x.USER_ID != userID).Select(t => (Guid)t.USER_ID).Distinct().ToList();
                            if (userIds != null && userIds.Any())
                            {
                                var UserNames = new List<string>();
                                var user = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                                foreach (var u in userIds)
                                {
                                    var current = user.FirstOrDefault(t => t.ID == u);
                                    UserNames.Add(current?.NAME);
                                }
                                //发消息
                                notices = NotificationTaskService.InsertUserNoticeTaskModels("作业活动记录表单(关键和许可作业)", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                                dtEnd, (int)FMNoticeTypeEnum.消息, "FO021_SHOWPRINT");
                            }
                            else
                            {
                                entity.FORM_STATUS = (int)FOTeamActivityState.已归档;
                            }
                        }
                    }
                    //查询消息表
                    //var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    //task = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == userID
                    //&& (i.NOTICE_STATUS == FMNoticeStatusEnum.未处理.GetInt() || i.NOTICE_STATUS == FMNoticeStatusEnum.超期办理.GetInt()), false);
                    //if (task != null)
                    //{
                    //    task.NOTICE_STATUS = FMNoticeStatusEnum.正常已办.GetInt();
                    //    task.TASK_DT = DateTime.Now;
                    //    task.MODIFIER_ID = userID;
                    //}
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "FO021_SHOWPRINT";
                    }
                    if (entity.IS_NEED == (int)ISImportantEnum.否 && entity.IS_OUTSOURCE == false)
                    {
                        //触发培训通知给班组长
                        var departmentId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentId;
                        var departmentInfo = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == Guid.Parse(departmentId), "Nav_User");
                        if (departmentInfo != null && departmentInfo.USER_ID != null)
                        {
                            notify = new T_SE_TRAIN_NOTIFY();
                            notify.ORG_ID = entity.ORG_ID;
                            notify.LAUNCH_TIME = DateTime.Now;
                            notify.LAUNCH_DEPARTMENT_ID = departmentInfo.ID;
                            notify.LAUNCH_USER_ID = departmentInfo.USER_ID;
                            notify.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                            notify.NAME = "关键许可作业活动记录培训通知";
                            notify.STATUS = SETrainNotifyStatus.草稿;
                            if (users.Any())
                            {
                                users.ForEach(t =>
                                {
                                    T_SE_TRAIN_NOTIFY_PERSONS person = new T_SE_TRAIN_NOTIFY_PERSONS();
                                    person.USER_ID = t.USER_ID.Value;
                                    person.NOTIFY_ID = notify.ID;
                                    person.ORG_ID = notify.ORG_ID;
                                    person.IS_LEAVE = SETrainYesNoEnum.参加;
                                    persons.Add(person);
                                });
                            }
                            notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("关键许可作业活动记录培训通知", notify.ID, notify.ORG_ID, departmentInfo.USER_ID.Value, departmentInfo.Nav_User.NAME, DateTime.Now,
                        dtEnd, (int)FMNoticeTypeEnum.消息, "SE014"));
                        }
                    }
                }
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //保存主表
                    if (users != null && users.Any())
                        BantchSaveEntityNoCommit(users);    //保存子表
                    if (details != null && details.Any())
                        BantchSaveEntityNoCommit(details);    //保存子表
                    if (flows != null && flows.Any())
                        BantchSaveEntityNoCommit(flows);    //保存子表
                    if (measures != null && measures.Any())
                        BantchSaveEntityNoCommit(measures);    //保存子表
                    if (file != null && file.Any())
                        BantchSaveEntityNoCommit(file);    //保存子表
                    if (flowFile != null && flowFile.Any())
                        BantchSaveEntityNoCommit(flowFile);    //保存子表
                    if (measureFile != null && measureFile.Any())
                        BantchSaveEntityNoCommit(measureFile);    //保存子表
                    if (notices != null && notices.Any())
                        BantchSaveEntityNoCommit(notices);
                    if (task != null)
                        UpdateEntityNoCommit(task);
                    if (notify != null)
                        UpdateEntityNoCommit(notify);   //保存主表
                    if (persons != null && persons.Any())
                        BantchSaveEntityNoCommit(persons);
                });
                return true;
            });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("FullDelete")]
        public JsonActionResult<bool> FullDelete(string id)
        {
            return SafeExecute<bool>(() =>
            {
                T_FO_JOB_ACTIVITY_RECORD entity = GetEntity<T_FO_JOB_ACTIVITY_RECORD>(t => t.ID.ToString() == id, false, "Nav_JobActivityPerson", "Nav_Details", "Nav_Details.Nav_Files", "Nav_Flow", "Nav_Flow.Nav_Files", "Nav_Measure", "Nav_Measure.Nav_Files");
                List<Guid> userIds = new List<Guid>();
                List<Guid> detailIds = new List<Guid>();
                List<Guid> fileIds = new List<Guid>();
                List<Guid> flowIds = new List<Guid>();
                List<Guid> flowFileIds = new List<Guid>();
                List<Guid> measureIds = new List<Guid>();
                List<Guid> measureFileIds = new List<Guid>();
                if (entity.Nav_JobActivityPerson != null && entity.Nav_JobActivityPerson.Any())
                {
                    var userIdList = entity.Nav_JobActivityPerson.Select(t => t.ID).ToList();
                    userIds.AddRange(userIdList);
                }
                if (entity.Nav_Details != null && entity.Nav_Details.Any())
                {
                    var detailIdList = entity.Nav_Details.Select(t => t.ID).ToList();
                    detailIds.AddRange(detailIdList);
                    entity.Nav_Details.ForEach(t =>
                    {
                        var ids = t.Nav_Files.Select(t => t.ID).ToList();
                        fileIds.AddRange(ids);
                    });
                }
                if (entity.Nav_Flow != null && entity.Nav_Flow.Any())
                {
                    var flowIdList = entity.Nav_Flow.Select(t => t.ID).ToList();
                    flowIds.AddRange(flowIdList);
                    entity.Nav_Flow.ForEach(t =>
                    {
                        var ids = t.Nav_Files.Select(t => t.ID).ToList();
                        flowFileIds.AddRange(ids);
                    });
                }
                if (entity.Nav_Measure != null && entity.Nav_Measure.Any())
                {
                    var measureIdList = entity.Nav_Measure.Select(t => t.ID).ToList();
                    measureIds.AddRange(measureIdList);
                    entity.Nav_Measure.ForEach(t =>
                    {
                        var ids = t.Nav_Files.Select(t => t.ID).ToList();
                        measureFileIds.AddRange(ids);
                    });
                }
                UnifiedCommit(() =>
                {
                    if (userIds != null && userIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_JOB_ACTIVITY_PERSON>(userIds);
                    if (detailIds != null && detailIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_JOB_ACTIVITY_DETAIL>(detailIds);
                    if (fileIds != null && fileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_JOB_ACTIVITY_FILE>(fileIds);
                    if (flowIds != null && flowIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_JOB_ACTIVITY_FLOW>(flowIds);
                    if (flowFileIds != null && flowFileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_JOB_ACTIVITY_FLOW_FILE>(flowFileIds);
                    if (measureIds != null && measureIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_JOB_ACTIVITY_MEASURE>(measureIds);
                    if (measureFileIds != null && measureFileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_JOB_ACTIVITY_MEASURE_FILE>(measureFileIds);
                    if (entity != null)
                        this.DeleteEntityNoCommit(entity);
                });
                return true;
            });
        }

        /// <summary>
        /// 签到同意
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("PersonalAgree")]
        public JsonActionResult<bool> PersonalAgree([FromBody] T_FO_JOB_ACTIVITY_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                entity.ORG_ID = orgId;
                var user = this.GetEntity<T_FO_JOB_ACTIVITY_PERSON>(t => t.JOB_ACTIVITY_RECORD_ID == entity.ID && t.USER_ID == userID, new BaseFilter(orgId));
                user.DEAL_STATUS = (int)FOUserShiftStatusEnum.已处理;
                var todoCount = this.GetCount<T_FO_JOB_ACTIVITY_PERSON>(t => t.JOB_ACTIVITY_RECORD_ID == entity.ID && t.DEAL_STATUS == 0 && t.USER_ID != userID, new BaseFilter(orgId));
                T_FO_JOB_ACTIVITY_RECORD model = null;
                if (todoCount == 0)
                {
                    model = GetEntity<T_FO_JOB_ACTIVITY_RECORD>(entity.ID.ToString());
                    model.FORM_STATUS = (int)FOTeamActivityState.已归档;
                }
                //查询消息表
                //var task = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == userID
                //&& (i.NOTICE_STATUS == FMNoticeStatusEnum.未处理.GetInt() || i.NOTICE_STATUS == FMNoticeStatusEnum.超期办理.GetInt()), false);
                //if (task != null)
                //{
                //    task.NOTICE_STATUS = FMNoticeStatusEnum.正常已办.GetInt();
                //    task.TASK_DT = DateTime.Now;
                //    task.MODIFIER_ID = userID;
                //}
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "FO021_SHOWPRINT";
                }
                this.UnifiedCommit(() =>
                {
                    if (model != null)
                        UpdateEntityNoCommit(model);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    if (user != null)
                        this.UpdateEntityNoCommit(user);
                });
                return true;
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_FO_JOB_ACTIVITY_RECORD> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_FO_JOB_ACTIVITY_RECORD>();
            var filter = pageFilter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "PARENT_NAME");
            if (filter != null && !string.IsNullOrEmpty(filter.Value.ToString()))
                pageFilter.FilterGroup.Rules.Remove(filter);
            var loginDepartmentId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
            var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var loginUserCode = APT.Infrastructure.Api.AppContext.CurrentSession.UserCode;
            //安环部负责人departmentID
            var manageDepartId = this.GetEntity<T_FM_USER>(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "安环部负责人" && t.ENABLE_STATUS == 0)?.DEPARTMENT_ID;
            if (loginUserCode == "admin" || loginDepartmentId == manageDepartId)
            {
                result = this.GetOrderPageEntities<T_FO_JOB_ACTIVITY_RECORD>(null, pageFilter);
            }
            else
            {
                List<Guid> departmentId = new List<Guid>() { loginDepartmentId.Value };
                List<Guid> departmentIds = new List<Guid>() { loginDepartmentId.Value };
                DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, departmentId, ref departmentIds);
                if (departmentIds != null && departmentIds.Any())
                {
                    result = this.GetOrderPageEntities<T_FO_JOB_ACTIVITY_RECORD>(t => t.Nav_CreateUser.DEPARTMENT_ID != null && departmentIds.Contains(t.Nav_CreateUser.DEPARTMENT_ID.Value), pageFilter);//|| dataIds.Contains(t.ID)
                }
                else
                    result.Data = null;
            }
            if (result.Data.Any())
            {
                var departments = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(pageFilter.OrgId)).ToList();
                result.Data.ForEach(t =>
                {
                    if (t.Nav_CreateUser != null && t.Nav_CreateUser.DEPARTMENT_ID != null)
                    {
                        var depart = GetDEPARTMENTLevel(departments, (Guid)t.Nav_CreateUser.DEPARTMENT_ID);
                        t.PARENT_NAME = depart?.NAME;
                    }
                });
                if (filter != null && !string.IsNullOrEmpty(filter.Value.ToString()))
                    result.Data = result.Data.Where(t => t.PARENT_NAME != null && t.PARENT_NAME.Contains(filter.Value.ToString()));
            }
            return result;
        }
        public T_FM_DEPARTMENT GetDEPARTMENTLevel(List<T_FM_DEPARTMENT> departList, Guid DepartmentID)
        {
            var department = departList.FirstOrDefault(t => t.ID == DepartmentID);
            if (department.DEPARTMENT_TYPE == (int)FMDepartmentType.公司)
            {
                return null;
            }
            else if (department.DEPARTMENT_TYPE == (int)FMDepartmentType.部门)
            {
                return department;
            }
            else
            {
                department = GetDEPARTMENTLevel(departList, department.PARENT_ID.Value);
            }
            return department;
        }
    }
}
