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.AE;
using APT.MS.Domain.Entities.SC;
using APT.MS.Domain.Entities.TI;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.SC.WebApi.Controllers.Api.AE
{
    [Route("api/AE/AEAccidentSurveyTeamMember")]
    public class AEAccidentSurveyTeamMemberController : AuthorizeApiController<T_AE_ACCIDENT_SURVEY_TEAM_MEMBER>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        //ISCMTMeetingService SCMTMeetingService { get; set; }  SCMTMeetingService = scMTMeetingService;, ISCMTMeetingService scMTMeetingService
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMNotificationTaskService NotificActionTaskService { get; set; }
        public AEAccidentSurveyTeamMemberController(IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IFMNotificationTaskService notificActionTaskService)
        {
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            NotificActionTaskService = notificActionTaskService;

        }

        /// <summary>
        /// 事故调查小组成员 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_AE_ACCIDENT_SURVEY_TEAM_MEMBER entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity.STATUS != PFStandardStatus.Draft && entity.STATUS != PFStandardStatus.Archived)
                {
                    throw new Exception("获取操作方式有误！");
                }
                if (entity.TaskID == Guid.Empty)
                {
                    var loginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    if (entity.CREATER_ID.Value != loginID.Value)
                    {
                        throw new Exception("此事故调查小组成信息不是您添加的，操作失败！");
                    }
                }

                var DeputyLeaderUser = entity.Nav_DeputyLeaderUser;
                entity.Nav_DeputyLeaderUser = null;
                if (DeputyLeaderUser != null && DeputyLeaderUser.Any())
                {
                    foreach (var item in DeputyLeaderUser)
                    {
                        item.Nav_User = null;
                    }
                }
                var TeamMembers = entity.Nav_TeamMembers;
                entity.Nav_TeamMembers = null;
                if (TeamMembers != null && TeamMembers.Any())
                {
                    foreach (var item in TeamMembers)
                    {
                        item.Nav_User = null;
                    }
                }
                if (entity.STATUS == PFStandardStatus.Draft)
                {
                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //事故调查小组成员
                        if (DeputyLeaderUser != null && DeputyLeaderUser.Any())
                            BantchSaveEntityNoCommit(DeputyLeaderUser);
                        if (TeamMembers != null && TeamMembers.Any())
                            BantchSaveEntityNoCommit(TeamMembers);
                    });
                }
                else
                {
                    if (entity.LEADER_USER_ID == null)
                    {
                        throw new Exception("请选择调查小组组长！");
                    }
                    if (DeputyLeaderUser == null || !DeputyLeaderUser.Any())
                    {
                        throw new Exception("请选择调查小组副组长！");
                    }
                    if (TeamMembers == null || !TeamMembers.Any())
                    {
                        throw new Exception("请选择调查小组组员！");
                    }
                    if (entity.SURVEY_USER_ID == null)
                    {
                        throw new Exception("请选择调查记录人！");
                    }

                    //需要处理别的逻辑
                    //结束待办
                    T_FM_NOTIFICATION_TASK task = null;
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificActionTaskService.GetEntityTask(entity.TaskID, "AE008_SHOWPRINT");
                    }

                    //提交后触发事故事件调查结果填报表给调查记录人，工作台截止时间为限制结案时间
                    //提交后触发今日提醒给调查记录人：消息内容：请在OA申请事故调查报告文件发布并上传至事故事件调查结果报送，消息类型：文件上传

                    DateTime dtEnd = DateTime.Now;
                    #region   获取 限制结案时间  dtEnd

                    AEAccidentLevel level = GetEntity<T_AE_ACCIDENT_EVENT_REPORT>(entity.REPORT_ID.Value).ACCIDENT_LEVEL.Value;
                    var days = GetEntity<T_AE_ACCIDENT_LEVEL_DAYS>(e => e.ACCIDENT_LEVEL == level);
                    if (days == null)
                    {
                        switch (level)
                        {
                            case AEAccidentLevel.Jumbo:
                            case AEAccidentLevel.Major:
                            case AEAccidentLevel.Larger:
                            case AEAccidentLevel.General:
                                dtEnd = DateTime.Now.Date.AddDays(32).AddSeconds(-1);
                                break;
                            case AEAccidentLevel.SeriouslyInjured:
                                dtEnd = DateTime.Now.Date.AddDays(17).AddSeconds(-1);
                                break;
                            case AEAccidentLevel.MinorJuries:
                            case AEAccidentLevel.Aminor:
                            case AEAccidentLevel.Risk:
                                dtEnd = DateTime.Now.Date.AddDays(12).AddSeconds(-1);
                                break;
                            default:
                                break;
                        }
                    }
                    else
                    {
                        dtEnd = DateTime.Now.Date.AddDays(2 + days.DAYS).AddSeconds(-1);
                    }
                    #endregion


                    #region 1、事故事件调查结果填报表   2、给调查记录人

                    //T_AE_ACCIDENT_EVENT_SURVEY_RESULT modelResult = new T_AE_ACCIDENT_EVENT_SURVEY_RESULT();
                    //modelResult.ID = Guid.NewGuid();
                    //modelResult.REPORT_ID = entity.REPORT_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 = "";


                    //string SURVEYNAME = string.Empty;
                    //if (entity.Nav_SurveyUser != null && !string.IsNullOrEmpty(entity.Nav_SurveyUser.NAME))
                    //{
                    //    SURVEYNAME = entity.Nav_SurveyUser.NAME;
                    //}
                    //else
                    //{
                    //    SURVEYNAME = GetEntity<T_FM_USER>(entity.SURVEY_USER_ID.Value).NAME;
                    //}

                    //T_FM_NOTIFICATION_TASK taskAdd = NotificActionTaskService.InsertUserNoticeTaskModel("事故事件调查结果填报", modelResult.ID, entity.ORG_ID, entity.SURVEY_USER_ID.Value, SURVEYNAME, DateTime.Now, dtEnd, (int)FMNoticeTypeEnum.消息, "AE010");
                    //事故调查小组成员表 填写 给记录人 触发勘察记录表  审批通过后 再给记录人 发送 事故事件调查结果报送表

                    #endregion


                    #region   流程修改

                    var Survery = GetEntity<T_FM_USER>(e => e.ID == entity.SURVEY_USER_ID);

                    //wyw 流程修改 231016  调查小组后 给组长触发会议 会议纪要归档后 触发  勘察记录表

                    #region 1、勘察记录表  2、给调查记录人

                    //T_AE_INVESTIGATION_RECORD modelResult = new T_AE_INVESTIGATION_RECORD();
                    //modelResult.ID = Guid.NewGuid();
                    ////modelResult.LAUNCH_TIME =;
                    //modelResult.DEPARTMENT_ID = Survery.DEPARTMENT_ID;
                    //modelResult.USER_ID = entity.SURVEY_USER_ID;
                    //modelResult.ACCIDENT_ID = entity.REPORT_ID; ;
                    //modelResult.TEAM_MEMBER_ID = entity.ID;
                    ////modelResult.INVESTIGATION_TIME =;
                    ////modelResult.INVESTIGATION_LOCATION =;
                    ////modelResult.INVESTIGATION_REASON =;
                    ////modelResult.SCENE_ENV_DESC =;
                    ////modelResult.SCENE_DESC =;
                    ////modelResult.SCENE_EVIDENCE_DESC =;
                    //modelResult.STATUS = PFStandardStatus.Draft;
                    ////modelResult.REVIEW_OK =;
                    ////modelResult.REVIEW_COMMENT =;
                    //modelResult.IS_DELETED = false;
                    //modelResult.ORG_ID = entity.ORG_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 =;
                    ////modelResult.LEADER_USER_ID =;
                    ////modelResult.APPROVE_ID =;

                    //T_FM_NOTIFICATION_TASK taskAdd = NotificActionTaskService.InsertUserNoticeTaskModel("勘察记录表", modelResult.ID, entity.ORG_ID, entity.SURVEY_USER_ID.Value, Survery.NAME, DateTime.Now, dtEnd, (int)FMNoticeTypeEnum.消息, "AE018");

                    #endregion


                    //T_SC_MT_MEETING modelMT = new T_SC_MT_MEETING();
                    //modelMT.ID = Guid.NewGuid();
                    //modelMT.CODE = "AE" + DateTime.Now.ToString("yyyyMMddHHmmss");
                    //modelMT.NAME = "事故事件触发会议" + DateTime.Now.ToString("yyMMdd");
                    //modelMT.MEETINGTYPE = SCMEETINGTYPE.Ordinary;
                    //var eventReport = GetEntity<T_AE_ACCIDENT_EVENT_REPORT>(entity.REPORT_ID.Value, "Nav_Department");
                    //modelMT.DEPARTMENT_ID = eventReport.DEPARTMENT_ID.Value;//
                    //modelMT.LEVELVALUE = eventReport.Nav_Department.DEPARTMENT_TYPE;
                    //modelMT.USER_ID_ORIGINATOR = entity.LEADER_USER_ID.Value;//组长
                    //modelMT.BEGIN_TIME = DateTime.Now;
                    //modelMT.STATUS = PFStandardStatus.Draft;
                    //modelMT.PERSCORE = 0;
                    //modelMT.IS_DELETED = false;
                    //modelMT.ORG_ID = entity.ORG_ID;
                    //modelMT.ENTITY_ORG_TPYE = 0;
                    //modelMT.FLOW_STATUS = 0;
                    //modelMT.FLOW_SEND_STATUS = 0;
                    //modelMT.CREATE_TIME = DateTime.Now;
                    //modelMT.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    //modelMT.CREACTTYPE = CREACTTYPEEnum.AEToMTAfterTeamMember;
                    //modelMT.ISBEGIN = false;
                    //modelMT.ISCANCEL = false;
                    ////modelMT.CheckLevel_ENUMS_ID = ;
                    ////modelMT.Nav_MinutesID = ;
                    ////modelMT.ADDRESS = ;
                    ////modelMT.THEME = ;
                    ////modelMT.PLANSET_ID = ;
                    ////modelMT.USER_ID_RECORDER = ;
                    ////modelMT.USER_ID_HOST = ;
                    ////modelMT.RECORD = ;
                    ////modelMT.APPROVE_ID = ;
                    ////modelMT.FORM_ID = ;
                    ////modelMT.FLOW_ID = ;
                    ////modelMT.MODIFY_TIME = ;
                    ////modelMT.MODIFIER_ID = ;
                    ////modelMT.CONTENT = ;

                    //List<T_SC_MT_MEETING_PALL> listAllUser = new List<T_SC_MT_MEETING_PALL>();
                    //foreach (var item in TeamMembers)
                    //{
                    //    if (!item.USER_ID.HasValue || item.IS_DELETED)
                    //    {
                    //        continue;
                    //    }
                    //    T_SC_MT_MEETING_PALL modelUser = new T_SC_MT_MEETING_PALL();
                    //    modelUser.ID = Guid.NewGuid();
                    //    modelUser.MEETING_ID = modelMT.ID;
                    //    modelUser.PERSONTYPE = SCMEETINGPERSONTYPE.ALL;
                    //    modelUser.USER_ID = item.USER_ID.Value;
                    //    modelUser.IS_DELETED = false;
                    //    modelUser.ORG_ID = modelMT.ORG_ID;
                    //    //modelUser.ENTITY_ORG_TPYE = "";
                    //    //modelUser.FORM_ID = "";
                    //    //modelUser.FLOW_STATUS = "";
                    //    //modelUser.FLOW_SEND_STATUS = "";
                    //    //modelUser.FLOW_ID = "";
                    //    //modelUser.CREATE_TIME = "";
                    //    //modelUser.MODIFY_TIME = "";
                    //    //modelUser.CREATER_ID = "";
                    //    //modelUser.MODIFIER_ID = "";
                    //    //modelUser.JOINRESULT = "";
                    //    //modelUser.NOTJOINREASON = "";
                    //    modelUser.PERSONNATURE = PersonNature.JOIN;
                    //    listAllUser.Add(modelUser);
                    //}


                    #endregion


                    #region    今日提醒给调查记录人

                    T_FM_NOTIFICATION_TASK WarmOA = NotificActionTaskService.InsertUserNoticeTaskModel("请于" + dtEnd.ToString("yyyy-MM-dd") + "前，在OA申请事故调查报告文件发布并上传至事故事件调查结果报送表！", entity.ID, entity.ORG_ID, entity.SURVEY_USER_ID.Value, Survery.NAME, DateTime.Now, dtEnd, (int)FMNoticeTypeEnum.今日提醒, "PF135");

                    #endregion

                    T_SC_MT_MEETING_BEGIN modelBegin = null;
                    if (entity.REPORT_ID.HasValue && entity.LEADER_USER_ID.HasValue)
                    {
                        //事故调查小组成员 
                        modelBegin = new T_SC_MT_MEETING_BEGIN();
                        modelBegin.ID = Guid.NewGuid();
                        modelBegin.ORG_ID = entity.ORG_ID;
                        modelBegin.SOURCETYPE = SOURCETYPE.AE008ToMeet;
                        modelBegin.TABLENAME = "T_AE_ACCIDENT_EVENT_REPORT";
                        modelBegin.DATA_ID = entity.REPORT_ID.Value;
                        modelBegin.ISBEGIN = false;
                        modelBegin.USER_ID = entity.LEADER_USER_ID.Value;
                        modelBegin.CREATE_TIME = DateTime.Now;
                        modelBegin.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    }

                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //事故调查小组成员
                        if (DeputyLeaderUser != null && DeputyLeaderUser.Any())
                            BantchSaveEntityNoCommit(DeputyLeaderUser);
                        if (TeamMembers != null && TeamMembers.Any())
                            BantchSaveEntityNoCommit(TeamMembers);
                        if (task != null) //消除待办
                            UpdateEntityNoCommit(task);

                        if (WarmOA != null)//添加 今日提醒给调查记录人 今日提醒
                            AddEntityNoCommit(WarmOA);

                        if (modelBegin != null)
                            UpdateEntityNoCommit(modelBegin);   //对接会议模块

                        //if (modelResult != null)//添加 事故事件调查结果填报
                        //    AddEntityNoCommit(modelResult);
                        //if (taskAdd != null)//添加 事故事件调查结果填报 待办
                        //    AddEntityNoCommit(taskAdd);
                    });

                    //方法修改 对接模式修改
                    //#region   对接会议模块 事务隔离 以免后续没对应模块  
                    //try
                    //{
                    //    var listUserID = TeamMembers.Where(e => !e.IS_DELETED && e.USER_ID.HasValue).Select(e => e.USER_ID.Value);
                    //    var eventReport = GetEntity<T_AE_ACCIDENT_EVENT_REPORT>(entity.REPORT_ID.Value, "Nav_Department");
                    //    SCMTMeetingService.AddMeeting(Guid.NewGuid(), "事故事件触发会议" + DateTime.Now.ToString("yyMMdd"), eventReport.CODE, eventReport.ORG_ID, Survery.DEPARTMENT_ID.Value, eventReport.Nav_Department.DEPARTMENT_TYPE, entity.LEADER_USER_ID.Value, (int)CREACTTYPEEnum.AEToMTAfterTeamMember, listUserID);
                    //}
                    //catch { }
                    //#endregion

                }

                return true;
            });
        }

    }
}