using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
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.CM;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace APT.SC.WebApi.Controllers.Api.CM
{
    [Route("api/CM/CMUrgentEvent")]
    public class CMUrgentEventController : AuthorizeApiController<T_CM_URGENT_EVENT>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMUserService UserService { get; set; }
        public CMUrgentEventController(IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IFMNotificationTaskService notificationTaskService, IFMUserService userService)
        {
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            NotificationTaskService = notificationTaskService;
            UserService = userService;
        }

        /// <summary>
        /// 体检周期表 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_CM_URGENT_EVENT entity)
        {
            return SafeExecute<bool>(() =>
            {
                #region     值判断

                var ListArearInfluence = entity.Nav_ListArearInfluence;
                entity.Nav_ListArearInfluence = null;
                if (ListArearInfluence == null || !ListArearInfluence.Any())
                {
                    throw new Exception("请选择预计影响范围！");
                }
                else
                {
                    foreach (var item in ListArearInfluence)
                    {
                        if (item.URGENT_EVENT_ID == Guid.Empty)
                        {
                            item.URGENT_EVENT_ID = entity.ID; //自动触发 没 ID
                        }
                    }
                }

                var ListEventRiskType = entity.Nav_ListEventRiskType;
                entity.Nav_ListEventRiskType = null;

                if (ListEventRiskType == null || !ListEventRiskType.Any())
                {
                    throw new Exception("请选择风险类别！");
                }
                else
                {
                    foreach (var item in ListEventRiskType)
                    {
                        if (item.URGENT_EVENT_ID == Guid.Empty)
                        {
                            item.URGENT_EVENT_ID = entity.ID;//item.ORG_ID = entity.ORG_ID;   
                        }
                    }
                }
                var ListEventContingencyPlan = entity.Nav_ListEventContingencyPlan;
                entity.Nav_ListEventContingencyPlan = null;

                if (ListEventContingencyPlan == null || !ListEventContingencyPlan.Any())
                {
                    throw new Exception("请填写预案信息！");
                }
                else
                {
                    foreach (var item in ListEventContingencyPlan)
                    {
                        if (item.URGENT_EVENT_ID == Guid.Empty)
                        {
                            item.URGENT_EVENT_ID = entity.ID; //item.ORG_ID = entity.ORG_ID;
                        }

                        //if (item.COMPLETE_TIME<DateTime.Now)
                        //{
                        //    throw  有的修改其中的
                        //}
                    }
                }

                #endregion

                foreach (var item in ListArearInfluence)
                {
                    item.Nav_CoverageInfluence = null;
                }
                foreach (var item in ListEventRiskType)
                {
                    item.Nav_RiskType = null;
                }
                T_FM_NOTIFICATION_TASK taskEnd = null;
                if (entity.TaskID != Guid.Empty)
                {
                    taskEnd = NotificationTaskService.GetEntityTask(entity.TaskID, "CM018_SHOWPRINT");
                    if (!taskEnd.SOURCE_DATA_ID.HasValue)
                        taskEnd.SOURCE_DATA_ID = entity.ID;
                }

                if (entity.ENABLE_STATUS == FMEnableStatusEnum.禁用)
                {
                    foreach (var item in ListEventContingencyPlan)
                    {
                        item.ENABLE_STATUS = entity.ENABLE_STATUS;
                    }
                }

                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (ListArearInfluence != null && ListArearInfluence.Any())//预计影响范围
                        BantchSaveEntityNoCommit(ListArearInfluence);
                    if (ListEventRiskType != null && ListEventRiskType.Any())//风险类别
                        BantchSaveEntityNoCommit(ListEventRiskType);
                    if (ListEventContingencyPlan != null && ListEventContingencyPlan.Any())//预案类型
                        BantchSaveEntityNoCommit(ListEventContingencyPlan);
                    if (taskEnd != null)
                        UpdateEntityNoCommit(taskEnd);
                });

                return true;
            });
        }



        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedReport")]
        public PagedActionResult<T_CM_URGENT_EVENT_CONTINGENCY_PLAN> OrderPagedReport([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_CM_URGENT_EVENT_CONTINGENCY_PLAN> result)
            {
                pageFilter.Include.Remove("Nav_UrgentEvent");
                pageFilter.Include.Remove("Nav_UrgentEvent.Nav_EventType");

                PagedActionResult<T_CM_URGENT_EVENT_CONTINGENCY_PLAN> orderPageEntities = GetOrderPageEntities<T_CM_URGENT_EVENT_CONTINGENCY_PLAN>(null, pageFilter, null);
                if (orderPageEntities.Data != null && orderPageEntities.Data.Any())
                {
                    List<Guid> listPlanID = orderPageEntities.Data.Select(e => e.URGENT_EVENT_ID).Distinct().ToList();
                    List<T_CM_URGENT_EVENT> listEvent = GetEntities<T_CM_URGENT_EVENT>(e => listPlanID.Contains(e.ID), null, new string[] { "Nav_EventType", "Nav_ListArearInfluence.Nav_CoverageInfluence", "Nav_ListEventRiskType.Nav_RiskType" }).ToList();
                    foreach (var item in listEvent)
                    {
                        if (item.Nav_ListArearInfluence != null && item.Nav_ListArearInfluence.Any())
                        {
                            foreach (var itemInf in item.Nav_ListArearInfluence)
                            {
                                item.AREARINFLUENCE += "，" + itemInf.Nav_CoverageInfluence.NAME;
                            }
                            item.AREARINFLUENCE = item.AREARINFLUENCE.Substring(1);
                        }

                        if (item.Nav_ListEventRiskType != null && item.Nav_ListEventRiskType.Any())
                        {
                            foreach (var itemRisk in item.Nav_ListEventRiskType)
                            {
                                item.RISKTYPE += "，" + itemRisk.Nav_RiskType.NAME;
                            }
                            item.RISKTYPE = item.RISKTYPE.Substring(1);
                        }
                    }
                    T_CM_URGENT_EVENT temp = null;
                    foreach (var item in orderPageEntities.Data)
                    {
                        temp = listEvent.FirstOrDefault(e => e.ID == item.URGENT_EVENT_ID);
                        if (temp != null)
                        {
                            item.Nav_UrgentEvent = temp;
                        }
                    }

                    orderPageEntities.Data = orderPageEntities.Data.OrderBy(e => e.Nav_UrgentEvent.Nav_EventType.NAME).ThenBy(e => e.URGENT_EVENT_ID);
                }

                result.Data = orderPageEntities.Data;
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }


        /// <summary>
        /// 应急事件 或者应急库中查看
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetShowPrint")]
        public JsonActionResult<T_CM_URGENT_EVENT> GetShowPrint([FromBody] KeywordFilter filter)
        {
            Guid ID = Guid.Empty;
            Guid PlanID = Guid.Empty;
            if (filter.FilterGroup.Rules.Count > 0)
            {
                foreach (var item in filter.FilterGroup.Rules)
                {
                    if (item.Field == "ID")
                    {
                        ID = new Guid(item.Value.ToString());
                    }
                    else if (item.Field == "PLANID")
                    {
                        PlanID = new Guid(item.Value.ToString());
                    }
                }

            }
            if (PlanID == Guid.Empty)
            {
                return WitEntity(null, filter);
            }
            else
            {
                filter.FilterGroup.Rules.Clear();
                var plan = GetEntity<T_CM_URGENT_EVENT_CONTINGENCY_PLAN>(PlanID);
                ID = plan.URGENT_EVENT_ID;
                return WitEntity(e => e.ID == ID, filter);
            }
        }
    }
}