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/CMAbilityEvaluate")]
    public class CMAbilityEvaluateController : AuthorizeApiController<T_CM_ABILITY_EVALUATE>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMUserService UserService { get; set; }
        public CMAbilityEvaluateController(IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IFMNotificationTaskService notificationTaskService, IFMUserService userService)
        {
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            NotificationTaskService = notificationTaskService;
            UserService = userService;
        }

        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetNew")]
        public JsonActionResult<T_CM_ABILITY_EVALUATE> GetNew([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                T_CM_ABILITY_EVALUATE model = new T_CM_ABILITY_EVALUATE();
                var listProject = GetEntities<T_CM_ABILITY_PROJECT>(null, null, null).OrderBy(e => e.EVALUATE_CONTENT);
                if (listProject != null && listProject.Any())
                {
                    DateTime dtNow = DateTime.Now;
                    Guid LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                    model.ID = Guid.NewGuid();
                    model.ORG_ID = filter.OrgId;
                    model.CREATE_TIME = dtNow;
                    model.MODIFY_TIME = dtNow;
                    model.CREATER_ID = LoginID;
                    model.MODIFIER_ID = LoginID;

                    model.Nav_ListProject = new List<T_CM_ABILITY_EVALUATE_PROJECT>();
                    model.Nav_Users = new List<T_CM_ABILITY_EVALUATE_USER>();
                    foreach (var item in listProject)
                    {
                        model.Nav_ListProject.Add(new T_CM_ABILITY_EVALUATE_PROJECT()
                        {
                            ID = Guid.NewGuid(),
                            EVALUATE_ID = model.ID,
                            PROJECT_ID = item.ID,
                            Nav_EvaluateProject = item,
                            //PLATFORM_TYPE
                            //REMARK
                            IS_DELETED = false,
                            ORG_ID = filter.OrgId,
                            //ENTITY_ORG_TPYE
                            //FORM_ID
                            //FLOW_STATUS
                            //FLOW_SEND_STATUS
                            ////FLOW_ID
                            CREATE_TIME = dtNow,
                            MODIFY_TIME = dtNow,
                            CREATER_ID = LoginID,
                            MODIFIER_ID = LoginID,
                        });
                    }
                }
                else
                {
                    throw new Exception("请先配置评估项目表！【系统管理 => 应急管理设置 => 评估项目】");
                }
                return model;
            });
        }
        /// <summary>
        /// 体检周期表 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_CM_ABILITY_EVALUATE entity)
        {
            return SafeExecute<bool>(() =>
            {
                var listUsers = entity.Nav_Users;
                entity.Nav_Users = null;

                var listListProject = entity.Nav_ListProject;
                entity.Nav_ListProject = null;

                List<T_FM_NOTIFICATION_TASK> listTask = null;
                T_FM_NOTIFICATION_TASK taskEnd = null;
                #region     值判断

                if (listUsers == null || !listUsers.Any())
                {
                    throw new Exception("请选择评估人员！");
                }
                if (listListProject.Any())
                {
                    foreach (var item in listListProject)
                    {
                        item.Nav_EvaluateProject = null;
                    }
                }
                if (entity.STATUS != PFStandardStatus.Draft)
                {
                    if (listListProject.Any())
                    {
                        int rowIndex = 1;
                        foreach (var item in listListProject)
                        {
                            if (item.PLATFORM_TYPE == null)
                            {
                                throw new Exception("请选择行【" + rowIndex + "】的评估情况！");
                            }
                            rowIndex++;
                        }

                        List<Guid> UserId = new List<Guid>();
                        List<string> userName = new List<string>();
                        var listUserID = listUsers.Where(e => !e.IS_DELETED).Select(e => e.USER_ID);
                        var listUser = GetEntities<T_FM_USER>(e => listUserID.Contains(e.ID), null, null);
                        foreach (var item in listUser)
                        {
                            UserId.Add(item.ID);
                            userName.Add(item.NAME);
                        }
                        listTask = NotificationTaskService.InsertUserNoticeTaskModels("应急能力评估确认", entity.ID, entity.ORG_ID, UserId, userName,
  DateTime.Now, DateTime.Now.AddDays(1), 0, "CM026_SHOWPRINT", APT.Infrastructure.Api.AppContext.CurrentSession.UserID);
                    }
                    else
                    {
                        throw new Exception("未获取到评估明细，操作失败！");
                    }

                    if (entity.TaskID != Guid.Empty)
                    {
                        taskEnd = NotificationTaskService.GetEntityTask(entity.TaskID, "CM026_SHOWPRINT");
                        if (!taskEnd.SOURCE_DATA_ID.HasValue)
                        {
                            taskEnd.SOURCE_DATA_ID = entity.ID;
                        }
                    }
                }

                #endregion


                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (taskEnd != null)
                        UpdateEntityNoCommit(taskEnd);
                    if (listUsers != null && listUsers.Any())//明细
                        BantchSaveEntityNoCommit(listUsers);
                    if (listListProject != null && listListProject.Any())//关联应急预案
                        BantchSaveEntityNoCommit(listListProject);
                    if (listTask != null && listTask.Any())//关联应急预案
                        BantchSaveEntityNoCommit(listTask);
                });

                return true;
            });
        }

        /// <summary>
        /// 评估人员签到
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Check")]
        public JsonActionResult<bool> Check([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                //评估人员签到，所有评估人员签到后触发审批
                Guid ABILITY_ID = new Guid(filter.Keyword);
                T_CM_ABILITY_EVALUATE ability = GetEntity<T_CM_ABILITY_EVALUATE>(ABILITY_ID, "Nav_Users");
                Guid taskID = Guid.Empty;
                if (!string.IsNullOrEmpty(filter.Parameter1))
                    taskID = new Guid(filter.Parameter1);
                if (ability.STATUS == PFStandardStatus.Sign)
                {
                    #region     评估人员 确认

                    if (ability.Nav_Users == null || !ability.Nav_Users.Any())
                    {
                        throw new Exception("获取确认信息失败！");
                    }


                    var loginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    var loginSign = ability.Nav_Users.FirstOrDefault(e => e.USER_ID == loginID);
                    if (loginSign == null)
                    {
                        throw new Exception("未获取到需要您确认的信息！");
                    }
                    else if (loginSign.ISCHECK)
                    {
                        throw new Exception("未获取到您未确认的信息！");
                    }
                    loginSign.ISCHECK = true;
                    loginSign.MODIFIER_ID = loginID;
                    loginSign.MODIFY_TIME = DateTime.Now;
                    var check = ability.Nav_Users.FirstOrDefault(e => !e.ISCHECK && e.USER_ID != loginID);

                    T_FM_NOTIFICATION_TASK taskSafe = null;
                    if (check == null)//除了登陆者 大家都确认了
                    {
                        ability.STATUS = PFStandardStatus.Approving;
                        //给安环部负责人 发送确认
                        string Msg = string.Empty;
                        var userSafeMaster = UserService.GetRoleUser(ref Msg, "安环部负责人", null, null);
                        if (userSafeMaster != null)
                        {
                            taskSafe = NotificationTaskService.InsertUserNoticeTaskModel("应急能力评估确认", ABILITY_ID, filter.OrgId, userSafeMaster.ID, userSafeMaster.NAME, DateTime.Now, DateTime.Now.AddDays(1), 0, "CM026_SHOWPRINT");
                        }
                    }

                    //结束 待办
                    T_FM_NOTIFICATION_TASK task = NotificationTaskService.GetEntityTask(taskID);
                    this.UnifiedCommit(() =>
                    {
                        if (loginSign != null)
                            UpdateEntityNoCommit(loginSign);
                        if (task != null)//代办消息 清除
                            UpdateEntityNoCommit(task);
                        if (ability != null)//最后一个人 状态修改
                            UpdateEntityNoCommit(ability);
                        if (taskSafe != null)//最后一个人  给安环部负责人 发送待办
                            UpdateEntityNoCommit(taskSafe);
                    });
                    #endregion
                }
                else
                {
                    //安环部负责人 确认
                    ability.STATUS = PFStandardStatus.Archived;
                    //结束 待办
                    T_FM_NOTIFICATION_TASK task = NotificationTaskService.GetEntityTask(taskID);
                    this.UnifiedCommit(() =>
                    {
                        if (task != null)//代办消息 清除
                            UpdateEntityNoCommit(task);
                        if (ability != null)//最后一个人 状态修改
                            UpdateEntityNoCommit(ability);
                    });
                }

                return true;
            });
        }


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