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.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/CMRspEstimate")]
    public class CMRspEstimateController : AuthorizeApiController<T_CM_RSP_ESTIMATE>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMUserService UserService { get; set; }
        public CMRspEstimateController(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_RSP_ESTIMATE entity)
        {
            return SafeExecute<bool>(() =>
            {
                //评估人员
                var ListEstimate = entity.Nav_ListEstimate;
                entity.Nav_ListEstimate = null;

                //应急响应情况
                var ListRspConditions = entity.Nav_ListRspConditions;
                entity.Nav_ListRspConditions = null;

                #region     值判断

                if (string.IsNullOrEmpty(entity.EVENT_NAME))
                    throw new Exception("请填写事故/事件名称!");
                if (entity.STATUS == PFStandardStatus.Sign)
                {
                    //保存并发送
                    if (!entity.DEPARTMENT_ID_REPORT.HasValue)
                        throw new Exception("请选择事故/事件单位!");
                    if (!entity.RSP_LEVEL.HasValue)
                        throw new Exception("请选择响应级别!");
                    if (ListEstimate == null || !ListEstimate.Any())
                        throw new Exception("请选择评估人员!");
                    if (!entity.RSP_TRAINING_LEVEL.HasValue)
                        throw new Exception("请选择培训水平!");
                    if (ListRspConditions != null && ListRspConditions.Any())
                    {
                        int rowIndex = 1;
                        foreach (var item in ListRspConditions)
                        {
                            item.Nav_RspEstimateCondition = null;
                            if (!item.RSP_CONDITION_STATUS.HasValue)
                            {
                                throw new Exception("请选择应急响应情况结果，行：" + rowIndex + "!");
                            }
                            rowIndex++;
                        }
                    }
                }

                #endregion

                //事故/事件种类
                var ListEventKind = entity.Nav_ListEventKind;
                entity.Nav_ListEventKind = null;
                //Todo 2401
                //if (ListEventKind != null && ListEventKind.Any())
                //{
                //    foreach (var item in ListEventKind)
                //    {
                //        item.Nav_RspAccdentKind = null;
                //    }
                //}

                //参与人员
                var ListJoin = entity.Nav_ListJoin;
                entity.Nav_ListJoin = null;
                if (ListJoin != null && ListJoin.Any())
                {
                    foreach (var item in ListJoin)
                    {
                        item.Nav_User = null;
                    }
                }
                if (ListEstimate != null && ListEstimate.Any())
                {
                    foreach (var item in ListEstimate)
                    {
                        item.Nav_User = null;
                    }
                }
                //发起人填写完成后点击通知，触发待办事项给评估人员签到，所有评估人员签到后触发审批
                List<T_FM_NOTIFICATION_TASK> listTask = null;
                if (entity.STATUS == PFStandardStatus.Sign)
                {
                    List<Guid> listUserID = ListEstimate.Select(e => e.USER_ID).ToList();
                    var listUser = GetEntities<T_FM_USER>(e => listUserID.Contains(e.ID), null, null);
                    List<Guid> UserId = new List<Guid>();
                    List<string> userName = new List<string>();
                    foreach (var user in listUser)
                    {
                        if (UserId.Contains(user.ID))
                            continue;
                        UserId.Add(user.ID);
                        userName.Add(user.NAME);
                    }
                    Guid? LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    listTask = NotificationTaskService.InsertUserNoticeTaskModels("应急响应评估签到", entity.ID, entity.ORG_ID, UserId, userName, DateTime.Now, DateTime.Now.AddDays(1), 0, "CM023_SHOWPRINT", LoginID);
                    //评估人员签到处理
                    if (LoginID.HasValue && UserId.Contains(LoginID.Value))
                    {
                        foreach (var item in ListEstimate)
                        {
                            if (item.USER_ID == LoginID.Value)
                            {
                                item.ISSIGN = true;
                                break;
                            }
                        }
                    }
                }


                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (ListEstimate != null && ListEstimate.Any()) //评估人员
                        BantchSaveEntityNoCommit(ListEstimate);
                    if (ListRspConditions != null && ListRspConditions.Any())//应急响应情况
                        BantchSaveEntityNoCommit(ListRspConditions);
                    if (ListEventKind != null && ListEventKind.Any())   //事故/事件种类
                        BantchSaveEntityNoCommit(ListEventKind);
                    if (ListJoin != null && ListJoin.Any())  //参与人员
                        BantchSaveEntityNoCommit(ListJoin);
                    if (listTask != null && listTask.Any())  //评估人员签到
                        BantchSaveEntityNoCommit(listTask);
                });
                return true;
            });
        }


        /// <summary>
        /// 获取事故事件的 事故/事件种类
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEventKinds")]
        public JsonActionResult<List<T_CM_RSP_ESTIMATE_EVENT_KIND>> GetEventKinds([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                List<T_CM_RSP_ESTIMATE_EVENT_KIND> listResult = new List<T_CM_RSP_ESTIMATE_EVENT_KIND>();
                Guid EventID = Guid.NewGuid();
                Guid ESTIMATE_ID = Guid.NewGuid();
                if (filter.FilterGroup.Rules != null && filter.FilterGroup.Rules.Any())
                {
                    foreach (var item in filter.FilterGroup.Rules)
                    {
                        if (item.Field == "EventID" && !string.IsNullOrEmpty(item.Value.ToString()))
                        {
                            EventID = new Guid(item.Value.ToString());
                        }
                        else if (item.Field == "ID")
                        {
                            ESTIMATE_ID = new Guid(item.Value.ToString());
                        }
                    }
                }

                if (EventID == Guid.Empty || ESTIMATE_ID == Guid.Empty)
                {
                    return listResult;
                }
                //Todo 2401
                //var Kinds = GetEntities<T_AE_ACCIDENT_EVENT_REPORT_LIST_KIND>(e => e.REPORT_ID == EventID && !e.IS_DELETED, null, "Nav_AccidentKind");
                //if (Kinds != null && Kinds.Any())
                //{
                //    foreach (var item in Kinds)
                //    {
                //        listResult.Add(new T_CM_RSP_ESTIMATE_EVENT_KIND()
                //        {
                //            ID = Guid.NewGuid(),
                //            ESTIMATE_ID = ESTIMATE_ID,
                //            KIND_ID = item.Nav_AccidentKind.ID,
                //            Nav_RspAccdentKind = item.Nav_AccidentKind,
                //            IS_DELETED = false,
                //            ORG_ID = filter.OrgId,
                //            //ENTITY_ORG_TPYE       = ,
                //            //FORM_ID               = ,
                //            //FLOW_STATUS           = ,
                //            //FLOW_SEND_STATUS      = ,
                //            //FLOW_ID               = ,
                //            //CREATE_TIME           = ,
                //            //MODIFY_TIME           = ,
                //            //CREATER_ID            = ,
                //            //MODIFIER_ID           = 

                //        });
                //    }
                //}
                return listResult;
            });
        }

        /// <summary>
        /// 评估人员签到
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Sign")]
        public JsonActionResult<bool> Sign([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                //评估人员签到，所有评估人员签到后触发审批
                Guid ESTIMATE_ID = new Guid(filter.Keyword);
                var listSign = GetEntities<T_CM_RSP_ESTIMATE_ESTIMATE_USER>(e => e.ESTIMATE_ID == ESTIMATE_ID && !e.ISSIGN, null, null);
                if (listSign == null || !listSign.Any())
                {
                    throw new Exception("获取确认信息失败！");
                }

                Guid taskID = Guid.Empty;
                if (!string.IsNullOrEmpty(filter.Parameter1))
                    taskID = new Guid(filter.Parameter1);

                var loginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var loginSign = listSign.FirstOrDefault(e => e.USER_ID == loginID);
                if (loginSign == null)
                {
                    throw new Exception("暂未获取到您未确认的信息！");
                }
                loginSign.ISSIGN = true;
                loginSign.MODIFIER_ID = loginID;
                loginSign.MODIFY_TIME = DateTime.Now;
                var isLast = false;
                if (listSign.Count() == 1)
                {
                    isLast = true;
                }

                if (isLast)
                {
                    //修改状态 结束待办 发起审批流 
                    var entity = GetEntity<T_CM_RSP_ESTIMATE>(ESTIMATE_ID);
                    entity.STATUS = PFStandardStatus.Approving;//其实是检查中了

                    entity.APPROVE_ID = Guid.NewGuid();
                    string serialCode = "XYPG" + DateTime.Now.ToString("yyyyMMddHHmmss");
                    var param = ((int)entity.RSP_LEVEL.Value).ToString();

                    MFlowPermitService.InsertApprove(serialCode, "CM023", param, entity.ID, "CM023_SHOWPRINT", taskID, true, () =>
                   {
                       if (entity != null)
                           UpdateEntityNoCommit(entity);
                       if (loginSign != null)
                           UpdateEntityNoCommit(loginSign);
                   }, entity.APPROVE_ID, entity.USER_ID, null, null, null, "CM023_SHOWPRINT");
                }
                else
                {
                    //结束 待办
                    T_FM_NOTIFICATION_TASK task = NotificationTaskService.GetEntityTask(taskID);
                    this.UnifiedCommit(() =>
                    {
                        if (loginSign != null)
                            UpdateEntityNoCommit(loginSign);
                        if (task != null)//代办消息 清除
                            UpdateEntityNoCommit(task);
                    });
                }
                return true;
            });
        }

        /// <summary>
        /// 年度应急演练计划表  审批结束
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("EstimateBack")]
        public JsonActionResult<bool> EstimateBack(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("CM/CMRspEstimate/EstimateBack", id);
            });
        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetOrder")]
        public JsonActionResult<T_CM_RSP_ESTIMATE> GetOrder([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var model = GetEntity<T_CM_RSP_ESTIMATE>(null, filter, null);
                if (model.Nav_ListRspConditions != null && model.Nav_ListRspConditions.Any())
                {
                    model.Nav_ListRspConditions = model.Nav_ListRspConditions.OrderBy(e => e.ROW_NO).ToList();
                }
                return model;
            });
        }
    }
}