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.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/AEInvestigationRecord")]
    public class AEInvestigationRecordController : AuthorizeApiController<T_AE_INVESTIGATION_RECORD>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMNotificationTaskService NotificActionTaskService { get; set; }
        public AEInvestigationRecordController(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_INVESTIGATION_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity.STATUS != PFStandardStatus.Draft && entity.STATUS != PFStandardStatus.Sign)
                {
                    throw new Exception("获取操作方式有误！");
                }
                var loginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.CREATE_TIME.HasValue && entity.CREATE_TIME < DateTime.Now && entity.USER_ID.Value != loginID.Value)
                {
                    throw new Exception("此勘察记录单不是您添加的，操作失败！");
                }

                var UsersInvestigation = entity.Nav_UsersInvestigation;//勘察人员
                entity.Nav_UsersInvestigation = null;
                var UsersAsk = entity.Nav_UsersAsk;//询问人员
                entity.Nav_UsersAsk = null;

                var FilesAcc = entity.Nav_FilesAcc;//事故照片
                entity.Nav_FilesAcc = null;
                var FilesChart = entity.Nav_FilesChart;//绘制事故图
                entity.Nav_FilesChart = null;
                var NotesFilesNotes = entity.Nav_NotesFilesNotes;//现场笔录
                entity.Nav_NotesFilesNotes = null;

                if (UsersAsk != null && UsersAsk.Count > 0)
                {
                    foreach (var item in UsersAsk)
                    {
                        item.Nav_User = null;
                    }
                }

                if (entity.STATUS == PFStandardStatus.Draft)
                {

                    if (UsersInvestigation != null && UsersInvestigation.Count > 0)
                    {
                        foreach (var item in UsersInvestigation)
                        {
                            item.Nav_User = null;
                        }
                    }
                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //勘察记录
                        if (UsersInvestigation != null && UsersInvestigation.Any())//勘察人员
                            BantchSaveEntityNoCommit(UsersInvestigation);
                        if (UsersAsk != null && UsersAsk.Any())//询问人员
                            BantchSaveEntityNoCommit(UsersAsk);
                        if (FilesAcc != null && FilesAcc.Any())//事故照片
                            BantchSaveEntityNoCommit(FilesAcc);
                        if (FilesChart != null && FilesChart.Any())//绘制事故图
                            BantchSaveEntityNoCommit(FilesChart);
                        if (NotesFilesNotes != null && NotesFilesNotes.Any())//现场笔录
                            BantchSaveEntityNoCommit(NotesFilesNotes);
                    });
                }
                else
                {
                    if (entity.ACCIDENT_ID == null)
                    {
                        throw new Exception("请选择事故事件！");
                    }
                    if (entity.INVESTIGATION_TIME == null)
                    {
                        throw new Exception("请选择勘察时间！");
                    }
                    //else if (entity.INVESTIGATION_TIME > DateTime.Now.Date.AddDays(1).AddSeconds(-1))
                    //{
                    //    throw new Exception("勘察时间不能大于今天！");
                    //}
                    if (string.IsNullOrEmpty(entity.INVESTIGATION_LOCATION))
                    {
                        throw new Exception("请填写勘察地点！");
                    }
                    if (string.IsNullOrEmpty(entity.INVESTIGATION_REASON))
                    {
                        throw new Exception("请填写勘察事由！");
                    }
                    if (string.IsNullOrEmpty(entity.SCENE_ENV_DESC))
                    {
                        throw new Exception("请填写事故现场外围和环境情况！");
                    }
                    if (entity.ACCIDENT_ID == null)
                    {
                        throw new Exception("请选择事故事件！");
                    }
                    if (UsersInvestigation == null || !UsersInvestigation.Any())
                    {
                        throw new Exception("请选择勘察人员！");
                    }

                    //事故 事件 调查小组
                    var TeamMember = GetEntity<T_AE_ACCIDENT_SURVEY_TEAM_MEMBER>(e => e.REPORT_ID == entity.ACCIDENT_ID && e.STATUS == PFStandardStatus.Archived);
                    if (TeamMember == null)
                    {
                        throw new Exception("获取该事故事件调查小组信息失败！");
                    }
                    entity.TEAM_MEMBER_ID = TeamMember.ID;
                    if (TeamMember == null || TeamMember.LEADER_USER_ID == null)
                    {
                        throw new Exception("调查小组组长不能为空！");
                    }
                    entity.LEADER_USER_ID = TeamMember.LEADER_USER_ID;//组长

                    List<Guid> listUserID = new List<Guid>();
                    List<string> listUserName = new List<string>();
                    var listUsersInvestigation = UsersInvestigation.ToList();
                    for (int i = 0; i < listUsersInvestigation.Count; i++)
                    {
                        if (!listUserID.Contains(listUsersInvestigation[i].USER_ID) && !listUsersInvestigation[i].IS_DELETED)
                        {
                            listUserID.Add(listUsersInvestigation[i].USER_ID);
                            listUserName.Add(listUsersInvestigation[i].Nav_User.NAME);
                        }
                    }

                    if (UsersInvestigation != null && UsersInvestigation.Count > 0)
                    {
                        foreach (var item in UsersInvestigation)
                        {
                            item.Nav_User = null;
                        }
                    }

                    //给勘察人员发送待办
                    List<T_FM_NOTIFICATION_TASK> listTask = NotificActionTaskService.InsertUserNoticeTaskModels("勘察记录审阅", entity.ID, entity.ORG_ID, listUserID, listUserName, DateTime.Now, DateTime.Now.AddHours(12), (int)FMNoticeTypeEnum.消息, "AE018_SHOWPRINT");


                    T_FM_NOTIFICATION_TASK taskEnd = null;
                    if (entity.TaskID != Guid.Empty)
                    {
                        taskEnd = NotificActionTaskService.GetTaskFinishModel(entity.TaskID, "AE018_SHOWPRINT");
                    }

                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //勘察记录
                        if (UsersInvestigation != null && UsersInvestigation.Any())//勘察人员
                            BantchSaveEntityNoCommit(UsersInvestigation);
                        if (UsersAsk != null && UsersAsk.Any())//询问人员
                            BantchSaveEntityNoCommit(UsersAsk);
                        if (FilesAcc != null && FilesAcc.Any())//事故照片
                            BantchSaveEntityNoCommit(FilesAcc);
                        if (FilesChart != null && FilesChart.Any())//绘制事故图
                            BantchSaveEntityNoCommit(FilesChart);
                        if (NotesFilesNotes != null && NotesFilesNotes.Any())//现场笔录
                            BantchSaveEntityNoCommit(NotesFilesNotes);
                        if (listTask != null && listTask.Any())//现场笔录
                            BantchSaveEntityNoCommit(listTask);
                        if (taskEnd != null)
                            UpdateEntityNoCommit(taskEnd);
                    });

                    try
                    {
                        //如果 勘察人员 包含 登陆者  添加 审阅
                        if (listUserID.Contains(loginID.Value))
                        {
                            KeywordFilter filter = new KeywordFilter();
                            filter.Keyword = entity.ID.ToString();
                            filter.Parameter1 = listTask.FirstOrDefault(e => e.USER_ID == loginID.Value).ID.ToString();
                            Read(filter);
                        }
                    }
                    catch { }

                }
                return true;
            });
        }

        /// <summary>
        /// 勘察人员 审阅
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost, Route("Read")]
        public JsonActionResult<bool> Read([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                if (string.IsNullOrEmpty(filter.Keyword) || string.IsNullOrEmpty(filter.Parameter1))
                {
                    throw new Exception("传参有误！");
                }
                var guid = new Guid(filter.Keyword);
                var taskID = new Guid(filter.Parameter1);
                if (guid == Guid.Empty || taskID == Guid.Empty)
                {
                    throw new Exception("传参有误！");
                }
                var loginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var Check = GetEntity<T_AE_INVESTIGATION_RECORD_INVESTIGATION_USERS>(e => e.USER_ID == loginID && e.RECORD_ID == guid);
                var task = NotificActionTaskService.GetEntityTask(taskID);


                if (Check == null)
                {
                    this.UnifiedCommit(() =>
                    {
                        if (task != null)
                            UpdateEntityNoCommit(task);
                    });
                    throw new Exception("您无需确认！");
                }
                else
                {

                    if (Check.STATUS == AEInvestigationUserStatusEnum.已审阅)
                    {
                        this.UnifiedCommit(() =>
                        {
                            if (task != null)
                                UpdateEntityNoCommit(task);
                        });
                        throw new Exception("您已审阅,无需再次操作！");
                    }
                    else
                    {
                        Check.STATUS = AEInvestigationUserStatusEnum.已审阅;
                        var UnCheck = GetEntity<T_AE_INVESTIGATION_RECORD_INVESTIGATION_USERS>(e => e.USER_ID != loginID && e.RECORD_ID == guid && e.STATUS == AEInvestigationUserStatusEnum.未审阅);
                        if (UnCheck == null)
                        {
                            T_AE_INVESTIGATION_RECORD model = GetEntity<T_AE_INVESTIGATION_RECORD>(Check.RECORD_ID, "Nav_LeaderUser");

                            Dictionary<int, T_FM_USER> dicApproveUser = new Dictionary<int, T_FM_USER>();
                            var approve = GetEntity<T_PF_APPROVE_TEMP>(e => e.FORM_CODE == "AE018", "Nav_ApproveTempDetails");
                            if (approve == null || approve.Nav_ApproveTempDetails == null || !approve.Nav_ApproveTempDetails.Any())
                            {
                                throw new Exception("您联系管理员配置勘察记录表！");
                            }
                            else
                            {
                                List<T_PF_APPROVE_TEMP_DETAIL> listATD = approve.Nav_ApproveTempDetails.OrderBy(e => e.NUM).ToList();
                                for (int i = 0; i < listATD.Count; i++)
                                {
                                    if (listATD[i].NAME.Contains("副组长"))
                                    {
                                        var listLeaders = GetEntities<T_AE_ACCIDENT_SURVEY_TEAM_DEPUTY_LEADER>(e => e.TEAM_MEMBER_ID == model.TEAM_MEMBER_ID.Value, null, "Nav_User");
                                        if (listLeaders == null || !listLeaders.Any())
                                        {
                                            dicApproveUser.Add((i + 1), model.Nav_LeaderUser);//组长
                                            break;
                                        }
                                        else if (listLeaders.Count() == 1)
                                        {
                                            //副组长
                                            dicApproveUser.Add((i + 1), listLeaders.ToList()[0].Nav_User);
                                        }
                                        else
                                        {
                                            //如果有多个副组长 就跳过该节点（直接组长审批）
                                            dicApproveUser.Add((i + 1), model.Nav_LeaderUser);//组长
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        dicApproveUser.Add((i + 1), model.Nav_LeaderUser);//组长
                                    }
                                }
                            }

                            model.APPROVE_ID = Guid.NewGuid();
                            model.STATUS = PFStandardStatus.Approving;//变成已归档
                            //给调查组组长 发送待办
                            MFlowPermitService.InsertApprove("", "AE018", null, model.ID, "AE018_SHOWPRINT", null, true, () =>
                            {
                                if (model != null)
                                    UpdateEntityNoCommit(model);
                                if (Check != null)
                                    UpdateEntityNoCommit(Check);
                                if (task != null)
                                    UpdateEntityNoCommit(task);
                            }, model.APPROVE_ID, null, dicApproveUser);
                        }
                        else
                        {
                            this.UnifiedCommit(() =>
                            {
                                if (task != null)
                                    UpdateEntityNoCommit(task);
                                if (Check != null)
                                    UpdateEntityNoCommit(Check);
                            });
                        }
                    }
                }
                return true;
            });
        }



        /// <summary>
        /// 勘察记录组长审批完成后回调  
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("LeaderCheck")]
        public JsonActionResult<bool> LeaderCheck(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("AE/AEInvestigationRecord/LeaderCheck", id);
            });
        }

    }
}