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.CM;
using log4net.Filter;
using Autofac.Features.Metadata;
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    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 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
    }
}