using APT.BaseData.Domain.Entities;
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;

namespace APT.SC.WebApi.Controllers.Api.CM
{
    [Route("api/CM/CMDrillEstimate")]
    public class CMDrillEstimateController : AuthorizeApiController<T_CM_DRILL_ESTIMATE>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMUserService UserService { get; set; }
        public CMDrillEstimateController(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_DRILL_ESTIMATE entity)
        {
            return SafeExecute<bool>(() =>
            {
                var ListEstimateRecord = entity.Nav_ListEstimateRecord;
                entity.Nav_ListEstimateRecord = null;
                if (!string.IsNullOrEmpty(entity.ADVISE) && entity.ADVISE.Length >= 300)
                {
                    throw new Exception("【其他改进方面】不能超过300个字符！");
                }
                if (entity.STATUS == PFStandardStatus.Draft)
                {
                    foreach (var item in ListEstimateRecord)
                    {
                        item.Nav_Item = null;
                    }
                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);
                        if (ListEstimateRecord != null && ListEstimateRecord.Any())//评估人员
                            BantchSaveEntityNoCommit(ListEstimateRecord);
                    });
                }
                else
                {
                    int RowIndex = 1;
                    foreach (var item in ListEstimateRecord)
                    {
                        item.Nav_Item = null;
                        if (!item.SCORE.HasValue)
                        {
                            throw new Exception("请选择评价结果【行：" + RowIndex + "】！");
                        }
                        RowIndex++;
                    }
                    //给所有 评估人员 发送 【演练效果评估表】 确认待办
                    List<T_FM_NOTIFICATION_TASK> listTask = new List<T_FM_NOTIFICATION_TASK>();
                    T_FM_NOTIFICATION_TASK task = null;
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetEntityTask(entity.TaskID, "CM036_SHOWPRINT");
                    }

                    var listUser = GetEntities<T_CM_DRILL_RECORD_USER_ESTIMATE>(e => e.RECORD_ID == entity.RECORD_ID && !e.ISSIGN && !e.IS_DELETED, null, "Nav_User");
                    if (listUser != null && listUser.Any())
                    {
                        List<Guid> UserId = new List<Guid>();
                        List<string> userName = new List<string>();
                        foreach (var item in listUser)
                        {
                            UserId.Add(item.USER_ID);
                            userName.Add(item.Nav_User.NAME);
                        }

                        listTask = NotificationTaskService.InsertUserNoticeTaskModels("演练效果评估确认", entity.ID, entity.ORG_ID, UserId, userName, DateTime.Now, DateTime.Now.AddDays(1), 1, "CM036_SHOWPRINT");
                    }

                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);
                        if (task != null)
                            UpdateEntityNoCommit(task);
                        if (ListEstimateRecord != null && ListEstimateRecord.Any())//评估结果
                            BantchSaveEntityNoCommit(ListEstimateRecord);
                        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 ESTIMATE_ID = new Guid(filter.Keyword);
                T_CM_DRILL_ESTIMATE ability = GetEntity<T_CM_DRILL_ESTIMATE>(ESTIMATE_ID, "Nav_Record.Nav_ListUserEstimate");
                Guid taskID = Guid.Empty;
                if (!string.IsNullOrEmpty(filter.Parameter1))
                    taskID = new Guid(filter.Parameter1);

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

                T_FM_NOTIFICATION_TASK taskSafe = null;
                T_FM_NOTIFICATION_TASK taskKnowledge = null;
                if (check == null)//除了登陆者 大家都确认了
                {
                    ability.STATUS = PFStandardStatus.Archived;
                    //给安环部负责人 发送确认
                    string Msg = string.Empty;
                    var userSafeMaster = UserService.GetRoleUser(ref Msg, "安环部负责人", null, null);
                    if (userSafeMaster != null)
                    {
                        taskSafe = NotificationTaskService.InsertUserNoticeTaskModel("请召开应急预案内部审核会", ESTIMATE_ID, filter.OrgId, userSafeMaster.ID, userSafeMaster.NAME, DateTime.Now, DateTime.Now.AddDays(1), 2, null);
                    }

                    //如“人员培训充分”的选项为一般、差，触发给一条今日提醒给安环部负责人，消息类型：组织培训，消息内容：请组织应急知识和技能培训
                    var listScoreGen = GetEntities<T_CM_DRILL_ESTIMATE_RECORD>(e => e.ESTIMEATE_ID == ESTIMATE_ID && e.SCORE.HasValue && (e.SCORE.Value == CMEvaluateStatusEnum.General || e.SCORE.Value == CMEvaluateStatusEnum.Bad), null, "Nav_Item");

                    bool isOther = false;//是否 请组织应急知识和技能培训
                    if (listScoreGen != null && listScoreGen.Any())
                    {
                        foreach (var item in listScoreGen)
                        {
                            if (item.Nav_Item.NAME.Contains("人员培训充分"))
                            {
                                isOther = true;
                                break;
                            }
                        }
                        if (isOther)
                        {
                            taskKnowledge = NotificationTaskService.InsertUserNoticeTaskModel("请组织应急知识和技能培训", ESTIMATE_ID, filter.OrgId, userSafeMaster.ID, userSafeMaster.NAME, DateTime.Now, DateTime.Now.AddDays(1), 2, null);
                        }
                    }
                }

                //结束 待办
                T_FM_NOTIFICATION_TASK task = NotificationTaskService.GetEntityTask(taskID);
                this.UnifiedCommit(() =>
                {
                    if (loginSign != null)
                        UpdateEntityNoCommit(loginSign);
                    if (task != null)//代办消息 清除
                        UpdateEntityNoCommit(task);
                    if (taskSafe != null)
                    {
                        if (ability != null)//最后一个人 状态修改
                            UpdateEntityNoCommit(ability);
                        if (taskSafe != null)//最后一个人  给安环部负责人 发送待办
                            UpdateEntityNoCommit(taskSafe);
                        if (taskKnowledge != null)//人员培训充分   请组织应急知识和技能培训
                            UpdateEntityNoCommit(taskKnowledge);
                    }
                });
                return true;
            });
        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetOrder")]
        public JsonActionResult<T_CM_DRILL_ESTIMATE> GetOrder([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var model = GetEntity<T_CM_DRILL_ESTIMATE>(null, filter, null);
                if (model.Nav_Record != null && model.Nav_Record.Nav_ListUserEstimate.Any())
                {
                    //第一个人 记录人
                    model.Nav_Record.Nav_ListUserEstimate = model.Nav_Record.Nav_ListUserEstimate.OrderByDescending(e => e.ISSIGN).ToList();
                }
                return model;
            });
        }


        /// <summary>
        /// 应急演练活动  审批结束
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("DrillEstimateEnd")]
        public JsonActionResult<bool> DrillEstimateEnd(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("CM/CMDrillPlan/DrillEstimateEnd", id);
            });
        }
    }
}