using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.LR;
using APT.MS.Domain.Entities.WB;
using APT.MS.Domain.Enums;
using APT.Utility;
using Castle.Core.Internal;
using InfluxData.Net.InfluxDb.Models.Responses;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.Differencing;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.SC.WebApi.Controllers.Api.WB
{
    [Route("api/WB/WBDangerousJob")]
    public class WBDangerousJobController : AuthorizeApiController<T_WB_DANGEROUS_JOB>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        public WBDangerousJobController(IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService)
        {
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_WB_DANGEROUS_JOB entity)
        {
            return SafeExecute(() =>
            {
                //T_FM_NOTIFICATION_TASK finishNotice = null;
                //T_FM_NOTIFICATION_TASK sendNotice = null;
                //T_WB_DANGEROUS_JOB_AUDIT newAudit = null;
                var Nav_Users = entity.Nav_Users;
                var Nav_Files = entity.Nav_Files;
                var Nav_Details = entity.Nav_Detail;

                entity.Nav_Users = null;
                entity.Nav_Files = null;
                entity.Nav_Detail = null;
                T_PF_APPROVE approve = null;
                ICollection<T_PF_APPROVE_DETAIL> listApproveDetail = null;
                T_FM_NOTIFICATION_TASK finishTask = null;
                T_FM_NOTIFICATION_TASK nextTask = null;
                string CALLBACK_INTERFACE = "";
                List<string> listDATA_ID = new List<string>();
                if (entity.USER_ID == Guid.Empty)
                {
                    throw new Exception("请选择现场监护人！");
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    //Guid userId = Guid.Empty;
                    //string userName = "";
                    if (entity.STATUS == PFStandardStatus.Rejected)
                    {
                        var lastAudit = GetEntities<T_WB_DANGEROUS_JOB_AUDIT>(t => t.PARENT_ID == entity.ID, new BaseFilter(entity.ORG_ID));
                        var lastIds = lastAudit.Select(t => t.ID).ToList();
                        BantchDeleteEntity<T_WB_DANGEROUS_JOB_AUDIT>(lastIds);
                    }
                    if (!entity.START_TIME.HasValue)
                    {
                        throw new Exception("请选择作业开始时间！");
                    }
                    if (!entity.END_TIME.HasValue)
                    {
                        throw new Exception("请选择作业结束时间！");
                    }
                    if (entity.START_TIME.Value > entity.END_TIME.Value)
                    {
                        throw new Exception("作业开始时间不能大于作业结束时间！");
                    }
                    if (entity.START_TIME.Value < DateTime.Now.AddMinutes(1))
                    {
                        throw new Exception("作业开始时间必须大于当前时间！");
                    }
                    if (Nav_Users == null || !Nav_Users.Any())
                    {
                        throw new Exception("请选择作业人员！");
                    }
                    //public Guid USER_ID { get; set; }
                    if (entity.USER_ID != Guid.Empty)
                    {
                        var checkU = Nav_Users.Where(e => e.USER_ID == entity.USER_ID);
                        if (checkU != null && checkU.Any())
                        {
                            throw new Exception("现场监护人不能是作业人员！");
                        }
                    }
                    //newAudit = new T_WB_DANGEROUS_JOB_AUDIT();
                    //newAudit.ID = Guid.NewGuid();
                    //newAudit.ORG_ID = entity.ORG_ID;
                    //newAudit.PARENT_ID = entity.ID;
                    foreach (var item in Nav_Details)
                    {
                        item.PARENT_ID = entity.ID;
                        item.ORG_ID = entity.ORG_ID;
                    }
                    foreach (var item in Nav_Users)
                    {
                        item.Nav_User = null;
                    }
                    var project = GetEntity<T_WB_REGISTER>(t => t.PROJECT_ID == entity.PROJECT_ID, "Nav_Item2");
                    var firstAudit = project.Nav_Item2.FirstOrDefault(t => t.WORKTYPE == WORKTYPE.现场负责人);
                    if (firstAudit == null)
                    {
                        throw new Exception("该单位人员信息未配置工种为【现场负责人】的人员！");
                    }
                    entity.STATUS = PFStandardStatus.Approving;
                    //var user = GetEntity<T_FM_USER>(t => t.CODE == firstAudit.PHONE);
                    //if (user == null)
                    //{
                    //    user = GetEntity<T_FM_USER>(t => t.NAME == firstAudit.NAME);
                    //}
                    //userId = user.ID;
                    //userName = user.NAME;
                    //newAudit.AUDIT_STATUS = 0;
                    //newAudit.USER_ID = userId;
                    //sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业-现场负责人审批", entity.ID, entity.ORG_ID, userId, userName, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB013_SHOWPRINT");
                    //if (entity.TaskID != Guid.Empty)
                    //{
                    //    finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID);
                    //}

                    var projet = GetEntity<T_WB_PROJECT_INPUT>(entity.PROJECT_ID, "Nav_User", "Nav_SceneUser");
                    if (projet.USER_ID == Guid.Empty)
                    {
                        throw new Exception("请完善该项目【建设项目负责人】");
                    }
                    if (projet.SCENE_USER_ID == Guid.Empty)
                    {
                        throw new Exception("请完善该项目【建设项目现场负责人】");
                    }
                    var register = GetEntity<T_WB_REGISTER>(e => e.PROJECT_ID == entity.PROJECT_ID);
                    var listRegister2 = GetEntities<T_WB_REGISTER_2>(e => e.PARENT_ID == register.ID && e.IS_LOGIN && (e.WORKTYPE == WORKTYPE.现场负责人 || e.WORKTYPE == WORKTYPE.项目监理), null, null);
                    if (listRegister2 == null)
                    {
                        throw new Exception("请完善【外包单位信息登记表】中对应改项目的现场负责人与项目监理");
                    }
                    var listPhone1 = listRegister2.Where(e => e.WORKTYPE == WORKTYPE.现场负责人).Select(e => e.PHONE);
                    if (listPhone1 == null || !listPhone1.Any() || listPhone1.Count() < 1)
                    {
                        throw new Exception("请完善【外包单位信息登记表】工种为【现场负责人】信息");
                    }
                    var listPhone3 = listRegister2.Where(e => e.WORKTYPE == WORKTYPE.项目监理).Select(e => e.PHONE);
                    //if (listPhone3 == null || !listPhone3.Any() || listPhone3.Count() < 1)
                    //{
                    //    throw new Exception("请完善【外包单位信息登记表】工种为【项目监理】信息");
                    //}
                    var listPhone = listRegister2.Select(e => e.PHONE);
                    var listUser = GetEntities<T_FM_USER>(e => e.PROJECT_ID == entity.PROJECT_ID && listPhone.Contains(e.PHONE), null, null);
                    Dictionary<int, T_FM_USER> dicApproveUser = new Dictionary<int, T_FM_USER>();

                    var User1 = listUser.FirstOrDefault(e => listPhone1.Contains(e.PHONE) || listPhone1.Contains(e.CODE) && e.ENABLE_STATUS == 0);
                    if (User1 == null)
                    {
                        throw new Exception("用户列表信息中该项目工种为【现场负责人】的信息缺失");
                    }
                    T_FM_USER User3 = null;
                    if (listPhone3 != null)
                    {
                        User3 = listUser.FirstOrDefault(e => listPhone3.Contains(e.PHONE) || listPhone3.Contains(e.CODE) && e.ENABLE_STATUS == 0);
                        //if (User3 == null)
                        //{
                        //    throw new Exception("用户列表信息中该项目工种为【现场负责人】的信息缺失");
                        //}
                    }
                    dicApproveUser.Add(1, User1);//外包单位现场负责人
                    if (User3 != null)
                    {
                        dicApproveUser.Add(2, User3);//外包工程项目监理
                    }
                    dicApproveUser.Add(3, projet.Nav_SceneUser);//建设项目现场负责人
                    dicApproveUser.Add(4, projet.Nav_User);//建设项目负责人
                    string Msg = "";
                    approve = MFlowPermitService.GetApproveInfo("WB013", null, entity.ID, "WB013_SHOWPRINT", entity.TaskID, "WB013_SHOWPRINT", null, dicApproveUser, null, "", ref Msg, ref finishTask, ref nextTask, ref CALLBACK_INTERFACE, ref listDATA_ID);
                    if (Msg != null && !string.IsNullOrEmpty(Msg))
                    {
                        throw new Exception(Msg);//如果有问题 进行提示
                    }
                    //listApproveDetail = approve.Nav_ApproveDetails;
                    listApproveDetail = approve.Nav_ApproveDetails.Where(e => e.APPROVE_USER_ID.HasValue && e.APPROVE_USER_ID != Guid.Empty).ToList();
                    approve.Nav_ApproveDetails = null;
                    approve.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                }

                UnifiedCommit(() =>
                {
                    UpdateEntity(entity);
                    if (Nav_Users != null && Nav_Users.Any())
                        BantchSaveEntityNoCommit(Nav_Users);
                    if (Nav_Files != null && Nav_Files.Any())
                        BantchSaveEntityNoCommit(Nav_Files);
                    if (Nav_Details != null && Nav_Details.Any())
                        BantchSaveEntityNoCommit(Nav_Details);
                    //if (sendNotice != null)
                    //    AddEntityNoCommit(sendNotice);
                    //if (newAudit != null)
                    //    AddEntityNoCommit(newAudit);
                    //if (finishNotice != null)
                    //    UpdateEntityNoCommit(finishNotice);
                    if (approve != null)
                        UpdateEntity(approve);
                    if (listApproveDetail != null && listApproveDetail.Any())
                        BantchSaveEntityNoCommit(listApproveDetail);
                    if (finishTask != null)
                        UpdateEntity(finishTask);
                    if (nextTask != null)
                        UpdateEntity(nextTask);
                });

                //执行信息
                if (!string.IsNullOrEmpty(CALLBACK_INTERFACE))
                {
                    if (CALLBACK_INTERFACE.EndsWith("New"))
                    {
                        this.UnifiedCommit(() =>
                        {
                            ApproveCallBackService.CallBackNew(CALLBACK_INTERFACE, approve, false);
                        });
                    }
                    else
                    {
                        this.UnifiedCommit(() =>
                        {
                            ApproveCallBackService.CallBack(CALLBACK_INTERFACE, listDATA_ID);
                        });
                    }
                }
                return true;
            });
        }


        ///// <summary>
        ///// 签到
        ///// </summary>
        ///// <param name="pageFilter"></param>
        ///// <returns></returns>
        //[HttpPost, Route("UserDisAgree")]
        //public JsonActionResult<bool> UserDisAgree([FromBody] KeywordFilter filter)
        //{
        //    return SafeExecute<bool>(() =>
        //    {
        //        var id = Guid.Parse(filter.Parameter1);
        //        var taskID = Guid.Parse(filter.Parameter2);
        //        var orgId = Guid.Parse(filter.Parameter3);
        //        var opinion = filter.Parameter4;

        //        if (string.IsNullOrEmpty(opinion))
        //        {
        //            throw new Exception("请填写理由！");
        //        }
        //        var dangerousJob = GetEntity<T_WB_DANGEROUS_JOB>(t => t.ID == id, "Nav_Audit");
        //        dangerousJob.STATUS = PFStandardStatus.Rejected;
        //        var currUser = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
        //        var currAudit = dangerousJob.Nav_Audit.FirstOrDefault(t => t.USER_ID == currUser);
        //        currAudit.AUDIT_DATE = DateTime.Now;
        //        currAudit.ISORNOT = ISORNOT.否;
        //        currAudit.AUDIT_OPINION = opinion;
        //        var finishTask = NotificationTaskService.FOGetTaskFinishModel(taskID, id);

        //        var sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业-审批驳回", id, orgId, (Guid)dangerousJob.MODIFIER_ID, GetEntity<T_FM_USER>(t => t.ID == dangerousJob.MODIFIER_ID).NAME, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB013");
        //        UnifiedCommit(() =>
        //        {
        //            if (sendNotice != null)
        //                AddEntityNoCommit(sendNotice);
        //            if (finishTask != null)
        //                UpdateEntityNoCommit(finishTask);
        //            if (dangerousJob != null)
        //                UpdateEntityNoCommit(dangerousJob);
        //            if (currAudit != null)
        //                UpdateEntityNoCommit(currAudit);

        //        });
        //        return true;
        //    });
        //}

        /// <summary>
        /// 危险作业申请审批驳回
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, Route("UserDisAgree")]
        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 dangerousJob = GetEntity<T_WB_DANGEROUS_JOB>(model.DATA_ID, null);
                dangerousJob.STATUS = PFStandardStatus.Rejected;
                var currUser = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var UackUserID = Guid.Empty;
                if (model.CREATER_ID.HasValue)
                {
                    UackUserID = model.CREATER_ID.Value;
                }
                if (UackUserID == Guid.Empty && dangerousJob.MODIFIER_ID.HasValue)
                {
                    UackUserID = dangerousJob.MODIFIER_ID.Value;
                }
                if (UackUserID == Guid.Empty && dangerousJob.CREATER_ID.HasValue)
                {
                    UackUserID = dangerousJob.CREATER_ID.Value;
                }
                if (UackUserID == Guid.Empty)
                {
                    throw new Exception("获取危险作业申请人信息失败！");
                }

                var sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业-审批驳回", dangerousJob.ID, dangerousJob.ORG_ID, UackUserID, GetEntity<T_FM_USER>(UackUserID).NAME, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB013");

                UnifiedCommit(() =>
                {
                    if (dangerousJob != null)
                        UpdateEntityNoCommit(dangerousJob);
                    if (sendNotice != null)
                        AddEntityNoCommit(sendNotice);

                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);
                    if (listAppDetail != null && listAppDetail.Count > 0)
                        BantchUpdateEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                });
                return true;
            });
        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetApprove")]
        public JsonActionResult<T_WB_DANGEROUS_JOB> GetApprove([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                filter.IgnoreDataRule = true;
                var result = GetEntity<T_WB_DANGEROUS_JOB>(null, filter, null);
                IEnumerable<T_PF_APPROVE> approve = GetEntities<T_PF_APPROVE>(e => e.DATA_ID == result.ID, null, "Nav_ApproveDetails.Nav_ApproveUser");
                if (approve != null && approve.Any())
                {
                    result.Nav_Approve = approve.OrderByDescending(e => e.CREATE_TIME).ToList()[0];
                }
                return result;
            });
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdateDisclose")]
        public JsonActionResult<bool> FullUpdateDisclose([FromBody] T_WB_DANGEROUS_JOB entity)
        {
            return SafeExecute(() =>
            {
                T_FM_NOTIFICATION_TASK finishNotice = null;
                List<T_FM_NOTIFICATION_TASK> sendNotices = new List<T_FM_NOTIFICATION_TASK>();
                var Nav_Users = entity.Nav_DisCloseUsers;
                var Nav_Files = entity.Nav_DisCloseFiles;
                var Nav_DisCloseDetails = entity.Nav_DisCloseDetails;

                entity.Nav_Users = null;
                entity.Nav_Files = null;
                entity.Nav_DisCloseDetails = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "WB019_SHOWPRINT");
                    }
                    if (entity.START_TIME.HasValue && entity.START_TIME.Value < DateTime.Now)
                    {
                        T_FM_NOTIFICATION_TASK sendNotice = null;
                        entity.STATUS = PFStandardStatus.Close;
                        string userName = "";
                        if (entity.CREATER_ID.HasValue)
                        {
                            var userId = entity.CREATER_ID.Value;
                            userName = GetEntity<T_FM_USER>(userId)?.NAME;
                            sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("危险作业申请安全技术交底已经超期，请重新发起", Guid.Empty, entity.ORG_ID, userId, userName, DateTime.Now, DateTime.Now.AddDays(1), 2, "");
                        }
                        if (finishNotice != null)
                        {
                            UnifiedCommit(() =>
                            {
                                UpdateEntityNoCommit(finishNotice);
                                if (sendNotice != null)
                                    UpdateEntityNoCommit(sendNotice);
                            });
                        }
                        throw new Exception("该危险作业申请已过期，请沟通" + (string.IsNullOrEmpty(userName) ? "" : "【" + userName + "】") + "重新申请！");
                    }
                    else
                    {
                        var currUser = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                        entity.DISCLOSE_STATUS = PFStandardStatus.Sign;
                        if (entity.DISCLOSE_USER_ID == currUser)
                        {
                            entity.DEAL_STATUS = 1;
                        }
                        else
                        {
                            sendNotices.Add(NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业-交底", entity.ID, entity.ORG_ID, (Guid)entity.DISCLOSE_USER_ID, GetEntity<T_FM_USER>(t => t.ID == entity.DISCLOSE_USER_ID).NAME, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB019_SHOWPRINT"));
                        }
                        foreach (var user in Nav_Users)
                        {
                            sendNotices.Add(NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业-交底", entity.ID, entity.ORG_ID, (Guid)user.USER_ID, GetEntity<T_FM_USER>(t => t.ID == user.USER_ID).NAME, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB019_SHOWPRINT"));
                            if (user.USER_ID.HasValue && user.USER_ID == currUser)
                            {
                                user.DEAL_STATUS = 1;
                                user.MODIFY_TIME = DateTime.Now;
                            }
                        }
                        sendNotices.ForEach(o =>
                        {
                            if (o.USER_ID == currUser.Value)
                            {
                                o.NOTICE_STATUS = 1;
                                o.TASK_DT = DateTime.Now;
                                o.MODIFIER_ID = currUser;
                            }
                        });
                    }
                }
                foreach (var user in Nav_Users)
                {
                    user.Nav_User = null;
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (Nav_Users != null && Nav_Users.Any())
                        BantchSaveEntityNoCommit(Nav_Users);
                    if (Nav_Files != null && Nav_Files.Any())
                        BantchSaveEntityNoCommit(Nav_Files);
                    if (Nav_DisCloseDetails != null && Nav_DisCloseDetails.Any())
                        BantchSaveEntityNoCommit(Nav_DisCloseDetails);
                    if (sendNotices != null && sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });
                return true;
            });
        }
        /// <summary>
        /// 签到
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("discloseSign")]
        public JsonActionResult<bool> discloseSign([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var id = Guid.Parse(filter.Parameter1);
                var taskID = Guid.Parse(filter.Parameter2);
                var userID = Guid.Parse(filter.Parameter3);
                var orgId = filter.GetOrgId();
                var sendUserID = Guid.Empty;
                var sendUserNAME = "";
                var users = GetEntities<T_WB_DANGEROUS_JOB_DISCLOSE_USER>(t => t.PARENT_ID == id, new BaseFilter(orgId));
                var currUser = users.FirstOrDefault(t => t.USER_ID == userID);
                T_WB_DANGEROUS_JOB model = null;
                T_FM_NOTIFICATION_TASK finishTask = null;
                T_FM_NOTIFICATION_TASK sendNotice = null;
                if (currUser == null)
                {
                    model = GetEntity<T_WB_DANGEROUS_JOB>(id, "Nav_Project.Nav_SceneUser");
                    model.DEAL_STATUS = 1;
                    model.MODIFY_TIME = DateTime.Now;
                }
                else
                {
                    currUser.DEAL_STATUS = 1;
                    currUser.MODIFY_TIME = DateTime.Now;
                }
                var todoCount = users.Count(t => t.DEAL_STATUS == 0);
                if (todoCount == 0)
                {
                    if (model == null)
                    {
                        model = GetEntity<T_WB_DANGEROUS_JOB>(id, "Nav_Project.Nav_SceneUser");
                    }
                    //被交底人和交底人都已经签名后 触发 作业监察
                    if (model.DEAL_STATUS == 1)
                    {
                        model.DISCLOSE_STATUS = PFStandardStatus.Archived;
                        model.DISCLOSE_TIME = DateTime.Now;
                        sendUserID = model.Nav_Project.SCENE_USER_ID;
                        sendUserNAME = model.Nav_Project.Nav_SceneUser.NAME;
                        sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业监查人", id, orgId, sendUserID, sendUserNAME, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB021");
                    }
                }
                if (taskID != Guid.Empty)
                {
                    finishTask = NotificationTaskService.FOGetTaskFinishModel(taskID, id);
                }
                UnifiedCommit(() =>
                {
                    if (model != null)
                        UpdateEntityNoCommit(model);
                    if (currUser != null)
                        UpdateEntityNoCommit(currUser);
                    if (sendNotice != null)
                        AddEntityNoCommit(sendNotice);
                    if (finishTask != null)
                        UpdateEntityNoCommit(finishTask);

                });
                return true;
            });
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdateCheck")]
        public JsonActionResult<bool> FullUpdateCheck([FromBody] T_WB_DANGEROUS_JOB entity)
        {
            return SafeExecute(() =>
            {
                T_FM_NOTIFICATION_TASK finishNotice = null;
                List<T_FM_NOTIFICATION_TASK> sendNotices = new List<T_FM_NOTIFICATION_TASK>();
                List<T_FM_NOTIFICATION_TASK> sendNotice = null;
                List<T_WB_DANGEROUS_JOB_RECORD_DETAIL> newRecordDetails = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (!entity.MOINTER_USER_ID.HasValue)
                    {
                        throw new Exception("请选择监查人");
                    }
                    else
                    {
                        if (entity.MOINTER_USER_ID.Value == APT.Infrastructure.Api.AppContext.CurrentSession.UserID)
                        {
                            T_WB_DANGEROUS_JOB model = null;
                            mointerSign(entity.ID, entity.ORG_ID.Value, ref model, ref sendNotice, ref newRecordDetails);
                            //状态赋值  默认 检查人 已确认
                            entity.MOINTER_DEAL_STATUS = 1;
                            entity.STATUS_DETAIL = PFStandardStatus.Draft;
                            entity.STATUS_MOINTER = PFStandardStatus.Draft;
                        }
                        else
                        {
                            sendNotices.Add(NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业-监察人确认", entity.ID, entity.ORG_ID, (Guid)entity.MOINTER_USER_ID, GetEntity<T_FM_USER>(t => t.ID == entity.MOINTER_USER_ID).NAME, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB021_SHOWPRINT"));
                        }
                        if (entity.TaskID != Guid.Empty)
                        {
                            finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "WB021_SHOWPRINT");
                        }
                    }
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (sendNotices != null && sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);


                    if (sendNotice != null && sendNotice.Any())//外包工程危险作业记录  外包工程危险作业监查记录
                        BantchAddEntityNoCommit(sendNotice);
                    if (newRecordDetails != null && newRecordDetails.Any())//记录明细
                        BantchAddEntityNoCommit(newRecordDetails);
                });
                return true;
            });
        }

        private void mointerSign(Guid JOBID, Guid orgId, ref T_WB_DANGEROUS_JOB model, ref List<T_FM_NOTIFICATION_TASK> sendNotice, ref List<T_WB_DANGEROUS_JOB_RECORD_DETAIL> newRecordDetails)
        {
            model = GetEntity<T_WB_DANGEROUS_JOB>(JOBID, "Nav_MointerUser", "Nav_User", "Nav_DisCloseDetails");
            sendNotice = new List<T_FM_NOTIFICATION_TASK>();
            newRecordDetails = new List<T_WB_DANGEROUS_JOB_RECORD_DETAIL>();
            model.MOINTER_DEAL_STATUS = 1;
            var sendUserID1 = model.USER_ID;
            var sendUserNAME1 = model.Nav_User.NAME;
            var sendUserID2 = model.MOINTER_USER_ID;//监查人如果为空 就默认为操作者
            var sendUserNAME2 = model?.Nav_MointerUser?.NAME;
            if (sendUserID2 == null || sendUserID2 == Guid.Empty)
            {
                sendUserID2 = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                model.MOINTER_USER_ID = sendUserID2;
                sendUserNAME2 = GetEntity<T_FM_USER>(sendUserID2.Value).NAME;
            }

            foreach (var item in model.Nav_DisCloseDetails)
            {
                T_WB_DANGEROUS_JOB_RECORD_DETAIL newRecordDetail = new T_WB_DANGEROUS_JOB_RECORD_DETAIL();
                newRecordDetail.ID = Guid.NewGuid();
                newRecordDetail.ROW_NUM = item.ROW_NUM;
                newRecordDetail.PARENT_ID = item.PARENT_ID;
                newRecordDetail.MEASURE = item.MEASURE;
                newRecordDetail.REMARK = item.REMARK;
                newRecordDetail.ORG_ID = item.ORG_ID;
                newRecordDetail.ISORNOT = item.ISORNOT;
                newRecordDetails.Add(newRecordDetail);
            }
            model.STATUS_DETAIL = PFStandardStatus.Draft;
            model.STATUS_MOINTER = PFStandardStatus.Draft;
            sendNotice.Add(NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业记录", JOBID, orgId, sendUserID1, sendUserNAME1, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB023"));
            sendNotice.Add(NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业监查记录", JOBID, orgId, (Guid)sendUserID2, sendUserNAME2, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB025"));

        }
        /// <summary>
        /// 签到
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("mointerSign")]
        public JsonActionResult<bool> mointerSign([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var id = Guid.Parse(filter.Parameter1);
                var taskID = Guid.Parse(filter.Parameter2);
                var userID = Guid.Parse(filter.Parameter3);
                var orgId = filter.GetOrgId();
                T_WB_DANGEROUS_JOB model = null;
                List<T_FM_NOTIFICATION_TASK> sendNotice = new List<T_FM_NOTIFICATION_TASK>();
                List<T_WB_DANGEROUS_JOB_RECORD_DETAIL> newRecordDetails = new List<T_WB_DANGEROUS_JOB_RECORD_DETAIL>();
                T_FM_NOTIFICATION_TASK finishTask = null;
                mointerSign(id, orgId, ref model, ref sendNotice, ref newRecordDetails);

                //var model = GetEntity<T_WB_DANGEROUS_JOB>(id, "Nav_MointerUser", "Nav_User", "Nav_DisCloseDetails");
                //model.MOINTER_DEAL_STATUS = 1;
                //var sendUserID1 = model.USER_ID;
                //var sendUserNAME1 = model.Nav_User.NAME;
                //var sendUserID2 = model.MOINTER_USER_ID;
                //var sendUserNAME2 = model.Nav_MointerUser.NAME;
                //foreach (var item in model.Nav_DisCloseDetails)
                //{
                //    T_WB_DANGEROUS_JOB_RECORD_DETAIL newRecordDetail = new T_WB_DANGEROUS_JOB_RECORD_DETAIL();
                //    newRecordDetail.ID = Guid.NewGuid();
                //    newRecordDetail.ROW_NUM = item.ROW_NUM;
                //    newRecordDetail.PARENT_ID = item.PARENT_ID;
                //    newRecordDetail.MEASURE = item.MEASURE;
                //    newRecordDetail.REMARK = item.REMARK;
                //    newRecordDetail.ORG_ID = item.ORG_ID;
                //    newRecordDetail.ISORNOT = item.ISORNOT;
                //    newRecordDetails.Add(newRecordDetail);
                //}
                //model.STATUS_DETAIL = PFStandardStatus.Draft;
                //model.STATUS_MOINTER = PFStandardStatus.Draft;
                //sendNotice.Add(NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业记录", id, orgId, sendUserID1, sendUserNAME1, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB023"));
                //sendNotice.Add(NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业监查记录", id, orgId, (Guid)sendUserID2, sendUserNAME2, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB025"));

                if (taskID != Guid.Empty)
                {
                    finishTask = NotificationTaskService.FOGetTaskFinishModel(taskID, id);
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(model);
                    if (sendNotice != null && sendNotice.Any())
                        BantchAddEntityNoCommit(sendNotice);
                    if (newRecordDetails != null && newRecordDetails.Any())
                        BantchAddEntityNoCommit(newRecordDetails);
                    if (finishTask != null)
                        UpdateEntityNoCommit(finishTask);
                });
                return true;
            });
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdateRecord")]
        public JsonActionResult<bool> FullUpdateRecord([FromBody] T_WB_DANGEROUS_JOB entity)
        {
            return SafeExecute(() =>
            {
                T_FM_NOTIFICATION_TASK finishNotice = null;
                List<T_FM_NOTIFICATION_TASK> sendNotices = new List<T_FM_NOTIFICATION_TASK>();
                var Nav_RecordDetails = entity.Nav_RecordDetails;
                List<T_WB_DANGEROUS_JOB_RECORD_DETAIL_FILE> Files = new List<T_WB_DANGEROUS_JOB_RECORD_DETAIL_FILE>();

                entity.Nav_RecordDetails = null;
                List<int> listNotCheck = new List<int>();
                int index = 0;
                Nav_RecordDetails.ForEach(t =>
                {
                    index++;
                    if (t.Nav_Files != null && t.Nav_Files.Count() > 0)
                    {
                        t.Nav_Files.ForEach(nf =>
                        {
                            nf.PARENT_ID = t.ID;
                        });
                        Files.AddRange(t.Nav_Files);
                        t.Nav_Files = null;
                    }
                    if (!t.ISOCONFIRM)
                    {
                        listNotCheck.Add(index);
                    }
                });
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (listNotCheck.Count > 0)
                    {
                        throw new Exception("请确认所有安全措施信息，行【" + String.Join(",", listNotCheck) + "】！");
                    }

                    var project = GetEntity<T_WB_PROJECT_INPUT>(t => t.ID == entity.PROJECT_ID, "Nav_User", "Nav_SceneUser");
                    var user2Id = project.USER_ID;
                    var user2Name = project.Nav_User.NAME;
                    sendNotices.Add(NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业记录-审阅", entity.ID, entity.ORG_ID, user2Id, user2Name, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB023_SHOWPRINT"));
                    var user3Id = project.SCENE_USER_ID;
                    var user3Name = project.Nav_SceneUser.NAME;
                    sendNotices.Add(NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业记录-审阅", entity.ID, entity.ORG_ID, user3Id, user3Name, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB023_SHOWPRINT"));
                    if (entity.MOINTER_USER_ID.HasValue && entity.MOINTER_USER_ID.Value != project.USER_ID && entity.MOINTER_USER_ID.Value != project.SCENE_USER_ID)
                    {
                        //待办数据去重
                        var user1Id = entity.MOINTER_USER_ID;
                        var user1Name = GetEntity<T_FM_USER>(user1Id.ToString()).NAME;
                        sendNotices.Add(NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业记录-审阅", entity.ID, entity.ORG_ID, (Guid)user1Id, user1Name, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB023_SHOWPRINT"));
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "WB023_SHOWPRINT");
                    }
                    entity.STATUS_DETAIL = PFStandardStatus.Reading;
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (Nav_RecordDetails != null && Nav_RecordDetails.Any())
                        BantchSaveEntityNoCommit(Nav_RecordDetails);
                    if (sendNotices != null && sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (Files.Any())
                        BantchSaveEntityNoCommit(Files);
                });
                return true;
            });
        }
        /// <summary>
        /// 签到
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("recordSign")]
        public JsonActionResult<bool> recordSign([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var id = Guid.Parse(filter.Parameter1);
                var taskID = Guid.Parse(filter.Parameter2);
                var userID = Guid.Parse(filter.Parameter3);
                var orgId = filter.GetOrgId();
                T_FM_NOTIFICATION_TASK finishTask = null;
                int CountD = 1;

                if (taskID != Guid.Empty)
                {
                    finishTask = NotificationTaskService.FOGetTaskFinishModel(taskID, id);
                    if (finishTask != null)
                    {
                        CountD = GetCount<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID == id && e.ID != taskID && e.NOTICE_STATUS == 0 && e.SOURCE_FORMCODE == finishTask.SOURCE_FORMCODE, null);
                    }
                }
                T_WB_DANGEROUS_JOB modelJob = null;
                if (CountD == 0 && finishTask != null)
                {
                    modelJob = GetEntity<T_WB_DANGEROUS_JOB>(id);
                    if (finishTask.SOURCE_FORMCODE == "WB023_SHOWPRINT")
                    {
                        modelJob.STATUS_DETAIL = PFStandardStatus.Archived;
                    }
                    else if (finishTask.SOURCE_FORMCODE == "WB025_SHOWPRINT")
                    {
                        modelJob.STATUS_MOINTER = PFStandardStatus.Archived;
                    }
                }

                UnifiedCommit(() =>
                {
                    if (finishTask != null)
                        UpdateEntityNoCommit(finishTask);
                    if (modelJob != null)
                        UpdateEntityNoCommit(modelJob);
                });
                return true;
            });
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdateMointer")]
        public JsonActionResult<bool> FullUpdateMointer([FromBody] T_WB_DANGEROUS_JOB entity)
        {
            return SafeExecute(() =>
            {
                T_FM_NOTIFICATION_TASK finishNotice = null;
                List<T_FM_NOTIFICATION_TASK> sendNotices = new List<T_FM_NOTIFICATION_TASK>();
                var Nav_MointerRecordDetails = entity.Nav_MointerRecordDetails;
                List<T_WB_DANGEROUS_JOB_MOINTER_RECORD_DETAIL_FILE> Files = new List<T_WB_DANGEROUS_JOB_MOINTER_RECORD_DETAIL_FILE>();

                entity.Nav_MointerRecordDetails = null;
                Nav_MointerRecordDetails.ForEach(t =>
                {
                    if (t.Nav_Files != null && t.Nav_Files.Count() > 0)
                    {
                        t.Nav_Files.ForEach(nf =>
                        {
                            nf.PARENT_ID = t.ID;
                        });
                        Files.AddRange(t.Nav_Files);
                        t.Nav_Files = null;
                    }
                });
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    var project = GetEntity<T_WB_PROJECT_INPUT>(t => t.ID == entity.PROJECT_ID, "Nav_User", "Nav_SceneUser");
                    var user2Id = project.USER_ID;
                    var user2Name = project.Nav_User.NAME;
                    sendNotices.Add(NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业监查记录-审阅", entity.ID, entity.ORG_ID, user2Id, user2Name, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB025_SHOWPRINT"));
                    var user3Id = project.SCENE_USER_ID;
                    var user3Name = project.Nav_SceneUser.NAME;
                    sendNotices.Add(NotificationTaskService.InsertUserNoticeTaskModel("外包工程危险作业监查记录-审阅", entity.ID, entity.ORG_ID, user3Id, user3Name, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB025_SHOWPRINT"));
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "WB025_SHOWPRINT");
                    }
                    entity.STATUS_MOINTER = PFStandardStatus.Reading;
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (Nav_MointerRecordDetails != null && Nav_MointerRecordDetails.Any())
                        BantchSaveEntityNoCommit(Nav_MointerRecordDetails);
                    if (sendNotices != null && sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (Files.Any())
                        BantchSaveEntityNoCommit(Files);
                });
                return true;
            });
        }


        /// <summary>
        /// 检查制表申请 审批流回调
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("UserAgreeNew")]
        public JsonActionResult<bool> UserAgreeNew([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBackNew("WB/WBDangerousJob/UserAgreeNew", entity);
            });
        }
    }
}
