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.DomainServices;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Enums;
using APT.Utility;
using IdentityModel;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.FO.WebApi.Controllers
{
    /// <summary>
    /// 作业活动记录(一般)
    /// </summary>
    [Route("api/FO/FOJobEventRecord")]
    public partial class JobEventRecordController : AuthorizeApiController<T_FO_JOB_EVENT_RECORD>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        /// <summary>
        /// FOPreOperSch
        /// </summary>
        /// <param name="codeRuleService"></param>
        public JobEventRecordController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IFMDepartmentService departmentService)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            DepartmentService = departmentService;
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEditOld")]
        public JsonActionResult<T_FO_JOB_EVENT_RECORD> GetEditOld([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                //filter.Include.Clear();
                //filter.Include.Add("Nav_CreateUser");
                //filter.Include.Add("Nav_OperationStep");
                //filter.Include.Add("Nav_JobEventPerson");
                //filter.Include.Add("Nav_JobEventPerson.Nav_User");
                //filter.Include.Add("Nav_JobEventPerson.Nav_User.Nav_Department");
                //filter.Include.Add("Nav_Meeting");
                //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_EVENT_RECORD>(id, new string[] { "Nav_CreateUser", "Nav_OperationStep",
            "Nav_JobEventPerson","Nav_JobEventPerson.Nav_User","Nav_JobEventPerson.Nav_User.Nav_Department","Nav_Meeting","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.FORM_STATUS == (int)FOTeamActivityState.已驳回)
                    {
                        result.CONTEXT = ApproveCallBackService.RejectContent(result.ID);
                    }
                    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_EVENT_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_EVENT_RECORD>(id, new string[] { "Nav_CreateUser", "Nav_OperationStep",
            //"Nav_JobEventPerson","Nav_JobEventPerson.Nav_User","Nav_JobEventPerson.Nav_User.Nav_Department","Nav_Meeting","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_EVENT_RECORD>(id, "Nav_CreateUser", "Nav_OperationStep", "Nav_Meeting");
                if (entity != null)
                {
                    if (entity.FORM_STATUS == (int)FOTeamActivityState.已驳回)
                    {
                        entity.CONTEXT = ApproveCallBackService.RejectContent(entity.ID);
                    }
                    var newFilter = new BaseFilter(filter.OrgId);
                    newFilter.SelectField = new List<string> { "ID", "DEAL_STATUS", "JOB_EVENT_RECORD_ID", "USER_ID",  "Nav_User.NAME", "Nav_User.CODE", "Nav_User.Nav_Department", "Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File" };
                    var persons = this.GetEntities<T_FO_JOB_EVENT_PERSON>(t => t.JOB_EVENT_RECORD_ID == entity.ID, newFilter).ToList();
                    entity.Nav_JobEventPerson = persons;
                    newFilter.SelectField = new List<string> { "ID", "NUM", "JOB_EVENT_RECORD_ID", "SafeConfirmsStr", "IS_CONFIRM", "Nav_Files.Nav_ImgFile.Nav_File" };
                    var safeConfirms = this.GetEntities<T_FO_JOB_EVENT_DETAIL>(t => t.JOB_EVENT_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_EVENT_RECORD_ID", "SafeMeasuresStr", "IS_CONFIRM", "Nav_Files.Nav_ImgFile.Nav_File" };
                    var safeMeasures = this.GetEntities<T_FO_JOB_EVENT_FLOW>(t => t.JOB_EVENT_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_EVENT_RECORD_ID", "DealMeasuresStr", "IS_CONFIRM", "Nav_Files.Nav_ImgFile.Nav_File" };
                    var dealMeasures = this.GetEntities<T_FO_JOB_EVENT_MEASURE>(t => t.JOB_EVENT_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="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FO_JOB_EVENT_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var record = this.GetEntity<T_FO_JOB_EVENT_RECORD>(entity.ID, "Nav_Meeting", "Nav_OperationStep");
                if (record != null && record.Nav_Meeting != null)
                {
                    if (DateTime.Now < record.Nav_Meeting.START_TIME)
                        throw new Exception("作业开始时间未到,请稍后再作业!");
                }
                List<T_FO_JOB_EVENT_FILE> file = new List<T_FO_JOB_EVENT_FILE>();
                List<T_FO_JOB_EVENT_FLOW_FILE> flowFile = new List<T_FO_JOB_EVENT_FLOW_FILE>();
                List<T_FO_JOB_EVENT_MEASURE_FILE> measureFile = new List<T_FO_JOB_EVENT_MEASURE_FILE>();
                var users = entity.Nav_JobEventPerson;
                if (users != null && users.Any())
                {
                    users = users.Where(t => t.USER_ID != null && !t.IS_DELETED).ToList();
                }
                entity.Nav_JobEventPerson = 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;
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                entity.DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                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_EVENT_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_EVENT_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_EVENT_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_EVENT_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_EVENT_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_EVENT_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.草稿;
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                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())
                    {
                        entity.FORM_STATUS = (int)FOTeamActivityState.签到中;
                        users.ForEach(t => {
                            t.ORG_ID = entity.ORG_ID;
                            t.JOB_EVENT_RECORD_ID = entity.ID;
                            if (t.USER_ID == loginUserId)
                                t.DEAL_STATUS = (int)FOUserShiftStatusEnum.已处理;
                            t.Nav_User = null;
                        });
                        //将另外两人的消息更新为查看表单
                        var userIds = users.Where(m => m.USER_ID != null && m.USER_ID != loginUserId).Select(t => t.USER_ID.Value).Distinct().ToList();
                        if (userIds.Count() == 0)
                        {
                            entity.FORM_STATUS = (int)FOTeamActivityState.审核中;
                            //取审批流水码
                            var sysFilter = new SystemCodeFilter();
                            sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                            sysFilter.Count = 1;
                            sysFilter.OrgId = entity.ORG_ID;
                            var codes = CodeRuleService.NewGenSerial(sysFilter);
                            var serialCode = codes.Split(new char[] { ',' });
                            var departmentId= APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                            var departmentType = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == departmentId)?.DEPARTMENT_TYPE;
                            var param = Enum.GetName(typeof(FMDepartmentType), departmentType);
                            MFlowPermitService.InsertApprove(serialCode[0], "FO015", param, entity.ID, "FO015_SHOWPRINT", entity.TaskID, true, () =>
                            {
                                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);    //保存子表
                            }, null, null, null, null, null, "FO015_SHOWPRINT", null, "作业活动记录表(一般作业)" + record.Nav_OperationStep?.NAME, FMTASKTYPE.JobSite);
                            return true;
                        }
                        else
                        {
                            entity.FORM_STATUS = (int)FOTeamActivityState.签到中;
                            notices = GetEntities<T_FM_NOTIFICATION_TASK>(t => t.SOURCE_FORMCODE == "FO015" && t.SOURCE_DATA_ID == entity.ID && t.NOTICE_STATUS == (int)FMNoticeStatusEnum.未处理 && userIds.Contains(t.USER_ID), new BaseFilter(entity.ORG_ID)).ToList();
                            if (notices.Count() == 0)
                            {
                                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(record.Nav_OperationStep?.NAME +"作业活动记录表(一般作业)签到", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                                dtEnd, (int)FMNoticeTypeEnum.消息, "FO015_SHOWPRINT");
                                //throw new Exception("未找到对应待办，请联系管理员");
                                //entity.FORM_STATUS = (int)FOTeamActivityState.已归档;
                            }
                            else
                            {
                                foreach (var item in notices)
                                {
                                    item.NOTICE_TITLE = item.NOTICE_TITLE + "签到";
                                    item.SOURCE_FORMCODE = "FO015_SHOWPRINT";
                                }
                            }
                            if (entity.TaskID != Guid.Empty)
                            {
                                task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                                task.SOURCE_FORMCODE = "FO015_SHOWPRINT";
                            }
                        }
                    }
                    //查询消息表
                    //task = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == loginUserId
                    //&& i.NOTICE_STATUS == FMNoticeStatusEnum.未处理.GetInt(), false);
                    //if (task != null)
                    //{
                    //    task.TASK_DT = DateTime.Now;
                    //    task.MODIFIER_ID = loginUserId;
                    //    task.SOURCE_FORMCODE = "FO015_SHOWPRINT";
                    //    if (DateTime.Now > task.TASK_ENDDT)
                    //        task.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                    //    else
                    //        task.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                    //}
                }
                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);
                });
                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_EVENT_RECORD entity = GetEntity<T_FO_JOB_EVENT_RECORD>(t => t.ID.ToString() == id, false, "Nav_JobEventPerson", "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_JobEventPerson != null && entity.Nav_JobEventPerson.Any())
                {
                    var userIdList = entity.Nav_JobEventPerson.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_EVENT_PERSON>(userIds);
                    if (detailIds != null && detailIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_JOB_EVENT_DETAIL>(detailIds);
                    if (fileIds != null && fileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_JOB_EVENT_FILE>(fileIds);
                    if (flowIds != null && flowIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_JOB_EVENT_FLOW>(flowIds);
                    if (flowFileIds != null && flowFileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_JOB_EVENT_FLOW_FILE>(flowFileIds);
                    if (measureIds != null && measureIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_JOB_EVENT_MEASURE>(measureIds);
                    if (measureFileIds != null && measureFileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_JOB_EVENT_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_EVENT_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_EVENT_PERSON>(t => t.JOB_EVENT_RECORD_ID == entity.ID && t.USER_ID == userID, new BaseFilter(orgId));
                if(user != null)
                    user.DEAL_STATUS = (int)FOUserShiftStatusEnum.已处理;
                var todoCount = this.GetCount<T_FO_JOB_EVENT_PERSON>(t => t.JOB_EVENT_RECORD_ID == entity.ID && t.DEAL_STATUS == 0, new BaseFilter(orgId));
                T_FO_JOB_EVENT_RECORD model = null;
                T_FM_NOTIFICATION_TASK task = null;
                if (todoCount == 0 || todoCount == 1)
                {
                    model = GetEntity<T_FO_JOB_EVENT_RECORD>(entity.ID.ToString(), "Nav_OperationStep");
                    model.FORM_STATUS = (int)FOTeamActivityState.审核中;
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = orgId;
                    var codes = CodeRuleService.NewGenSerial(sysFilter);
                    var serialCode = codes.Split(new char[] { ',' });
                    var departmentId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                    var departmentType = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == departmentId)?.DEPARTMENT_TYPE;
                    var param = Enum.GetName(typeof(FMDepartmentType), departmentType);
                    MFlowPermitService.InsertApprove(serialCode[0], "FO015", param, entity.ID, "FO015_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        if (model != null)
                        {
                            model.Nav_OperationStep = null;
                            UpdateEntityNoCommit(model);
                        }
                        if (user != null)
                            this.UpdateEntityNoCommit(user);
                    }, null, null, null, null, null, "FO015_SHOWPRINT", null, "作业活动记录表(一般作业)" + model.Nav_OperationStep?.NAME, FMTASKTYPE.JobSite);
                    return true;
                }
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "FO015_SHOWPRINT";
                }
                model.Nav_OperationStep = null;
                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="id"></param>
        /// <returns></returns>
        [HttpGet, Route("BackUpdate")]
        public JsonActionResult<bool> BackUpdate(string id)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBack("FO/FOJobEventRecord/BackUpdate", id);
            });
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("BackUpdateNew")]
        public JsonActionResult<bool> BackUpdateNew([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBackNew("FO/FOJobEventRecord/BackUpdateNew", entity);
            });
        }
        /// <summary>
        /// 驳回
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("RejectUpdate")]
        public JsonActionResult<bool> RejectUpdate([FromBody] T_PF_APPROVE model)
        {
            return SafeExecute(() =>
            {
                //公共 获取审批流信息
                T_PF_APPROVE modelApp = null;
                List<T_PF_APPROVE_DETAIL> listAppDetail = null;
                T_FM_NOTIFICATION_TASK taskFinish = null;
                string Msg = string.Empty;
                bool ResultGetInfo = ApproveCallBackService.GetApproject(model, ref modelApp, ref listAppDetail, ref taskFinish, ref Msg);
                if (!ResultGetInfo)
                    throw new Exception("驳回失败！");

                if (modelApp == null || listAppDetail == null)
                    throw new Exception("获取驳回信息失败！");
                var entity = this.GetEntity<T_FO_JOB_EVENT_RECORD>(model.DATA_ID, new string[] { "Nav_JobEventPerson.Nav_User", "Nav_CreateUser" });
                entity.FORM_STATUS = (int)FOTeamActivityState.已驳回;
                T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                if (entity.Nav_JobEventPerson.Any())
                {
                    //随机取一个
                    var user = entity.Nav_JobEventPerson.OrderBy(t => t.MODIFY_TIME).FirstOrDefault();
                    //发消息
                    notice = NotificationTaskService.InsertUserNoticeTaskModel("作业活动记录表(一般作业)已被驳回", entity.ID, entity.ORG_ID, (Guid)user.USER_ID, user.Nav_User.NAME, DateTime.Now,
               DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO015");
                }
                else
                {
                    //没有作业员，驳回给创建人
                    notice = NotificationTaskService.InsertUserNoticeTaskModel("作业活动记录表(一般作业)已被驳回", entity.ID, entity.ORG_ID, (Guid)entity.CREATER_ID, entity.Nav_CreateUser.NAME, DateTime.Now,
                DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO015");
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (notice != null)
                        this.UpdateEntityNoCommit(notice);
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);
                    if (listAppDetail != null && listAppDetail.Count > 0)
                        BantchUpdateEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                });
                return true;
                //return ApproveCallBackService.CallReject("HM/HMLicenseAnalysis/RejectUpdate", id);
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_FO_JOB_EVENT_RECORD> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_FO_JOB_EVENT_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_EVENT_RECORD>(null, pageFilter, "Nav_CreateUser");
            }
            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_EVENT_RECORD>(t => t.Nav_CreateUser.DEPARTMENT_ID != null && departmentIds.Contains(t.Nav_CreateUser.DEPARTMENT_ID.Value), pageFilter,"Nav_CreateUser");//|| 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;
        }
    }
}
