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.AE;
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/AEAccidentEventSurveyResult")]
    public class AEAccidentEventSurveyResultController : AuthorizeApiController<T_AE_ACCIDENT_EVENT_SURVEY_RESULT>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMNotificationTaskService NotificActionTaskService { get; set; }
        IAEAccidentEventReportService AccidentEventReportService { get; set; }
        public AEAccidentEventSurveyResultController(IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IFMNotificationTaskService notificActionTaskService, IAEAccidentEventReportService accidentEventReportService)
        {
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            NotificActionTaskService = notificActionTaskService;
            AccidentEventReportService = accidentEventReportService;
        }

        /// <summary>
        /// 获得单条实体数据(添加限制结束时间)
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("Get")]
        public JsonActionResult<T_AE_ACCIDENT_EVENT_SURVEY_RESULT> Get([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                filter.IgnoreDataRule = true;
                var result = GetEntity<T_AE_ACCIDENT_EVENT_SURVEY_RESULT>(null, filter, null);
                if (result.Nav_AccidentEventReport != null && result.Nav_AccidentEventReport.ACCIDENT_LEVEL.HasValue && result.Nav_AccidentEventReport.ACCIDENT_LEVEL.HasValue)
                {
                    var level = GetEntity<T_AE_ACCIDENT_LEVEL_DAYS>(e => e.ACCIDENT_LEVEL == result.Nav_AccidentEventReport.ACCIDENT_LEVEL.Value);
                    if (level != null)
                    {
                        result.SYSTEMMAXTIME = result.Nav_AccidentEventReport.TIME.Value.AddDays(level.DAYS + 1).AddSeconds(-1);
                    }
                }
                return result;
            });
        }

        /// <summary>
        /// 获得单条实体数据(添加限制结束时间)
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetAE010")]
        public JsonActionResult<T_AE_ACCIDENT_EVENT_SURVEY_RESULT> GetAE010([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var result = GetEntity<T_AE_ACCIDENT_EVENT_SURVEY_RESULT>(null, filter, null);
                if (result.Nav_AccidentEventReport != null && result.Nav_AccidentEventReport.ACCIDENT_LEVEL.HasValue && result.Nav_AccidentEventReport.ACCIDENT_LEVEL.HasValue)
                {
                    var level = GetEntity<T_AE_ACCIDENT_LEVEL_DAYS>(e => e.ACCIDENT_LEVEL == result.Nav_AccidentEventReport.ACCIDENT_LEVEL.Value);
                    if (level != null)
                    {
                        result.SYSTEMMAXTIME = result.Nav_AccidentEventReport.TIME.Value.AddDays(level.DAYS + 1).AddSeconds(-1);
                    }
                }

                result.Nav_ListReason = GetEntities<T_AE_ACCIDENT_EVENT_SURVEY_REASON>(e => e.RESULT_ID == result.ID, null, new string[] { "Nav_ListReasonType.Nav_ReasonType" }).ToList();
                result.Nav_ListForensics = GetEntities<T_AE_ACCIDENT_EVENT_SURVEY_FORENSICS>(e => e.RESULT_ID == result.ID, null, null).ToList();
                result.Nav_ListEquipmentLoss = GetEntities<T_AE_ACCIDENT_EVENT_SURVEY_EQUIPMENT_LOSS>(e => e.RESULT_ID == result.ID, null, null).ToList();
                result.Nav_ListCasualties = GetEntities<T_AE_ACCIDENT_EVENT_SURVEY_CASUALTIES>(e => e.RESULT_ID == result.ID, null, new string[] { "Nav_User" }).ToList();
                result.Nav_ListAdmPunishment = GetEntities<T_AE_ACCIDENT_EVENT_SURVEY_ADM_PUNISHMENT>(e => e.RESULT_ID == result.ID, null, new string[] { "Nav_Department", "Nav_User" }).ToList();

                return result;
            });
        }

        /// <summary>
        /// 事故事件调查结果 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_AE_ACCIDENT_EVENT_SURVEY_RESULT entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity.STATUS != PFStandardStatus.Draft && entity.STATUS != PFStandardStatus.Approving) //.Archived => Approving
                {
                    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("您不能操作此事故事件调查结果表，操作失败！");
                    }
                }
                if (!entity.REPORT_ID.HasValue || entity.REPORT_ID == Guid.Empty)
                {
                    throw new Exception("获取事故事件关联信息失败！");
                }

                //致害物
                var ListSurveyDamageObject = entity.Nav_ListSurveyDamageObject;
                entity.Nav_ListSurveyDamageObject = null;
                if (ListSurveyDamageObject != null && ListSurveyDamageObject.Any())
                {
                    foreach (var item in ListSurveyDamageObject)
                    {
                        item.Nav_SurveyResult = null;
                        item.Nav_DamageObject = null;
                    }
                }
                //调查报告附件
                var FilesSurvey = entity.Nav_FilesSurvey;
                entity.Nav_FilesSurvey = null;

                //公示文件附件
                var FilesP = entity.Nav_FilesP;
                entity.Nav_FilesP = null;

                //事故事件原因
                var ListReason = entity.Nav_ListReason;
                entity.Nav_ListReason = null;
                List<T_AE_ACCIDENT_EVENT_SURVEY_REASON_TYPE> listReasonType = new List<T_AE_ACCIDENT_EVENT_SURVEY_REASON_TYPE>();
                if (ListReason != null && ListReason.Any())
                {
                    ListReason = ListReason.Where(e => e.Nav_ListReasonType != null).ToList();
                }
                if (ListReason != null && ListReason.Any())
                {
                    //ListReason = ListReason.Where(e=>e.);
                    foreach (var item in ListReason)
                    {
                        if (item.Nav_ListReasonType != null && item.Nav_ListReasonType.Any())
                        {
                            foreach (var itemType in item.Nav_ListReasonType)
                            {
                                itemType.Nav_ReasonType = null;
                            }
                            listReasonType.AddRange(item.Nav_ListReasonType);
                        }
                        item.Nav_ListReasonType = null;
                    }
                }
                //调查取证资料
                var ListForensics = entity.Nav_ListForensics;
                entity.Nav_ListForensics = null;
                if (ListForensics != null && ListForensics.Any())
                {
                    ListForensics = ListForensics.Where(e => e.EVIDENCE_DESC != null || e.EVIDENCE_SOURCE > 0).ToList();
                }
                List<T_AE_ACCIDENT_EVENT_SURVEY_FORENSICS_FILE> listFoFiles = new List<T_AE_ACCIDENT_EVENT_SURVEY_FORENSICS_FILE>();
                if (ListForensics != null && ListForensics.Any())
                {
                    foreach (var item in ListForensics)
                    {
                        item.RESULT_ID = entity.ID;
                        if (item.Nav_FilesSurvey != null && item.Nav_FilesSurvey.Any())
                        {
                            foreach (var itemFile in item.Nav_FilesSurvey)
                            {
                                itemFile.SURVEY_FORENSICS_ID = item.ID;
                                itemFile.ORG_ID = entity.ORG_ID;
                                itemFile.Nav_SurveyForensics = null;
                            }
                            listFoFiles.AddRange(item.Nav_FilesSurvey);
                            item.Nav_FilesSurvey = null;
                        }
                    }
                }


                //设备设施损失信息
                var ListEquipmentLoss = entity.Nav_ListEquipmentLoss;
                entity.Nav_ListEquipmentLoss = null;
                if (ListEquipmentLoss != null && ListEquipmentLoss.Any())
                {
                    ListEquipmentLoss = ListEquipmentLoss.Where(e => e.EQUIPMENT_ID.HasValue || e.FACILITIES_ID.HasValue).ToList();
                }
                //人员伤亡信息
                var ListCasualties = entity.Nav_ListCasualties;
                entity.Nav_ListCasualties = null;
                if (ListCasualties != null && ListCasualties.Any())
                {
                    ListCasualties = ListCasualties.Where(e => e.USER_ID.HasValue).ToList();
                }
                if (ListCasualties != null && ListCasualties.Any())
                {
                    int rowNO = 0;
                    foreach (var item in ListCasualties)
                    {
                        rowNO++;
                        if (!item.INJURED_TIME.HasValue)
                            continue;
                        if (item.INJURED_TIME.Value > DateTime.Now)
                        {
                            throw new Exception("人员伤亡，第【" + rowNO + "】行受伤时间不能大于当前时间！");
                        }
                    }
                }

                //行政处罚信息
                var ListAdmPunishment = entity.Nav_ListAdmPunishment;
                entity.Nav_ListAdmPunishment = null;
                if (ListAdmPunishment != null && ListAdmPunishment.Any())
                {
                    ListAdmPunishment = ListAdmPunishment.Where(e => e.DEPARTMENT_ID.HasValue).ToList();
                }


                if (entity.STATUS == PFStandardStatus.Draft)
                {
                    //保存草稿
                    this.UnifiedCommit(() =>
                    {
                        if (entity != null) //事故事件调查结果
                            UpdateEntityNoCommit(entity);
                        if (ListSurveyDamageObject != null && ListSurveyDamageObject.Any())//致害物
                            BantchSaveEntityNoCommit(ListSurveyDamageObject);
                        if (FilesSurvey != null && FilesSurvey.Any())//调查报告附件
                            BantchSaveEntityNoCommit(FilesSurvey);
                        if (FilesP != null && FilesP.Any())//公示文件附件
                            BantchSaveEntityNoCommit(FilesP);

                        if (ListReason != null && ListReason.Any())//事故事件原因
                            BantchSaveEntityNoCommit(ListReason);
                        if (listReasonType != null && listReasonType.Any())//事故事件原因类别
                            BantchSaveEntityNoCommit(listReasonType);

                        if (ListForensics != null && ListForensics.Any())//调查取证资料
                            BantchSaveEntityNoCommit(ListForensics);
                        if (listFoFiles != null && listFoFiles.Any())//调查取证资料  附件（证据）
                            BantchSaveEntityNoCommit(listFoFiles);

                        if (ListEquipmentLoss != null && ListEquipmentLoss.Any())//设备设施损失信息
                            BantchSaveEntityNoCommit(ListEquipmentLoss);
                        if (ListCasualties != null && ListCasualties.Any())//人员伤亡信息
                            BantchSaveEntityNoCommit(ListCasualties);
                        if (ListAdmPunishment != null && ListAdmPunishment.Any())//行政处罚信息
                            BantchSaveEntityNoCommit(ListAdmPunishment);
                    });

                }
                else
                {
                    if (!entity.REPORT_ID.HasValue)
                    {
                        throw new Exception("获取事故事件参数有误！");
                    }
                    if (!entity.TIME.HasValue)
                    {
                        throw new Exception("请填写实际结案时间！");
                    }
                    if (!entity.CASUALTY_COUNT.HasValue)
                    {
                        throw new Exception("请填写事故伤亡人数！");
                    }
                    else if (entity.CASUALTY_COUNT < 0)
                    {
                        throw new Exception("请填写正确的事故伤亡人数！");
                    }

                    if (!entity.ECONOMIC_LOSSES.HasValue)
                    {
                        throw new Exception("请填写直接经济损失（元）！");
                    }
                    else if (entity.ECONOMIC_LOSSES < 0)
                    {
                        throw new Exception("请填写正确的直接经济损失（元）！");
                    }
                    if (string.IsNullOrEmpty(entity.ACCIDENT_COURSE))
                    {
                        throw new Exception("请填写事故事件经过");
                    }
                    else if (entity.ACCIDENT_COURSE.Length > 1000)
                    {
                        throw new Exception("事故事件经过不能超过1000字");
                    }

                    if (ListReason == null || !ListReason.Any())
                    {
                        throw new Exception("请填写事故事件原因！");
                    }
                    if (ListForensics == null || !ListForensics.Any())
                    {
                        throw new Exception("请填写调查取证资料！");
                    }
                    //// 设备设施 或者  人员伤亡 必须有一个
                    //if ((ListEquipmentLoss == null || !ListEquipmentLoss.Any()) && (ListCasualties == null || !ListCasualties.Any()))
                    //{
                    //    throw new Exception("请填写设备设施损失信息或者写人员伤亡信息！");
                    //}
                    if (ListCasualties == null || !ListCasualties.Any())
                    {
                        if (entity.CASUALTY_COUNT.HasValue && entity.CASUALTY_COUNT.Value > 0)
                        {
                            throw new Exception("请填写人员伤亡信息！");
                        }
                    }

                    //不一定都要有
                    //if (ListAdmPunishment == null || !ListAdmPunishment.Any())
                    //{
                    //    throw new Exception("请填写行政处罚信息！");
                    //}

                    T_FM_NOTIFICATION_TASK task = null;
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificActionTaskService.GetEntityTask(entity.TaskID, "AE010_SHOWPRINT");
                    }

                    var AccdentReport = GetEntity<T_AE_ACCIDENT_EVENT_REPORT>(e => e.ID == entity.REPORT_ID);
                    string param = AccidentEventReportService.GetApproveParm(AccdentReport);

                    //走上报审批流
                    //保存数据
                    entity.APPROVE_ID = Guid.NewGuid();
                    Guid userID = Guid.Empty;
                    //事故部门 负责人
                    var dep = GetEntity<T_FM_DEPARTMENT>(AccdentReport.DEPARTMENT_ID.Value);
                    if (dep.USER_ID != null && dep.USER_ID != Guid.Empty)
                    {
                        userID = dep.USER_ID.Value;
                    }
                    else
                    {
                        userID = GetEntity<T_FM_USER>(e => e.DEPARTMENT_ID == AccdentReport.DEPARTMENT_ID).ID;
                    }

                    //限制结案时间 =上报时间 +限制天数（事故事件等级）
                    if (AccdentReport.TIME.HasValue && AccdentReport.ACCIDENT_LEVEL.HasValue)
                    {
                        var levelDays = GetEntity<T_AE_ACCIDENT_LEVEL_DAYS>(e => e.ACCIDENT_LEVEL == AccdentReport.ACCIDENT_LEVEL);
                        if (levelDays == null)
                        {
                            throw new Exception("请联系管理员配置【事故等级结案限制】，配置路径：系统管理 > 事故事件设置 > 事故等级结案限制");
                        }
                        entity.SYSTEMMAXTIME = AccdentReport.TIME.Value.Date.AddDays(1 + levelDays.DAYS).AddSeconds(-1);
                    }

                    MFlowPermitService.InsertApprove("", "AE010", param, entity.ID, "AE010_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        if (entity != null) //事故事件调查结果
                            UpdateEntityNoCommit(entity);
                        if (ListSurveyDamageObject != null && ListSurveyDamageObject.Any())//致害物
                            BantchSaveEntityNoCommit(ListSurveyDamageObject);
                        if (FilesSurvey != null && FilesSurvey.Any())//调查报告附件
                            BantchSaveEntityNoCommit(FilesSurvey);
                        if (FilesP != null && FilesP.Any())//公示文件附件
                            BantchSaveEntityNoCommit(FilesP);

                        if (ListReason != null && ListReason.Any())//事故事件原因
                            BantchSaveEntityNoCommit(ListReason);
                        if (listReasonType != null && listReasonType.Any())//事故事件原因类别
                            BantchSaveEntityNoCommit(listReasonType);

                        if (ListForensics != null && ListForensics.Any())//调查取证资料
                            BantchSaveEntityNoCommit(ListForensics);
                        if (listFoFiles != null && listFoFiles.Any())//调查取证资料  附件（证据）
                            BantchSaveEntityNoCommit(listFoFiles);

                        if (ListEquipmentLoss != null && ListEquipmentLoss.Any())//设备设施损失信息
                            BantchSaveEntityNoCommit(ListEquipmentLoss);
                        if (ListCasualties != null && ListCasualties.Any())//人员伤亡信息
                            BantchSaveEntityNoCommit(ListCasualties);
                        if (ListAdmPunishment != null && ListAdmPunishment.Any())//行政处罚信息
                            BantchSaveEntityNoCommit(ListAdmPunishment);
                    }, entity.APPROVE_ID, userID, null, null, null, null, null);


                    //this.UnifiedCommit(() =>
                    //{
                    //    if (entity != null) //事故事件调查结果
                    //        UpdateEntityNoCommit(entity);
                    //    if (ListSurveyDamageObject != null && ListSurveyDamageObject.Any())//致害物
                    //        BantchSaveEntityNoCommit(ListSurveyDamageObject);
                    //    if (FilesSurvey != null && FilesSurvey.Any())//调查报告附件
                    //        BantchSaveEntityNoCommit(FilesSurvey);
                    //    if (FilesP != null && FilesP.Any())//公示文件附件
                    //        BantchSaveEntityNoCommit(FilesP);

                    //    if (ListReason != null && ListReason.Any())//事故事件原因
                    //        BantchSaveEntityNoCommit(ListReason);
                    //    if (listReasonType != null && listReasonType.Any())//事故事件原因类别
                    //        BantchSaveEntityNoCommit(listReasonType);

                    //    if (ListForensics != null && ListForensics.Any())//调查取证资料
                    //        BantchSaveEntityNoCommit(ListForensics);
                    //    if (listFoFiles != null && listFoFiles.Any())//调查取证资料  附件（证据）
                    //        BantchSaveEntityNoCommit(listFoFiles);

                    //    if (ListEquipmentLoss != null && ListEquipmentLoss.Any())//设备设施损失信息
                    //        BantchSaveEntityNoCommit(ListEquipmentLoss);
                    //    if (ListCasualties != null && ListCasualties.Any())//人员伤亡信息
                    //        BantchSaveEntityNoCommit(ListCasualties);
                    //    if (ListAdmPunishment != null && ListAdmPunishment.Any())//行政处罚信息
                    //        BantchSaveEntityNoCommit(ListAdmPunishment);
                    //});
                }
                return true;
            });
        }

        /// <summary>
        /// 事故事件调查结果审批回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("EventResultBack")]
        public JsonActionResult<bool> EventResultBack(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("AE/AEAccidentEventSurveyResult/EventResultBack", id);
            });
        }
    }
}