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.Entities.OG;
using APT.MS.Domain.Enums;
using APT.MS.Domain.Enums.SK;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.FO.WebApi.Controllers
{
    /// <summary>
    ///  动火作业
    /// </summary>
    [Route("api/FO/FOFireJob")]
    public partial class FireJobController : AuthorizeApiController<T_FO_FIRE_JOB>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        /// <summary>
        /// FOPreOperSch
        /// </summary>
        /// <param name="codeRuleService"></param>
        public FireJobController(IPFCodeRuleService codeRuleService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IFMNotificationTaskService notificationTaskService)
        {
            CodeRuleService = codeRuleService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            NotificationTaskService = notificationTaskService;
        }
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_FO_FIRE_JOB> 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 entity = this.GetEntity<T_FO_FIRE_JOB>(id, "Nav_ApplyUser", "Nav_Company", "Nav_ApplyDepartment", "Nav_OperationStep", "Nav_ProductionUnit", "Nav_FireUser.Nav_UserSignFiles.Nav_ImgFile", "Nav_FireDepartment", 
                    "Nav_SafeUser.Nav_UserSignFiles.Nav_ImgFile", "Nav_Area", "Nav_Type", "Nav_MonitorUser.Nav_UserSignFiles.Nav_ImgFile", "Nav_Risks", "Nav_Files.Nav_ImgFile",  
                    "Nav_FireFiles.Nav_ImgFile", "Nav_MonitorFiles.Nav_ImgFile", "Nav_DispatchUser.Nav_UserSignFiles.Nav_ImgFile");
                if (entity != null)
                {
                    var details = this.GetEntities<T_FO_FIRE_JOB_DETAIL>(t => t.FIRE_JOB_ID == entity.ID, new BaseFilter(entity.ORG_ID), "Nav_DetailFiles.Nav_ImgFile.Nav_File").ToList();
                    
                    entity.Nav_Details = details.OrderBy(t => t.JOB_STEP).ThenBy(m => m.NUM).ToList();
                    if (entity.FIRE_STATUS.GetInt() == 10 || entity.FIRE_STATUS.GetInt() == 15)
                    {
                        entity.Nav_Details = entity.Nav_Details.Where(t => t.JOB_STEP == FOJobStepEnum.Pre).OrderBy(m => m.NUM).ToList();
                    }
                    if (entity.FIRE_STATUS.GetInt() == 18 || entity.FIRE_STATUS.GetInt() == 21)
                    {
                        entity.Nav_Details = entity.Nav_Details.Where(t => t.JOB_STEP != FOJobStepEnum.Pre).OrderBy(t => t.JOB_STEP).ThenBy(m => m.NUM).ToList();
                    }
                    var users = this.GetEntities<T_FO_FIRE_JOB_USER>(t => t.FIRE_JOB_ID == entity.ID, new BaseFilter(entity.ORG_ID), "Nav_UserType", "Nav_Train", "Nav_UserFiles.Nav_ImgFile", "Nav_User").ToList();
                    entity.Nav_Users = users.ToList();
                }
                return entity;
            });
        }
        /// <summary>
        /// 新增修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FO_FIRE_JOB entity)
        {
            return SafeExecute<bool>(() =>
            {
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var departmentId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                if(entity.APPLY_USER_ID == null)
                    entity.APPLY_USER_ID = loginUserId;
                if(entity.APPLY_DEPARTMENT_ID == null)
                    entity.APPLY_DEPARTMENT_ID = departmentId;
                if (entity.COMPANY_ID == null)
                {
                    entity.COMPANY_ID = this.GetEntity<T_FM_DEPARTMENT>(t => t.PARENT_ID == null)?.ID;
                }
                if (entity.PRODUCTION_UNIT_ID == null)
                {
                    entity.PRODUCTION_UNIT_ID = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.APPLY_DEPARTMENT_ID)?.PRODUCTION_UNIT_ID;
                }
                if (string.IsNullOrEmpty(entity.CODE))
                {
                    var num = "001";
                    var record = this.GetEntities<T_FO_FIRE_JOB>(t => t.CREATE_TIME.Value.Date == DateTime.Now.Date,new BaseFilter(entity.ORG_ID)).OrderByDescending(m => m.CREATE_TIME).FirstOrDefault();
                    if (record != null)
                    {
                        var codeTake = record.CODE.Substring(record.CODE.Length - 3).ToString();
                        var temp = int.Parse(codeTake) + 1;
                        num = temp.ToString().PadLeft(3, '0');
                    }
                    entity.CODE = "DHZY" + DateTime.Now.Date.ToString("yyyyMMdd") + num;
                }
                if (entity.FIRE_USER_ID == null)
                {
                    throw new Exception("施工单位负责人必须填写");
                }
                if (entity.SAFE_USER_ID == null)
                {
                    throw new Exception("安全管理人员必须填写");
                }
                if (entity.JOB_DATE == null)
                {
                    throw new Exception("计划开始时间必须填写");
                }
                if (entity.JOB_END_DATE == null)
                {
                    throw new Exception("计划结束时间必须填写");
                }
                //entity.ACT_DATE = entity.JOB_DATE;
                //entity.ACT_END_DATE = entity.JOB_END_DATE;
                if (entity.JOB_END_DATE > entity.JOB_DATE.Value.AddHours(8))
                {
                    throw new Exception("计划开始和计划结束时间不能超过8小时");
                }
                if (entity.ACT_DATE != null && entity.ACT_DATE < entity.JOB_DATE)
                {
                    throw new Exception("动火实际开始时间不能早于计划开始时间");
                }
                if (entity.ACT_END_DATE!=null && entity.ACT_END_DATE > entity.JOB_END_DATE)
                {
                    throw new Exception("动火实际结束时间不能晚于计划结束时间");
                }
                if (entity.LEAVE_DATE!=null && entity.ACT_END_DATE != null && entity.LEAVE_DATE < entity.ACT_END_DATE.Value.AddHours(1))
                {
                    throw new Exception("离开现场时间必须大于实际动火结束时间1小时以上");
                }
                var details = entity.Nav_Details;
                if (details != null && details.Any())
                {
                    details = details.Where(t => !t.IS_DELETED).ToList();
                }
                entity.Nav_Details = null;
                var detailInfos = this.GetEntities<T_FO_FIRE_JOB_DETAIL>(t => t.FIRE_JOB_ID == entity.ID, new BaseFilter(entity.ORG_ID)).ToList();
                var detailIds = detailInfos.Select(m => m.ID).ToList();
                var detailFileInfos = this.GetEntities<T_FO_FIRE_JOB_DETAIL_FILE>(t => detailIds.Contains(t.FIRE_JOB_DETAIL_ID), new BaseFilter(entity.ORG_ID)).ToList();
                var detailFileIds = detailFileInfos.Select(m => m.ID).ToList();
                var detailList = new List<T_FO_FIRE_JOB_DETAIL>();
                var detailFileList = new List<T_FO_FIRE_JOB_DETAIL_FILE>();
                if (details != null && details.Any())
                {
                    foreach (var item in details)
                    {
                        if (item.Nav_DetailFiles != null && item.Nav_DetailFiles.Any())
                        {
                            foreach (var item2 in item.Nav_DetailFiles)
                            {
                                item2.ORG_ID = entity.ORG_ID;
                                item2.FIRE_JOB_DETAIL_ID = item.ID;
                                item2.Nav_ImgFile = null;
                                detailFileList.Add(item2);
                            }
                        }
                        item.ORG_ID = entity.ORG_ID;
                        item.FIRE_JOB_ID = entity.ID;
                        item.Nav_DetailFiles = null;
                        detailList.Add(item);
                    }
                }
                var files = entity.Nav_Files;
                if (files != null && files.Any())
                {
                    files = files.Where(t => !t.IS_DELETED).ToList();
                }
                entity.Nav_Files = null;
                var fileIds = this.GetEntities<T_FO_FIRE_JOB_FILE>(t => t.FIRE_JOB_ID == entity.ID, new BaseFilter(entity.ORG_ID)).Select(m => m.ID).ToList();
                var fileList = new List<T_FO_FIRE_JOB_FILE>();
                if (files != null && files.Any())
                {
                    foreach (var item in files)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.FIRE_JOB_ID = entity.ID;
                        item.Nav_ImgFile = null;
                        fileList.Add(item);
                    }
                }
                var risks = entity.Nav_Risks;
                if (risks != null && risks.Any())
                {
                    risks = risks.Where(t => !t.IS_DELETED).ToList();
                }
                entity.Nav_Risks = null;
                var riskIds = this.GetEntities<T_FO_FIRE_JOB_RISK>(t => t.FIRE_JOB_ID == entity.ID, new BaseFilter(entity.ORG_ID)).Select(m => m.ID).ToList();
                var riskList = new List<T_FO_FIRE_JOB_RISK>();
                if (risks != null && risks.Any())
                {
                    foreach (var item in risks)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.FIRE_JOB_ID = entity.ID;
                        riskList.Add(item);
                    }
                }
                var users = entity.Nav_Users;
                if (users != null && users.Any())
                {
                    users = users.Where(t => !t.IS_DELETED).ToList();
                }
                entity.Nav_Users = null;
                var userIds = this.GetEntities<T_FO_FIRE_JOB_USER>(t => t.FIRE_JOB_ID == entity.ID, new BaseFilter(entity.ORG_ID)).Select(m => m.ID).ToList();
                var userFileIds = this.GetEntities<T_FO_FIRE_JOB_USER_FILE>(t => userIds.Contains(t.FIRE_JOB_USER_ID), new BaseFilter(entity.ORG_ID)).Select(m => m.ID).ToList();
                var userFileList = new List<T_FO_FIRE_JOB_USER_FILE>();
                var userList = new List<T_FO_FIRE_JOB_USER>();
                if (users != null && users.Any())
                {
                    var userTypes = this.GetEntities<T_OG_RELATED_USER_TYPE>(t => t.NAME == "动火操作人员" || t.NAME == "瓦检员" || t.NAME == "喷水人员", new BaseFilter(entity.ORG_ID));
                    var userTypeIds = userTypes.Select(m => m.ID).ToList();
                    var dhUser = userTypes.FirstOrDefault(t => t.NAME == "动火操作人员");
                    if (dhUser == null)
                    {
                        throw new Exception("人员类别未维护动火操作人员，请到系统管理添加名称为动火操作人员的人员类别");
                    }
                    else
                    {
                        var dhUserHas = users.FirstOrDefault(t => t.USER_TYPE_ID == dhUser.ID);
                        if (dhUserHas == null)
                        {
                            throw new Exception("作业人员必须要有动火操作人员");
                        }
                    }
                    var dhCers = users.FirstOrDefault(t => t.USER_TYPE_ID == dhUser.ID && t.CERTIFICATE_CODE == null);
                    if (dhCers != null)
                    {
                        throw new Exception("动火操作人员必须填写证书编号");
                    }
                    var dhfiles = users.FirstOrDefault(t => t.USER_TYPE_ID == dhUser.ID && (t.Nav_UserFiles == null || !t.Nav_UserFiles.Any()));
                    if (dhfiles != null)
                    {
                        throw new Exception("动火操作人员必须上传附件");
                    }
                    //var wjUser = userTypes.FirstOrDefault(t => t.NAME == "瓦检员");
                    //if (wjUser == null)
                    //{
                    //    throw new Exception("人员类别未维护瓦检员，请到系统管理添加名称为瓦检员的人员类别");
                    //}
                    //else
                    //{
                    //    var wjUserHas = users.FirstOrDefault(t => t.USER_TYPE_ID == wjUser.ID);
                    //    if (wjUserHas == null)
                    //    {
                    //        throw new Exception("作业人员必须要有瓦检员");
                    //    }
                    //}
                    //var psUser = userTypes.FirstOrDefault(t => t.NAME == "喷水人员");
                    //if (psUser == null)
                    //{
                    //    throw new Exception("人员类别未维护喷水人员，请到系统管理添加名称为喷水人员的人员类别");
                    //}
                    //else
                    //{
                    //    var psUserHas = users.FirstOrDefault(t => t.USER_TYPE_ID == psUser.ID);
                    //    if (psUserHas == null)
                    //    {
                    //        throw new Exception("作业人员必须要有喷水人员");
                    //    }
                    //}
                    foreach (var item in users)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.FIRE_JOB_ID = entity.ID;
                        item.Nav_User = null;
                        item.Nav_UserType = null;
                        if (item.Nav_UserFiles != null && item.Nav_UserFiles.Any())
                        {
                            foreach (var userFile in item.Nav_UserFiles)
                            {
                                T_FO_FIRE_JOB_USER_FILE item2 = new T_FO_FIRE_JOB_USER_FILE();
                                item2.ORG_ID = entity.ORG_ID;
                                item2.FIRE_JOB_USER_ID = item.ID;
                                item2.Nav_ImgFile = null;
                                item2.IMG_FILE_ID = userFile.IMG_FILE_ID;
                                userFileList.Add(item2);
                            }
                        }
                        item.Nav_UserFiles = null;
                        userList.Add(item);
                    }
                }
                else
                {
                    throw new Exception("作业人员不能为空");
                }
                var fireFiles = entity.Nav_FireFiles;
                if (fireFiles != null && fireFiles.Any())
                {
                    fireFiles = fireFiles.Where(t => !t.IS_DELETED).ToList();
                }
                entity.Nav_FireFiles = null;
                var fireFileIds = this.GetEntities<T_FO_FIRE_JOB_FIRE_FILE>(t => t.FIRE_JOB_JOB_ID == entity.ID, new BaseFilter(entity.ORG_ID)).Select(m => m.ID).ToList();
                var fireFileList = new List<T_FO_FIRE_JOB_FIRE_FILE>();
                if (fireFiles != null && fireFiles.Any())
                {
                    foreach (var item in fireFiles)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.FIRE_JOB_JOB_ID = entity.ID;
                        item.Nav_ImgFile = null;
                        fireFileList.Add(item);
                    }
                }
                var monitorFiles = entity.Nav_MonitorFiles;
                if (monitorFiles != null && monitorFiles.Any())
                {
                    monitorFiles = monitorFiles.Where(t => !t.IS_DELETED).ToList();
                }
                entity.Nav_MonitorFiles = null;
                var monitorFileIds = this.GetEntities<T_FO_FIRE_JOB_MONITOR_FILE>(t => t.FIRE_JOB_ID == entity.ID, new BaseFilter(entity.ORG_ID)).Select(m => m.ID).ToList();
                var monitorFileList = new List<T_FO_FIRE_JOB_MONITOR_FILE>();
                if (monitorFiles != null && monitorFiles.Any())
                {
                    foreach (var item in monitorFiles)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.FIRE_JOB_ID = entity.ID;
                        item.Nav_ImgFile = null;
                        monitorFileList.Add(item);
                    }
                }
                T_FM_NOTIFICATION_TASK task = null;
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                //监护人员填写
                if (entity.FIRE_STATUS == FOFireStatus.Monitor)
                {
                    if (string.IsNullOrEmpty(entity.COMPLETED_CONTENT))
                        throw new Exception("动火作业完工验收情况必须填写");
                    if (entity.IS_LEAVE == null)
                            throw new Exception("是否撤离必须填写");
                        if (entity.IS_LEAVE == FOYesOrNoEnum.No)
                            throw new Exception("不可撤离请稍后再进行验收");
                        if (entity.ACT_END_DATE == null)
                            throw new Exception("动火实际结束时间必须填写");
                        if (entity.LEAVE_DATE == null)
                            throw new Exception("离开现场时间必须填写");
                        if (monitorFileList == null || !monitorFileList.Any())
                            throw new Exception("必须上传完工验收附件");
                        var detailNeed = detailList.FirstOrDefault(t => (t.JOB_STEP == FOJobStepEnum.Ing && t.IS_CONFIRM_NEW == false) || (t.JOB_STEP == FOJobStepEnum.After && t.IS_CONFIRM_NEW == false));
                        if (detailNeed != null)
                            throw new Exception("作业中或作业后未全部确认！");
                        var detailAfterIds = detailList.Where(t => t.JOB_STEP != FOJobStepEnum.Pre).Select(m=>m.ID).ToList();
                        var fileAfter = detailFileList.FirstOrDefault(t => detailAfterIds.Contains(t.FIRE_JOB_DETAIL_ID));
                        if(fileAfter == null)
                            throw new Exception("作业中或作业后必须上传一个附件！");
                        //作业前不删
                        var noDeleteIds = detailInfos.Where(t => t.JOB_STEP == FOJobStepEnum.Pre).Select(t => t.ID).ToList();
                        detailIds = detailIds.Where(t => !noDeleteIds.Contains(t)).ToList();
                        var noDeleteFileIds = detailFileInfos.Where(t => noDeleteIds.Contains(t.FIRE_JOB_DETAIL_ID)).Select(t => t.ID).ToList();
                        detailFileIds = detailFileIds.Where(t => !noDeleteFileIds.Contains(t)).ToList();
                        //触发给动火部门负责人、安全管理人员审阅
                        var sendUser = this.GetEntities<T_FM_USER>(t => t.ID == entity.FIRE_USER_ID || t.ID == entity.SAFE_USER_ID, new BaseFilter(entity.ORG_ID)).ToList();
                        if (sendUser != null && sendUser.Any())
                        {
                            var sendUserIds = sendUser.Select(t => t.ID).Distinct().ToList();
                            var sendUserNames = sendUser.Select(t => t.NAME).Distinct().ToList();
                            entity.FIRE_STATUS = FOFireStatus.ReadingFinish;
                            notices = NotificationTaskService.InsertUserNoticeTaskModels("动火作业完工验收审阅", entity.ID, entity.ORG_ID, sendUserIds, sendUserNames, DateTime.Now,
              DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO043_SHOWPRINT");
                        }
                        else
                        {
                            //直接归档
                            entity.FIRE_STATUS = FOFireStatus.Archived;
                        }
                    }
                    //动火作业人员填写
                    else if (entity.FIRE_STATUS == FOFireStatus.Sign)
                    {
                        if (string.IsNullOrEmpty(entity.COMPLETED_CONDITION))
                            throw new Exception("动火作业现场条件验收情况必须填写");
                        if (entity.IS_FIRE == null)
                            throw new Exception("是否可以动火必须填写");
                        if (entity.IS_FIRE == FOYesOrNoEnum.No)
                            throw new Exception("不可动火请稍后再进行验收");
                        if (entity.ACT_DATE == null)
                            throw new Exception("动火实际开始时间必须填写");
                        if (fireFileList == null || !fireFileList.Any())
                            throw new Exception("必须上传现场条件验收附件");
                        var detailNeed = detailList.FirstOrDefault(t => t.JOB_STEP == FOJobStepEnum.Pre && t.IS_CONFIRM_NEW == false);
                        if (detailNeed != null)
                            throw new Exception("作业前未全部确认！");
                        var detailPreIds = detailList.Where(t => t.JOB_STEP == FOJobStepEnum.Pre).Select(m => m.ID).ToList();
                        var filePre = detailFileList.FirstOrDefault(t => detailPreIds.Contains(t.FIRE_JOB_DETAIL_ID));
                        if (filePre == null)
                            throw new Exception("作业前必须上传一个附件！");
                        //作业中后不删
                        var noDeleteIds = detailInfos.Where(t => t.JOB_STEP != FOJobStepEnum.Pre).Select(t => t.ID).ToList();
                        detailIds = detailIds.Where(t => !noDeleteIds.Contains(t)).ToList();
                        var noDeleteFileIds = detailFileInfos.Where(t => noDeleteIds.Contains(t.FIRE_JOB_DETAIL_ID)).Select(t => t.ID).ToList();
                        detailFileIds = detailFileIds.Where(t => !noDeleteFileIds.Contains(t)).ToList();
                        //触发给动火部门负责人、安全管理人员、矿调度人员审阅
                        var sendUser = this.GetEntities<T_FM_USER>(t => t.ID == entity.FIRE_USER_ID || t.ID == entity.SAFE_USER_ID || t.ID == entity.DISPATCH_USER_ID, new BaseFilter(entity.ORG_ID)).ToList();
                        if (sendUser != null && sendUser.Any())
                        {
                            var sendUserIds = sendUser.Select(t => t.ID).Distinct().ToList();
                            var sendUserNames = sendUser.Select(t => t.NAME).Distinct().ToList();
                            entity.FIRE_STATUS = FOFireStatus.Reading;
                            notices = NotificationTaskService.InsertUserNoticeTaskModels("动火作业现场条件验收审阅", entity.ID, entity.ORG_ID, sendUserIds, sendUserNames, DateTime.Now,
              DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO043_SHOWPRINT");
                        }
                        else
                        {
                            //没有审阅人就触发给安全管理人员填写,原设计是监护人entity.MONITOR_USER_ID
                            var monitorUser = this.GetEntity<T_FM_USER>(t => t.ID == entity.SAFE_USER_ID);
                            if (monitorUser != null)
                            {
                                entity.FIRE_STATUS = FOFireStatus.Monitor;
                                notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("动火作业全程监护", entity.ID, entity.ORG_ID, monitorUser.ID, monitorUser.NAME, DateTime.Now,
                  DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO043_2"));
                            }
                            else
                            {
                                throw new Exception("安全管理人员不能为空，请联系管理员补充填写");
                            }
                        }
                    }
                    else
                    {
                        //作业中后不删
                        var noDeleteIds = detailInfos.Where(t => t.JOB_STEP != FOJobStepEnum.Pre).Select(t => t.ID).ToList();
                        detailIds = detailIds.Where(t => !noDeleteIds.Contains(t)).ToList();
                        var noDeleteFileIds = detailFileInfos.Where(t => noDeleteIds.Contains(t.FIRE_JOB_DETAIL_ID)).Select(t => t.ID).ToList();
                        detailFileIds = detailFileIds.Where(t => !noDeleteFileIds.Contains(t)).ToList();
                        //触发审批
                        entity.STATUS = BaseData.Domain.Enums.PF.PFStandardStatus.Approving;
                        entity.FIRE_STATUS = FOFireStatus.Approving;
                        //取审批流水码
                        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 param = "工作日";
                        if (entity.IS_HOLIDAY == true)
                        {
                            param = "节假日";
                        }
                        MFlowPermitService.InsertApprove(serialCode[0], "FO043", param, entity.ID, "FO043_SHOWPRINT", entity.TaskID, true, () =>
                        {
                            if (detailFileIds != null && detailFileIds.Any())
                                this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_DETAIL_FILE>(detailFileIds);
                            if (detailIds != null && detailIds.Any())
                                this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_DETAIL>(detailIds);
                            if (userFileIds != null && userFileIds.Any())
                                this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_USER_FILE>(userFileIds);
                            if (userIds != null && userIds.Any())
                                this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_USER>(userIds);
                            if (fileIds != null && fileIds.Any())
                                this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_FILE>(fileIds);
                            if (fireFileIds != null && fireFileIds.Any())
                                this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_FIRE_FILE>(fireFileIds);
                            if (monitorFileIds != null && monitorFileIds.Any())
                                this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_MONITOR_FILE>(monitorFileIds);
                            if (riskIds != null && riskIds.Any())
                                this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_RISK>(riskIds);
                            if (entity != null)
                                UpdateEntityNoCommit(entity);
                            if (detailList != null && detailList.Any())
                                this.BantchSaveEntityNoCommit(detailList);
                            if (detailFileList != null && detailFileList.Any())
                                this.BantchSaveEntityNoCommit(detailFileList);
                            if (userList != null && userList.Any())
                                this.BantchSaveEntityNoCommit(userList);
                            if (userFileList != null && userFileList.Any())
                                this.BantchSaveEntityNoCommit(userFileList);
                            if (riskList != null && riskList.Any())
                                this.BantchSaveEntityNoCommit(riskList);
                            if (monitorFileList != null && monitorFileList.Any())
                                this.BantchSaveEntityNoCommit(monitorFileList);
                            if (fireFileList != null && fireFileList.Any())
                                this.BantchSaveEntityNoCommit(fireFileList);
                            if (fileList != null && fileList.Any())
                                this.BantchSaveEntityNoCommit(fileList);
                        }, null, null, null, null, null, "FO043_SHOWPRINT", null,null, FMTASKTYPE.JobSite);
                        return true;
                    }
                  
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "FO043_SHOWPRINT";
                    }
                }
                this.UnifiedCommit(() =>
                {
                    if (detailFileIds != null && detailFileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_DETAIL_FILE>(detailFileIds);
                    if (detailIds != null && detailIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_DETAIL>(detailIds);
                    if (userFileIds != null && userFileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_USER_FILE>(userFileIds);
                    if (userIds != null && userIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_USER>(userIds);
                    if (fileIds != null && fileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_FILE>(fileIds);
                    if (fireFileIds != null && fireFileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_FIRE_FILE>(fireFileIds);
                    if (monitorFileIds != null && monitorFileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_MONITOR_FILE>(monitorFileIds);
                    if (riskIds != null && riskIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_FIRE_JOB_RISK>(riskIds);
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (detailList != null && detailList.Any())
                        this.BantchSaveEntityNoCommit(detailList);
                    if (detailFileList != null && detailFileList.Any())
                        this.BantchSaveEntityNoCommit(detailFileList);
                    if (userList != null && userList.Any())
                        this.BantchSaveEntityNoCommit(userList);
                    if (userFileList != null && userFileList.Any())
                        this.BantchSaveEntityNoCommit(userFileList);
                    if (riskList != null && riskList.Any())
                        this.BantchSaveEntityNoCommit(riskList);
                    if (monitorFileList != null && monitorFileList.Any())
                        this.BantchSaveEntityNoCommit(monitorFileList);
                    if (fireFileList != null && fireFileList.Any())
                        this.BantchSaveEntityNoCommit(fireFileList);
                    if (fileList != null && fileList.Any())
                        this.BantchSaveEntityNoCommit(fileList);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (task != null)
                        UpdateEntityNoCommit(task);
                });
                return true;
            });
        }
        /// <summary>
        /// 部门负责人、安全管理人员、矿调度人员审阅
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("IdentityUpdate")]
        public JsonActionResult<bool> IdentityUpdate([FromBody] T_FO_FIRE_JOB entity)
        {
            return SafeExecute(() =>
            {
                var fire = this.GetEntity<T_FO_FIRE_JOB>(entity.ID);
                var detailList = new List<T_FO_FIRE_JOB_DETAIL>();
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        userId = currTask.USER_ID;
                    }
                }
                if (fire == null)
                {
                    throw new Exception("未获取到动火作业工作票数据，请联系管理员确认");
                }
                T_FM_NOTIFICATION_TASK notice = null;
                if (fire.FIRE_STATUS == FOFireStatus.Reading)
                {
                    if (fire.FIRE_USER_ID == userId)
                    {
                        fire.USER_DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                    }
                    if (fire.SAFE_USER_ID == userId)
                    {
                        fire.SAFE_DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                    }
                    if (fire.DISPATCH_USER_ID == userId)
                    {
                        fire.DISPATCH_DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                    }
                    if (fire.USER_DEAL_STATUS == FOUserShiftStatusEnum.已处理 && fire.SAFE_DEAL_STATUS == FOUserShiftStatusEnum.已处理 && fire.DISPATCH_DEAL_STATUS == FOUserShiftStatusEnum.已处理)
                    {
                        //触发给安全管理人员填写
                        var monitorUser = this.GetEntity<T_FM_USER>(t => t.ID == fire.SAFE_USER_ID);
                        if (monitorUser != null)
                        {
                            fire.FIRE_STATUS = FOFireStatus.Monitor;
                            notice = NotificationTaskService.InsertUserNoticeTaskModel("动火作业全程监护", fire.ID, fire.ORG_ID, monitorUser.ID, monitorUser.NAME, DateTime.Now,
              DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO043_2");
                        }
                        else
                        {
                            throw new Exception("安全管理人员不能为空，请联系管理员补充填写");
                        }
                    }
                }
                else if (fire.FIRE_STATUS == FOFireStatus.ReadingFinish)
                {
                    if (fire.FIRE_USER_ID == userId)
                    {
                        fire.USER_DEAL_FINISH_STATUS = FOUserShiftStatusEnum.已处理;
                    }
                    if (fire.SAFE_USER_ID == userId)
                    {
                        fire.SAFE_DEAL_FINISH_STATUS = FOUserShiftStatusEnum.已处理;
                    }
                    if (fire.USER_DEAL_FINISH_STATUS == FOUserShiftStatusEnum.已处理 && fire.SAFE_DEAL_FINISH_STATUS == FOUserShiftStatusEnum.已处理)
                    {
                        fire.FIRE_STATUS = FOFireStatus.Archived;
                    }
                }
                else
                {
                    throw new Exception("当前非审阅状态，请联系管理员排查");
                }
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "FO043_SHOWPRINT";
                }
                UnifiedCommit(() =>
                {
                    if (fire != null)
                        this.UpdateEntityNoCommit(fire);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    if (notice != null)
                        this.UpdateEntityNoCommit(notice);
                });
                return true;
            });
        }
        /// <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/FOFireJob/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_FIRE_JOB>(model.DATA_ID, new string[] { "Nav_ApplyUser" });
                entity.STATUS = BaseData.Domain.Enums.PF.PFStandardStatus.Rejected;
                entity.FIRE_STATUS = FOFireStatus.Rejected;
                entity.USER_DEAL_STATUS = FOUserShiftStatusEnum.待处理;
                entity.USER_DEAL_FINISH_STATUS = FOUserShiftStatusEnum.待处理;
                entity.SAFE_DEAL_STATUS = FOUserShiftStatusEnum.待处理;
                entity.SAFE_DEAL_FINISH_STATUS = FOUserShiftStatusEnum.待处理;
                entity.DISPATCH_DEAL_STATUS = FOUserShiftStatusEnum.待处理;
                var persons = this.GetEntities<T_FO_FIRE_JOB_USER>(t => t.FIRE_JOB_ID == model.DATA_ID, new BaseFilter(entity.ORG_ID));
                if (persons.Any())
                    persons.ForEach(t => { t.DEAL_STATUS = 0; t.Nav_User = null; });
                //直接驳回给申请人
                T_FM_NOTIFICATION_TASK notice = NotificationTaskService.InsertUserNoticeTaskModel("动火作业工作票已被驳回", entity.ID, entity.ORG_ID, (Guid)entity.APPLY_USER_ID, entity.Nav_ApplyUser.NAME, DateTime.Now,
                DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO043");
                //当前节点其他审核人待办消除
                var taskOtherIds = this.GetEntities<T_FM_NOTIFICATION_TASK>(t => t.SOURCE_DATA_ID == model.ID && t.NOTICE_STATUS == 0, new BaseFilter(entity.ORG_ID)).Select(t => t.ID).ToList();
                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 (persons != null && persons.Any())
                        BantchUpdateEntityNoCommit(persons);
                    if (taskOtherIds != null && taskOtherIds.Any())
                        BantchDeleteEntityNoCommit<T_FM_NOTIFICATION_TASK>(taskOtherIds);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                });
                return true;
            });
        }
        /// <summary>
        /// 作业名称onchange事件
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetAnalyzeDetail")]
        public JsonActionResult<T_FO_FIRE_JOB> GetAnalyzeDetail([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                T_FO_FIRE_JOB main = new T_FO_FIRE_JOB();
                //传入的作业名称ID不为空
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    var link = GetEntity<T_HM_OPERATION_LINK>(t => t.OPERATION_STEP_ID == Guid.Parse(filter.Keyword) && t.STATUS == (int)STATUSEnum.启用, new string[] { "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures" });
                    if (link != null)
                    {
                        main.AUDIT_LEVEL = link.AUDIT_LEVEL;
                        main.EVALUATE_LEVEL = link.EVALUATE_LEVEL !=null?(SKEvaluateLevelEnum)link.EVALUATE_LEVEL: MS.Domain.Enums.SK.SKEvaluateLevelEnum.低风险;
                        List<T_FO_FIRE_JOB_DETAIL> details = new List<T_FO_FIRE_JOB_DETAIL>();
                        if (link.Nav_SafeConfirms != null && link.Nav_SafeConfirms.Any())
                        {
                            foreach (var item in link.Nav_SafeConfirms.OrderBy(t=>t.NUM))
                            {
                                T_FO_FIRE_JOB_DETAIL de = new T_FO_FIRE_JOB_DETAIL();
                                de.ORG_ID = item.ORG_ID;
                                de.NUM = item.NUM;
                                de.JOB_STEP = FOJobStepEnum.Pre;
                                de.CONTENT = item.NAME;
                                details.Add(de);
                            }
                        }
                        if (link.Nav_SafeMeasures != null && link.Nav_SafeMeasures.Any())
                        {
                            foreach (var item in link.Nav_SafeMeasures.OrderBy(t => t.NUM))
                            {
                                T_FO_FIRE_JOB_DETAIL de = new T_FO_FIRE_JOB_DETAIL();
                                de.ORG_ID = item.ORG_ID;
                                de.NUM = item.NUM;
                                de.JOB_STEP = FOJobStepEnum.Ing;
                                de.CONTENT = item.NAME;
                                details.Add(de);
                            }
                        }
                        if (link.Nav_DealMeasures != null && link.Nav_DealMeasures.Any())
                        {
                            foreach (var item in link.Nav_DealMeasures.OrderBy(t => t.NUM))
                            {
                                T_FO_FIRE_JOB_DETAIL de = new T_FO_FIRE_JOB_DETAIL();
                                de.ORG_ID = item.ORG_ID;
                                de.NUM = item.NUM;
                                de.JOB_STEP = FOJobStepEnum.After;
                                de.CONTENT = item.NAME;
                                details.Add(de);
                            }
                        }
                        main.Nav_Details = details.OrderBy(t => t.JOB_STEP).ThenBy(m => m.NUM).ToList();
                    }
                }
                return main;
            });
        }

        /// <summary>
        /// 动火部门onchange事件
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetSafeUser")]
        public JsonActionResult<T_FM_USER> GetSafeUser([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                T_FM_USER main = new T_FM_USER();
                //传入的作业名称ID不为空
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    main = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == Guid.Parse(filter.Keyword) && t.ENABLE_STATUS == 0 && t.Nav_ApproveRole!=null && t.Nav_ApproveRole.NAME.Contains("安全员"));
                }
                return main;
            });
        }
    }
}
