using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.Infrastructure.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using APT.Infrastructure.Api;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Enums;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Domain.Entities.FM;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.HM;
using APT.BaseData.Domain.Enums.PF;
using APT.MS.Domain.Entities.PF;
using APT.MS.Domain.Entities.SC;
using APT.MS.Domain.Entities.TI;
using APT.MS.Domain.Entities.AE;
using APT.MS.Domain.Entities.OH;
using APT.MS.Domain.Entities.CM;
using log4net.Filter;
using Autofac.Features.Metadata;
using APT.MS.Domain.Entities.DM;
namespace APT.BaseData.Services.DomainServices
{
    /// 
    /// 会议 
    /// 
    public class PFApproveCallBackMTService : CommonService, IPFApproveCallBackMTService
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFSysLogService SysLogService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        IFMUserService UserService { get; set; }
        public PFApproveCallBackMTService(IRepository repository, IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IPFSysLogService sysLogService, IFMDepartmentService departmentService, IFMUserService userService)
            : base(repository)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            SysLogService = sysLogService;
            DepartmentService = departmentService;
            UserService = userService;
        }
        #region      会议模块审批回调
        /// 
        /// 会议发布审批回调
        /// 
        /// 
        /// 
        public bool MeetingNoticeBack(string id)
        {
            //状态修改  给 所有参会人 发送(参加、请假)待办
            Guid MeetingId = new Guid(id);
            T_SC_MT_MEETING entity = GetEntity(MeetingId, new string[] { "Nav_ListPAll.Nav_User", "Nav_ListPReView.Nav_User", "Nav_UserRecorder", "Nav_UserHost" });// 参会人 评审人 记录人  主持人
            entity.STATUS = PFStandardStatus.Archived;//变成已归档
            //如果是年度生产作业计划触发的,审批结束后发今日提醒给企管部负责人
            T_FM_NOTIFICATION_TASK sendNotice = null;
            if (entity.CREACTTYPE == CREACTTYPEEnum.YearPlanAdd)
            {
                var userInfo = this.GetEntity(t => t.NAME == "企管部负责人", "Nav_User");
                if (userInfo != null)
                {
                    sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("请上传下年度生产作业计划至文件库。", entity.ID, entity.ORG_ID, userInfo.USER_ID.Value, userInfo.Nav_User.NAME, DateTime.Now, DateTime.Now.AddDays(30), (int)FMNoticeTypeEnum.今日提醒, "PF135");
                }
            }
            //  XXXX 会  参会通知  
            string perNoticeTitle = entity.MEETINGTYPE.GetDescription() + "参会通知";
            List ListNoticeAll = new List();
            List ListNoticeAllNAME = new List();
            var listUser = entity.Nav_ListPAll.Where(e => !e.IS_DELETED).Select(e => e.Nav_User).ToList();
            for (int i = 0; i < listUser.Count; i++)
            {
                if (ListNoticeAll.Contains(listUser[i].ID))
                {
                    continue;
                }
                ListNoticeAll.Add(listUser[i].ID);
                ListNoticeAllNAME.Add(listUser[i].NAME);
            }
            //主持人
            if (!ListNoticeAll.Contains(entity.USER_ID_HOST.Value))
            {
                ListNoticeAll.Add(entity.USER_ID_HOST.Value);
                ListNoticeAllNAME.Add(entity.Nav_UserHost.NAME);
            }
            //记录人
            if (!ListNoticeAll.Contains(entity.USER_ID_RECORDER.Value))
            {
                ListNoticeAll.Add(entity.USER_ID_RECORDER.Value);
                ListNoticeAllNAME.Add(entity.Nav_UserRecorder.NAME);
            }
            //评审人
            if (entity.Nav_ListPReView != null && entity.Nav_ListPReView.Any())
            {
                var ReView = entity.Nav_ListPReView.ToList();
                for (int i = 0; i < ReView.Count; i++)
                {
                    if (ListNoticeAll.Contains(ReView[i].USER_ID))
                    {
                        continue;
                    }
                    ListNoticeAll.Add(ReView[i].USER_ID);
                    ListNoticeAllNAME.Add(ReView[i].Nav_User.NAME);
                }
            }
            //给责任人 发送通知
            List listNoticeDeals = NotificationTaskService.InsertUserNoticeTaskModels(perNoticeTitle, entity.ID, entity.ORG_ID, ListNoticeAll, ListNoticeAllNAME, DateTime.Now, entity.BEGIN_TIME.Value, (int)FMNoticeTypeEnum.消息, "SC028_SHOWPRINT");
            //如果会议已经开始了 待办变成已完成
            if (entity.BEGIN_TIME.Value < DateTime.Now)
                foreach (var item in listNoticeDeals)
                {
                    item.NOTICE_STATUS = 1;
                }
            this.UnifiedCommit(() =>
            {
                if (entity != null)
                    UpdateEntityNoCommit(entity);
                if (listNoticeDeals != null && listNoticeDeals.Any())//隐患上报明细表
                    BantchSaveEntityNoCommit(listNoticeDeals);
                if (sendNotice != null)
                    UpdateEntityNoCommit(sendNotice);
            });
            return true;
        }
        /// 
        /// 会议纪要审批回调
        /// 
        /// 
        /// 
        public bool MeetingMinutesBack(string id)
        {
            //状态修改
            Guid MeetingMinutesId = new Guid(id);
            T_SC_MT_MEETING_MINUTES entity = GetEntity(MeetingMinutesId);
            entity.STATUS = PFStandardStatus.Archived;//变成已归档
            T_SC_MT_MEETING_END modelEnd = new T_SC_MT_MEETING_END();
            modelEnd.ID = Guid.NewGuid();
            modelEnd.ORG_ID = entity.ORG_ID;
            modelEnd.MEETING_ID = entity.MEETING_ID;
            modelEnd.ISEND = false;
            modelEnd.RUN_COUNT = 0;
            modelEnd.CREATE_TIME = DateTime.Now;
            //会议结束的逻辑请转至  PP/SC/MeetingEndToOther  处理
            this.UnifiedCommit(() =>
            {
                if (entity != null)
                    UpdateEntityNoCommit(entity);
                UpdateEntityNoCommit(modelEnd);//添加结束表 隔离会议模块
            });
            return true;
        }
        #endregion
        #region     安全科技 保险单
        //TI/TISafePdtCostRecordType/RecordBack
        /// 
        /// 安全生产费用使用记录审批
        /// 
        /// 
        /// 
        public bool RecordBack(string id)
        {
            Guid MeetingMinutesId = new Guid(id);
            T_TI_SAFE_PDT_COST_RECORD entity = GetEntity(MeetingMinutesId);
            entity.STATUS = PFStandardStatus.Archived;//变成已归档
            this.UnifiedCommit(() =>
            {
                if (entity != null)
                    UpdateEntityNoCommit(entity);
            });
            return true;
        }
        #endregion
        #region      事故事件上报
        //AE/AEAccidentEventReport/EventBack
        /// 
        /// 事故事件上报审批
        /// 
        /// 
        /// 
        public bool EventBack(string id)
        {
            Guid GUID = new Guid(id);
            T_AE_ACCIDENT_EVENT_REPORT entity = GetEntity(GUID);
            entity.STATUS = PFStandardStatus.Archived;//变成已归档
            //重伤及以上:安环部负责人
            //轻伤:部门级部门负责人
            //微伤:部门级部门负责人
            //险肇:部门级部门负责人
            T_FM_USER user = new T_FM_USER();
            T_PF_APPROVAL_ROLE approveRole = null;
            #region    获取负责人
            switch (entity.ACCIDENT_LEVEL)
            {
                case AEAccidentLevel.Jumbo:
                case AEAccidentLevel.Major:
                case AEAccidentLevel.Larger:
                case AEAccidentLevel.General:
                case AEAccidentLevel.SeriouslyInjured:
                    var ToUser = GetEntity(e => e.EVENTTYPE == EventType.AE006ToAE008);//触发设置
                    if (ToUser == null)
                    {
                        //安环部负责人
                        approveRole = GetEntity(e => e.NAME.Contains("安环部负责人"));
                        if (approveRole != null)
                        {
                            user = GetEntity(e => e.APPROVE_ROLE_ID == approveRole.ID);
                            if (user == null)
                            {
                                SysLogService.AddAddLog(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "AE006", entity.ID.ToString(), "", "未找到安环部负责人【" + approveRole.ID + "】!");
                            }
                        }
                        else
                        {
                            SysLogService.AddAddLog(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "AE006", entity.ID.ToString(), "", "未找到审批角色安环部负责人");
                        }
                    }
                    else
                    {
                        //部门岗位人员
                        string Msg = string.Empty;
                        var listUser = UserService.GetDepPostUser(ref Msg, ToUser.DEPARTMENT_ID, ToUser.POST_ID, true);
                        if (listUser != null && listUser.Any())
                        {
                            user = listUser[0];
                        }
                        else
                        {
                            SysLogService.AddAddLog(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "AE006", entity.ID.ToString(), "", "未找到配置的部门岗位人员!");
                        }
                    }
                    break;
                case AEAccidentLevel.MinorJuries:
                case AEAccidentLevel.Aminor:
                case AEAccidentLevel.Risk:
                    //部门级部门负责人
                    if (entity.DEPARTMENT_ID.HasValue)
                    {
                        var dep = DepartmentService.GetDEPARTMENTLevel(entity.DEPARTMENT_ID.Value);
                        if (dep != null)
                        {
                            approveRole = GetEntity(e => e.NAME.Contains("部门负责人"));
                            if (approveRole != null)
                            {
                                user = GetEntity(e => e.DEPARTMENT_ID == dep.ID && e.APPROVE_ROLE_ID == approveRole.ID);
                                if (user == null)
                                {
                                    SysLogService.AddAddLog(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "AE006", entity.ID.ToString(), "", "未找到部门【" + entity.DEPARTMENT_ID.Value + "】(审批角色)负责人【" + approveRole.ID + "】!");
                                }
                            }
                            else
                            {
                                SysLogService.AddAddLog(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "AE006", entity.ID.ToString(), "", "未找到审批角色部门负责人");
                            }
                        }
                        else
                        {
                            SysLogService.AddAddLog(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "AE006", entity.ID.ToString(), "", "未找到部门【" + entity.DEPARTMENT_ID.Value + "】的部门级");
                        }
                    }
                    else
                    {
                        SysLogService.AddAddLog(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "AE006", entity.ID.ToString(), "", "部门ID为空");
                    }
                    break;
                default:
                    break;
            }
            #endregion
            T_AE_ACCIDENT_SURVEY_TEAM_MEMBER member = null;
            T_FM_NOTIFICATION_TASK task = null;
            T_SC_MT_MEETING_BEGIN modelBegin = null;
            if (user != null)
            {
                //全部对接  流程修改 为 发起会议 归档后 到 会议开始 
                ////找到了负责人
                //member = new T_AE_ACCIDENT_SURVEY_TEAM_MEMBER();
                //member.ID = Guid.NewGuid();
                //member.REPORT_ID = entity.ID;
                //member.STATUS = PFStandardStatus.Draft;
                //member.IS_DELETED = false;
                //member.ORG_ID = entity.ORG_ID;
                //member.CREATE_TIME = DateTime.Now;
                //member.CREATER_ID = user.ID;
                ////member.LEADER_USER_ID = ;
                ////member.SURVEY_USER_ID = ;
                ////member.ENTITY_ORG_TPYE = ;
                ////member.FORM_ID = ;
                ////member.FLOW_STATUS = ;
                ////member.FLOW_SEND_STATUS = ;
                ////member.FLOW_ID = ;
                ////member.MODIFY_TIME = ;
                //member.MODIFIER_ID = user.ID;
                //task = NotificationTaskService.InsertUserNoticeTaskModel("事故调查小组成员", member.ID, entity.ORG_ID, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.消息, "AE008");
                //勘察记录结束后 触发  调查报告讨论 会议
                modelBegin = new T_SC_MT_MEETING_BEGIN();
                modelBegin.ID = Guid.NewGuid();
                modelBegin.ORG_ID = entity.ORG_ID;
                modelBegin.SOURCETYPE = SOURCETYPE.AE006ToMeet;//事故事件上报[AE006] 对接到 会议开始
                modelBegin.TABLENAME = "T_AE_ACCIDENT_EVENT_REPORT";
                modelBegin.DATA_ID = entity.ID;
                modelBegin.ISBEGIN = false;
                modelBegin.USER_ID = user.ID;
                modelBegin.CREATE_TIME = DateTime.Now;
                modelBegin.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            }
            this.UnifiedCommit(() =>
            {
                if (entity != null)
                    UpdateEntityNoCommit(entity);
                if (modelBegin != null)
                    UpdateEntityNoCommit(modelBegin);
                if (task != null)
                    AddEntityNoCommit(task);
                if (member != null)
                    AddEntityNoCommit(member);
            });
            return true;
        }
        //AE/AEInvestigationRecord/LeaderCheck
        /// 
        /// 勘察记录组长审批完成后回调
        /// 
        /// 
        /// 
        public bool LeaderCheck(string id)
        {
            Guid GUID = new Guid(id);
            T_AE_INVESTIGATION_RECORD entity = GetEntity(GUID);
            entity.STATUS = PFStandardStatus.Archived;//变成已归档
            var appDet = GetEntity(e => e.APPROVE_ID == entity.APPROVE_ID);
            entity.REVIEW_OK = appDet.NODE_APPROVE_STATUS == 10 ? true : false;// 组长审阅状态
            entity.REVIEW_COMMENT = appDet.CONTEXT;// 审阅意见
            //事故调查小组成员表 填写 给记录人 触发勘察记录表  审批通过后 再给记录人 发送 事故事件调查结果报送表
            T_AE_ACCIDENT_SURVEY_TEAM_MEMBER member = GetEntity(e => e.REPORT_ID == entity.ACCIDENT_ID, new string[] { "Nav_SurveyUser" });
            //勘察记录结束后 触发  调查报告讨论 会议
            T_SC_MT_MEETING_BEGIN modelBegin = new T_SC_MT_MEETING_BEGIN();
            modelBegin.ID = Guid.NewGuid();
            modelBegin.ORG_ID = entity.ORG_ID;
            modelBegin.SOURCETYPE = SOURCETYPE.AE018ToMeet;
            modelBegin.TABLENAME = "T_AE_INVESTIGATION_RECORD";
            modelBegin.DATA_ID = GUID;
            modelBegin.ISBEGIN = false;
            modelBegin.USER_ID = member.SURVEY_USER_ID.Value;
            modelBegin.CREATE_TIME = DateTime.Now;
            modelBegin.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            //#region    这段代码应该是得移走 到会议结束后触发
            //T_AE_ACCIDENT_EVENT_SURVEY_RESULT modelResult = new T_AE_ACCIDENT_EVENT_SURVEY_RESULT();
            //modelResult.ID = Guid.NewGuid();
            //modelResult.REPORT_ID = entity.ACCIDENT_ID;
            //modelResult.STATUS = PFStandardStatus.Draft;
            //modelResult.IS_DELETED = false;
            //modelResult.ORG_ID = entity.ORG_ID;
            ////modelResult.CASUALTY_COUNT = "";
            ////modelResult.ECONOMIC_LOSSES = "";
            ////modelResult.ACCIDENT_COURSE = "";
            ////modelResult.TIME = "";
            ////modelResult.RISK_SUBMIT_ID = "";
            ////modelResult.ENTITY_ORG_TPYE = "";
            ////modelResult.FORM_ID = "";
            ////modelResult.FLOW_STATUS = "";
            ////modelResult.FLOW_SEND_STATUS = "";
            ////modelResult.FLOW_ID = "";
            ////modelResult.CREATE_TIME = "";
            ////modelResult.MODIFY_TIME = "";
            ////modelResult.CREATER_ID = "";
            ////modelResult.MODIFIER_ID = ""; 
            //T_FM_NOTIFICATION_TASK taskAdd = NotificationTaskService.InsertUserNoticeTaskModel("事故事件调查结果填报", modelResult.ID, entity.ORG_ID, member.SURVEY_USER_ID.Value, member.Nav_SurveyUser.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.消息, "AE010");
            //#endregion
            this.UnifiedCommit(() =>
            {
                if (entity != null)
                    UpdateEntityNoCommit(entity);
                UpdateEntityNoCommit(modelBegin);//会议开始
                //if (modelResult != null)//添加 事故事件调查结果填报
                //    AddEntityNoCommit(modelResult);
                //if (taskAdd != null)//添加 事故事件调查结果填报 待办
                //    AddEntityNoCommit(taskAdd);
            });
            return true;
        }
        /// 
        /// 事故事件调查结果审批
        /// 
        /// 
        /// 
        public bool EventResultBack(string id)
        {
            Guid GUID = new Guid(id);
            T_AE_ACCIDENT_EVENT_SURVEY_RESULT entity = GetEntity(GUID);
            entity.STATUS = PFStandardStatus.Archived;//变成已归档
            ////重伤及以上:安环部负责人
            ////轻伤:部门级部门负责人
            ////微伤:部门级部门负责人
            ////险肇:部门级部门负责人
            //T_FM_USER user = new T_FM_USER();
            //T_PF_APPROVAL_ROLE approveRole = null;
            //#region    获取负责人
            //switch (entity.ACCIDENT_LEVEL)
            //{
            //    case AEAccidentLevel.Jumbo:
            //    case AEAccidentLevel.Major:
            //    case AEAccidentLevel.Larger:
            //    case AEAccidentLevel.General:
            //    case AEAccidentLevel.SeriouslyInjured:
            //        //安环部负责人
            //        approveRole = GetEntity(e => e.NAME.Contains("安环部负责人"));
            //        if (approveRole != null)
            //        {
            //            user = GetEntity(e => e.APPROVE_ROLE_ID == approveRole.ID);
            //            if (user == null)
            //            {
            //                SysLogService.AddAddLog(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "AE006", entity.ID.ToString(), "", "未找到安环部负责人【" + approveRole.ID + "】!");
            //            }
            //        }
            //        else
            //        {
            //            SysLogService.AddAddLog(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "AE006", entity.ID.ToString(), "", "未找到审批角色安环部负责人");
            //        }
            //        break;
            //    case AEAccidentLevel.MinorJuries:
            //    case AEAccidentLevel.Aminor:
            //    case AEAccidentLevel.Risk:
            //        //部门级部门负责人
            //        if (entity.DEPARTMENT_ID.HasValue)
            //        {
            //            var dep = DepartmentService.GetDEPARTMENTLevel(entity.DEPARTMENT_ID.Value);
            //            if (dep != null)
            //            {
            //                approveRole = GetEntity(e => e.NAME.Contains("部门负责人"));
            //                if (approveRole != null)
            //                {
            //                    user = GetEntity(e => e.DEPARTMENT_ID == dep.ID && e.APPROVE_ROLE_ID == approveRole.ID);
            //                    if (user == null)
            //                    {
            //                        SysLogService.AddAddLog(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "AE006", entity.ID.ToString(), "", "未找到部门【" + entity.DEPARTMENT_ID.Value + "】(审批角色)负责人【" + approveRole.ID + "】!");
            //                    }
            //                }
            //                else
            //                {
            //                    SysLogService.AddAddLog(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "AE006", entity.ID.ToString(), "", "未找到审批角色部门负责人");
            //                }
            //            }
            //            else
            //            {
            //                SysLogService.AddAddLog(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "AE006", entity.ID.ToString(), "", "未找到部门【" + entity.DEPARTMENT_ID.Value + "】的部门级");
            //            }
            //        }
            //        else
            //        {
            //            SysLogService.AddAddLog(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "AE006", entity.ID.ToString(), "", "部门ID为空");
            //        }
            //        break;
            //    default:
            //        break;
            //}
            //#endregion
            //T_AE_ACCIDENT_SURVEY_TEAM_MEMBER member = null;
            //T_FM_NOTIFICATION_TASK task = null;
            //if (user != null)
            //{
            //    //找到了负责人
            //    member = new T_AE_ACCIDENT_SURVEY_TEAM_MEMBER();
            //    member.ID = Guid.NewGuid();
            //    member.REPORT_ID = entity.ID;
            //    member.STATUS = PFStandardStatus.Draft;
            //    member.IS_DELETED = false;
            //    member.ORG_ID = entity.ORG_ID;
            //    member.CREATE_TIME = DateTime.Now;
            //    member.CREATER_ID = user.ID;
            //    //member.LEADER_USER_ID = ;
            //    //member.SURVEY_USER_ID = ;
            //    //member.ENTITY_ORG_TPYE = ;
            //    //member.FORM_ID = ;
            //    //member.FLOW_STATUS = ;
            //    //member.FLOW_SEND_STATUS = ;
            //    //member.FLOW_ID = ;
            //    //member.MODIFY_TIME = ;
            //    member.MODIFIER_ID = user.ID;
            //    task = NotificationTaskService.InsertUserNoticeTaskModel("事故调查小组成员", member.ID, entity.ORG_ID, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.消息, "AE008");
            //}
            #region    给人事专员触发工伤保险理赔信息记录   
            //TI021   发起部门 姓名 事故事件 受伤日期   发起部门:受伤人 所在部门
            List listClaim = null;
            List listTask = null;
            if (entity.REPORT_ID.HasValue)
            {
                var listUsers = GetEntities(e => e.RESULT_ID == entity.ID && !e.IS_DELETED, "Nav_User");
                if (listUsers != null && listUsers.Any())
                {
                    var doSet = GetEntity(e => e.EVENTTYPE == EventType.ClaimRecord && !e.IS_DELETED);
                    if (doSet != null)
                    {
                        //给对应部门人员 发送待办
                        var user = GetEntity(e => e.DEPARTMENT_ID.HasValue && e.ENABLE_STATUS == 0 && !e.IS_DELETED && e.DEPARTMENT_ID.Value == doSet.DEPARTMENT_ID && e.PERSON_ID.HasValue && e.Nav_Person.POST_ID.HasValue && e.Nav_Person.POST_ID.Value == doSet.POST_ID, "Nav_Person");
                        if (user != null)
                        {
                            listClaim = new List();
                            listTask = new List();
                            foreach (var item in listUsers)
                            {
                                T_TI_INSURANCE_CLAIM_RECORD claim = new T_TI_INSURANCE_CLAIM_RECORD();
                                claim.ID = Guid.NewGuid();
                                claim.ORG_ID = doSet.ORG_ID;
                                claim.ACCIDENT_ID = entity.REPORT_ID;
                                claim.DEPARTMENT_ID = item.Nav_User.DEPARTMENT_ID;
                                claim.INJURE_TIME = item.INJURED_TIME;
                                claim.USER_ID = item.USER_ID;
                                claim.STATUS = PFStandardStatus.Draft;
                                listTask.Add(NotificationTaskService.InsertUserNoticeTaskModel("工伤保险理赔 事故事件:" + item.Nav_User.NAME, claim.ID, claim.ORG_ID, user.ID, user.NAME, DateTime.Now, 0, "TI021", FMTASKTYPE.Default));
                                listClaim.Add(claim);
                            }
                        }
                    }
                }
            }
            #endregion
            this.UnifiedCommit(() =>
            {
                if (entity != null)
                    UpdateEntityNoCommit(entity);
                //if (task != null)
                //    AddEntityNoCommit(task);
                //if (member != null)
                //    AddEntityNoCommit(member);
                if (listClaim != null && listClaim.Count > 0)
                    BantchSaveEntityNoCommit(listClaim);
                if (listTask != null && listTask.Count > 0)
                    BantchSaveEntityNoCommit(listTask);
            });
            return true;
        }
        #endregion
        #region      职业卫生
        /// 
        /// 职业卫生 体检计划 人事部经理审批
        /// 
        /// 
        /// 
        public bool PlanMasterBack(string id)
        {
            Guid GUID = new Guid(id);
            string Msg = string.Empty;
            var member = UserService.GetPostUser(ref Msg, "人事专员");
            if (member == null)
            {
                if (!string.IsNullOrEmpty(Msg))
                {
                    throw new Exception(Msg);
                }
                else
                {
                    throw new Exception("获取人事专员岗位信息失败!");
                }
            }
            T_OH_HEALTH_EXAM_PLAN entity = GetEntity(GUID, new string[] { "Nav_ListPlanRegister.Nav_ListHazard" });
            entity.STATUS = PFStandardStatus.Archived;//变成已归档
            DateTime dtNow = DateTime.Now;
            //给人事专员发送 体检填表
            T_OH_HEALTH_EXAM_NOTICE notice = new T_OH_HEALTH_EXAM_NOTICE();
            notice.ID = Guid.NewGuid();
            notice.CODE = "TJ" + dtNow.ToString("yyyyMMddHHmmss");
            //notice.NAME ="";
            //notice.OTHER_STUFF =;
            notice.STATUS = PFStandardStatus.Draft;
            //notice.APPROVE_ID =;
            notice.IS_DELETED = false;
            notice.ORG_ID = entity.ORG_ID;
            //notice.ENTITY_ORG_TPYE =;
            //notice.FORM_ID =;
            //notice.FLOW_STATUS =;
            //notice.FLOW_SEND_STATUS =;
            //notice.FLOW_ID =;
            //notice.CREATE_TIME =;
            //notice.MODIFY_TIME =;
            //notice.CREATER_ID =;
            //notice.MODIFIER_ID =;
            List listRegister = new List();
            IEnumerable listRegisterCheck = null;
            T_OH_HEALTH_EXAM_NOTICE_REGISTER modelLast = null;
            List listOccHazard = new List();
            Guid LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
            BaseFilter basFiliter = new BaseFilter();
            basFiliter.Order = DbOrder.DESC;
            basFiliter.Orders.Add(new DataOrder() { Field = "THISDATE", Order = DbOrder.DESC });
            foreach (var item in entity.Nav_ListPlanRegister)
            {
                T_OH_HEALTH_EXAM_NOTICE_REGISTER model = new T_OH_HEALTH_EXAM_NOTICE_REGISTER();
                model.ID = Guid.NewGuid();
                model.NOTICE_ID = notice.ID;
                model.USER_ID = item.USER_ID;
                model.DEPARTMENT_ID = item.DEPARTMENT_ID;
                model.DEPARTMENT_ID_WORKSHOP = item.DEPARTMENT_ID_WORKSHOP;
                model.CYCLE_ID = item.EXAM_CYCLE_ID;
                //model.EXAM_BATCH_ID
                model.TYPE = OHHealthExamType.Post;
                model.STATUS = OHHealthExamNoticeRegisterStatus.WaitNotice;
                model.IS_DELETED = false;
                model.ORG_ID = item.ORG_ID;
                //model.ENTITY_ORG_TPYE
                //model.FORM_ID
                //model.FLOW_STATUS
                //model.FLOW_SEND_STATUS
                //model.FLOW_ID
                model.LASTDATE = dtNow;//上次体检时间
                //新方法
                modelLast = GetEntity(e => !e.IS_DELETED && e.USER_ID == model.USER_ID && e.STATUS >= OHHealthExamNoticeRegisterStatus.NoticeResult, basFiliter, "");
                //modelLast = GetEntity(e => !e.IS_DELETED && e.USER_ID == model.USER_ID && e.STATUS >= OHHealthExamNoticeRegisterStatus.MasterRead, basFiliter, "");
                if (modelLast != null && modelLast.THISDATE.HasValue)
                {
                    model.LASTDATE = modelLast.THISDATE;//上次体检时间 就是上次通知的本次时间
                }
                //旧方法
                //listRegisterCheck = GetEntities(e => !e.IS_DELETED && e.USER_ID == model.USER_ID && e.STATUS >= OHHealthExamNoticeRegisterStatus.NoticeResult).OrderByDescending(e => e.THISDATE);
                //if (listRegisterCheck != null && listRegisterCheck.Any())
                //{
                //    modelLast = listRegisterCheck.ToList()[0];
                //    if (modelLast.EXAM_BATCH_ID.HasValue)
                //    {
                //        model.LASTDATE = modelLast.THISDATE;//上次体检时间 就是上次通知的本次时间
                //        //if (!listBatchID.Contains(modelLast.EXAM_BATCH_ID.Value))
                //        //{
                //        //    listBatchID.Add(modelLast.EXAM_BATCH_ID.Value);
                //        //    modelBatch = GetEntity(modelLast.EXAM_BATCH_ID.Value);
                //        //    listLastBatch.Add(modelBatch);
                //        //}
                //        //else
                //        //{
                //        //    modelBatch = listLastBatch.First(e => e.ID == modelLast.EXAM_BATCH_ID.Value);
                //        //}
                //        //model.LASTDATE = modelBatch.START_TIME;//上次体检时间
                //    }
                //}
                model.CREATE_TIME = dtNow;
                model.MODIFY_TIME = dtNow;
                model.CREATER_ID = LoginID;
                //model.MODIFIER_ID
                model.PLAN_ID_DEP = item.PLAN_ID_DEP;
                model.PLAN_REGISTER_ID = item.ID;
                listRegister.Add(model);
                foreach (var itemHaz in item.Nav_ListHazard)
                {
                    listOccHazard.Add(new T_OH_EXAM_NOTICE_OCC_HAZARD()
                    {
                        ID = Guid.NewGuid(),
                        REGISTER_ID = model.ID,
                        HAZARD_ID = itemHaz.HAZARD_ID,
                        ORG_ID = notice.ORG_ID,
                        CREATE_TIME = dtNow,
                        MODIFY_TIME = dtNow
                    });
                }
            }
            //人事专员 发送 体检通知 安排
            T_FM_NOTIFICATION_TASK taskAdd = NotificationTaskService.InsertUserNoticeTaskModel("体检通知表", notice.ID, entity.ORG_ID, member.ID, member.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.消息, "OH010");
            this.UnifiedCommit(() =>
            {
                if (entity != null)
                    UpdateEntityNoCommit(entity);
                if (notice != null)//体检通知
                    AddEntityNoCommit(notice);
                if (listRegister != null && listRegister.Count > 0)//人员
                    BantchAddEntityNoCommit(listRegister);
                if (taskAdd != null)//添加 事故事件调查结果填报 待办
                    AddEntityNoCommit(taskAdd);
                if (listOccHazard != null && listOccHazard.Count > 0)//人员
                    BantchAddEntityNoCommit(listOccHazard);
            });
            return true;
        }
        #endregion
        #region    CM
        public bool EstimateBack(string id)
        {
            //流程完毕,触发给一条今日提醒给安环部负责人,消息类型:召开会议,消息内容:请召开应急预案审核会
            //培训水平选中“不充分”,触发给一条今日提醒给事故 / 事件单位负责人,消息类型:组织培训,消息内容:请组织应急知识和技能培训
            Guid GUID = new Guid(id);
            var entity = GetEntity(GUID);
            entity.STATUS = PFStandardStatus.Archived;
            T_FM_NOTIFICATION_TASK modelSafeMeeting = null;//今日提醒给安环部负责人
            string Msg = string.Empty;
            var userSafeMaster = UserService.GetRoleUser(ref Msg, "安环部负责人", null, null);
            if (userSafeMaster != null)
            {
                modelSafeMeeting = NotificationTaskService.InsertUserNoticeTaskModel("请召开应急预案审核会", Guid.Empty, entity.ORG_ID, userSafeMaster.ID, userSafeMaster.NAME, DateTime.Now, DateTime.Now.AddDays(1), 2, null);
            }
            T_FM_NOTIFICATION_TASK modelNotEnougth = null;//培训水平选中“不充分”
            if (entity.RSP_TRAINING_LEVEL.HasValue && entity.RSP_TRAINING_LEVEL.Value == CMRspTrainingLevel.NotEnough && entity.DEPARTMENT_ID_REPORT.HasValue)
            {
                var dep = GetEntity(entity.DEPARTMENT_ID_REPORT.Value, "Nav_User");
                if (dep != null && dep.USER_ID.HasValue)
                {
                    modelNotEnougth = NotificationTaskService.InsertUserNoticeTaskModel("请组织应急知识和技能培训", Guid.Empty, entity.ORG_ID, dep.USER_ID.Value, dep.Nav_User.NAME, DateTime.Now, DateTime.Now.AddDays(1), 2, null);
                }
            }
            this.UnifiedCommit(() =>
            {
                if (entity != null)//状态修改
                    UpdateEntityNoCommit(entity);
                if (modelSafeMeeting != null)//今日提醒给安环部负责人
                    UpdateEntityNoCommit(modelSafeMeeting);
                if (modelNotEnougth != null)//不充分
                    UpdateEntityNoCommit(modelNotEnougth);
            });
            return true;
        }
        /// 
        /// 年度应急演练计划表 审批流回调
        /// 
        /// 
        ///  
        public bool DrillPlanEnd(string id)
        {
            //“演练方案触发时间”触发一条今日提醒给责任人,消息类型:召开会议,消息内容:请编制应急演练方案并召开应急演练方案讨论会
            Guid GUID = new Guid(id);
            var entity = GetEntity(GUID);
            entity.STATUS = PFStandardStatus.Archived;
            this.UnifiedCommit(() =>
            {
                if (entity != null)
                    UpdateEntityNoCommit(entity);
            });
            return true;
        }
        /// 
        /// 设备设施维保
        /// 
        /// 
        /// 
        public bool Audit(string id)
        {
            Guid GUID = new Guid(id);
            var entity = GetEntity(GUID);
            entity.STATUS_APPROVE = PFStandardStatus.Archived;
            this.UnifiedCommit(() =>
            {
                if (entity != null)
                    UpdateEntityNoCommit(entity);
            });
            return true;
        }
        /// 
        /// 应急演练活动记录表
        /// 
        /// 
        ///  
        public bool DrillRecordEnd(string id)
        {
            //“应急演练活动记录表“审核完成后触发两个待办事项:事项一:演练效果评估表、事项二:演练人员自我评估调查表(在问卷调查模块、后续开发),给第一个评估人员
            //待办事项”演练效果评估表“在工作台中任务名称中添加”待调查结束后填写“
            //给第一个评估人员 添加 [演练效果评估表]
            Guid GUID = new Guid(id);
            var entity = GetEntity(GUID, "Nav_ListUserEstimate");
            entity.STATUS = PFStandardStatus.Archived;
            T_FM_USER userRec = null;
            List listEstimateRecord = null;
            if (entity.Nav_ListUserEstimate != null && entity.Nav_ListUserEstimate.Any())
            {
                var userSign = entity.Nav_ListUserEstimate.FirstOrDefault(e => e.ISSIGN);
                if (userSign != null)
                    userRec = GetEntity(userSign.USER_ID);
            }
            T_FM_NOTIFICATION_TASK task = null;//演练效果评估表待办	
            T_CM_DRILL_ESTIMATE modelEstimate = null;
            if (userRec != null)
            {
                modelEstimate = new T_CM_DRILL_ESTIMATE();
                modelEstimate.ID = Guid.NewGuid();
                modelEstimate.CODE = "YLPG" + DateTime.Now.ToString("yyyyMMddHHmmss");
                modelEstimate.RECORD_ID = entity.ID;
                //modelEstimate.ADVISE = ;
                modelEstimate.STATUS = PFStandardStatus.Draft;
                modelEstimate.IS_DELETED = false;
                modelEstimate.ORG_ID = entity.ORG_ID;
                //modelEstimate.ENTITY_ORG_TPYE = ;
                //modelEstimate.FORM_ID = ;
                //modelEstimate.FLOW_STATUS = ;
                //modelEstimate.FLOW_SEND_STATUS = ;
                //modelEstimate.FLOW_ID = ;
                modelEstimate.CREATE_TIME = DateTime.Now;
                modelEstimate.MODIFY_TIME = DateTime.Now;
                modelEstimate.CREATER_ID = userRec.ID;
                modelEstimate.MODIFIER_ID = userRec.ID;
                listEstimateRecord = new List();
                var listEstimateItem = GetEntities(null);
                foreach (var item in listEstimateItem)
                {
                    listEstimateRecord.Add(new T_CM_DRILL_ESTIMATE_RECORD()
                    {
                        ID = Guid.NewGuid(),
                        ESTIMEATE_ID = modelEstimate.ID,
                        ITEM_ID = item.ID,
                        //SCORE = ,
                        //ADVISE = ,
                        IS_DELETED = false,
                        ORG_ID = item.ORG_ID,
                        //ENTITY_ORG_TPYE = ,
                        //FORM_ID = ,
                        //FLOW_STATUS = ,
                        //FLOW_SEND_STATUS = ,
                        //FLOW_ID = ,
                        CREATE_TIME = modelEstimate.CREATE_TIME,
                        MODIFY_TIME = modelEstimate.CREATE_TIME,
                        CREATER_ID = userRec.ID,
                        MODIFIER_ID = userRec.ID,
                    });
                }
                task = NotificationTaskService.InsertUserNoticeTaskModel("演练效果评估", modelEstimate.ID, modelEstimate.ORG_ID, userRec.ID, userRec.NAME, DateTime.Now, DateTime.Now.AddDays(1), 1, "CM036");
            }
            this.UnifiedCommit(() =>
            {
                if (entity != null)
                    UpdateEntityNoCommit(entity);
                if (task != null)//演练效果评估表待办		
                    UpdateEntityNoCommit(task);
                if (modelEstimate != null)//演练效果评估表待办		
                    UpdateEntityNoCommit(modelEstimate);
                if (listEstimateRecord != null && listEstimateRecord.Any())
                    BantchAddEntityNoCommit(listEstimateRecord);
            });
            return true;
        }
        #endregion
    }
}