using APT.BaseData.Domain.ApiModel.PF;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Enums;
using APT.Utility;
using APT.WebApi.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace APT.BS.WebApi.Controllers.Api
{
    [Route("api/BS/BSSafeCheckDetailReject")]
    public partial class BSSafeCheckDetailRejectController : AuthorizeApiController<T_BS_SAFE_CHECK_DETAIL_REJECT>
    {

        IFMNotificationTaskService NotificationTaskService { get; set; }

        public BSSafeCheckDetailRejectController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }

        #region       检查记录退回

        /// <summary>
        /// 检查明细退回
        /// </summary>
        /// <param name="filiter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetRejectModel")]
        public JsonActionResult<T_BS_SAFE_CHECK_DETAIL_REJECT> GetRejectModel([FromBody] KeywordFilter filiter)
        {
            return SafeExecute<T_BS_SAFE_CHECK_DETAIL_REJECT>(() =>
            {
                T_BS_SAFE_CHECK_DETAIL_REJECT modelResult = new T_BS_SAFE_CHECK_DETAIL_REJECT();
                Guid SAFE_CHECK_DETAIL_ID = Guid.Empty;
                foreach (var item in filiter.FilterGroup.Rules)
                {
                    if (item.Field == "ID")
                    {
                        SAFE_CHECK_DETAIL_ID = new Guid(item.Value.ToString());
                        break;
                    }
                }
                if (SAFE_CHECK_DETAIL_ID == Guid.Empty)
                {
                    throw new Exception("获取信息失败！");
                }
                modelResult.ID = Guid.NewGuid();
                modelResult.SAFE_CHECK_DETAIL_ID = SAFE_CHECK_DETAIL_ID;
                return modelResult;
            });
        }

        /// <summary>
        /// 检查明细退回
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("Reject")]
        public JsonActionResult<bool> Reject([FromBody] T_BS_SAFE_CHECK_DETAIL_REJECT entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity.SAFE_CHECK_DETAIL_ID == Guid.Empty)
                {
                    throw new Exception("获取传参失败！");
                }
                if (string.IsNullOrEmpty(entity.REASON))
                {
                    throw new Exception("退回原因不能未空！");
                }
                if (entity.Nav_Files == null || !entity.Nav_Files.Any())
                {
                    throw new Exception("请上传退回附件！");
                }
                //检查明细
                var SafeCheckDetail = GetEntity<T_BS_SAFE_CHECK_DETAIL>(entity.SAFE_CHECK_DETAIL_ID);
                if (SafeCheckDetail == null)
                {
                    throw new Exception("获取退回信息失败！");
                }
                if (SafeCheckDetail.IS_REJECTING)
                {
                    throw new Exception("该检查明细结果已被退回给了登记人，请先直接确认！");
                }

                SafeCheckDetail.IS_REJECTING = true;
                SafeCheckDetail.USERID_REJECT = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;

                //退回信息
                entity.SAFE_CHECK_ID = SafeCheckDetail.SAFE_CHECK_ID;

                var files = entity.Nav_Files;
                entity.Nav_Files = null;

                entity.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;//创建人 即 退回人

                var userMain = GetEntity<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_DETAIL_ID == entity.SAFE_CHECK_DETAIL_ID && !e.IS_DELETED && e.ISMAINCHECK, "Nav_User");
                if (userMain == null || userMain.USER_ID == Guid.Empty)
                {
                    throw new Exception("获取检查登记人信息失败！");
                }

                //给记录人 添加待办//BS069
                var TaskReject = NotificationTaskService.InsertUserNoticeTaskModel("检查记录确认退回", entity.ID, entity.ORG_ID, userMain.USER_ID, userMain.Nav_User.NAME, DateTime.Now, 0, "BS069", FMTASKTYPE.Default);

                //保存草稿 只保存页面数据
                this.UnifiedCommit(() =>
                {
                    if (entity != null)//拒绝记录
                        UpdateEntityNoCommit(entity);
                    if (SafeCheckDetail != null)//被退回的检查明细
                        UpdateEntityNoCommit(SafeCheckDetail);
                    if (files != null && files.Any())//附件
                        BantchSaveEntityNoCommit(files);
                    if (TaskReject != null)//检查登记人待办
                        UpdateEntityNoCommit(TaskReject);
                });
                return true;
            });
        }

        #endregion


        #region     退回  信息加载 与 操作


        /// <summary>
        /// 检查明细退回 （BS069）
        /// </summary>
        /// <param name="filiter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetDetailRejectModel")]
        public JsonActionResult<T_BS_SAFE_CHECK_DETAIL> GetDetailRejectModel([FromBody] KeywordFilter filiter)
        {
            return SafeExecute<T_BS_SAFE_CHECK_DETAIL>(() =>
            {
                T_BS_SAFE_CHECK_DETAIL modelResult = null;
                T_BS_SAFE_CHECK_DETAIL_REJECT modelReject = null;
                Guid RejectID = Guid.Empty;
                foreach (var item in filiter.FilterGroup.Rules)
                {
                    if (item.Field == "ID")
                    {
                        RejectID = new Guid(item.Value.ToString());

                        if (RejectID == Guid.Empty)
                        {
                            throw new Exception("获取信息失败！");
                        }

                        modelReject = GetEntity<T_BS_SAFE_CHECK_DETAIL_REJECT>(RejectID, "Nav_Files.Nav_ImgFile.Nav_File");
                        if (modelReject == null)
                        {
                            throw new Exception("获取退回信息失败！");
                        }

                        item.Value = modelReject.SAFE_CHECK_DETAIL_ID;
                    }
                }

                var listInclude = filiter.Include.ToList();
                for (int i = 0; i < listInclude.Count; i++)
                {
                    if (listInclude[i].StartsWith("Nav_Reject"))
                    {
                        listInclude.Remove(listInclude[i]);
                        i--;
                    }
                }
                filiter.Include = listInclude;
                modelResult = GetEntity<T_BS_SAFE_CHECK_DETAIL>(null, filiter);
                if (modelResult != null && modelResult.Nav_ListCheckDetailUser != null)
                {
                    modelResult.Nav_ListCheckDetailUser = modelResult.Nav_ListCheckDetailUser.OrderByDescending(e => e.ISMAINCHECK).ToList();
                }

                modelResult.Nav_Reject = modelReject;
                var userID = modelReject.CREATER_ID;
                if (userID == null)
                    userID = modelResult.USERID_REJECT;
                if (userID.HasValue)
                {
                    T_FM_USER modelUser = GetEntity<T_FM_USER>(userID.Value);//.CREATER_ID APP显示退回人 修改 riskSumbitDetailBack
                    modelReject.Nav_User = modelUser;
                }
                if (DataHelper.GetRequestType(Request.Headers) == 2 && modelResult.Nav_ListCheckDetailQuestion != null && modelResult.Nav_ListCheckDetailQuestion.Any())
                {
                    modelResult.Nav_ListCheckDetailQuestion.ForEach(e =>
                    {
                        if (e.Nav_Question != null)
                        {
                            if (e.Nav_Question.QUESTION_LEVEL > 0)
                            {
                                e.Nav_Question.QUESTION_LEVEL_SHOW = e.Nav_Question.QUESTION_LEVEL.GetDescription();
                            }
                            else
                            {
                                e.Nav_Question.QUESTION_LEVEL_SHOW = "";
                            }
                        }
                    });
                }
                return modelResult;
            });
        }



        /// <summary>
        /// 检查明细退回 重新检查登记（单条）
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("RejectUpdate")]
        public JsonActionResult<bool> RejectUpdate([FromBody] T_BS_SAFE_CHECK_DETAIL entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity.TaskID == Guid.Empty)
                {
                    throw new Exception("获取待办信息失败，请刷新后再试！");
                }
                var LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                T_BS_SAFE_CHECK_DETAIL_REJECT Reject = GetEntity<T_BS_SAFE_CHECK_DETAIL_REJECT>(e => e.SAFE_CHECK_DETAIL_ID == entity.ID);
                //var Reject = entity.Nav_Reject;
                //entity.Nav_Reject = null;

                T_FM_NOTIFICATION_TASK Task = null;
                if (Reject.RESULT != RejectResult.Default)
                {
                    //数据异常 默认正常待办
                    Task = NotificationTaskService.GetEntityTask(entity.TaskID, "BS069_SHOWPRINT", 1);

                    this.UnifiedCommit(() =>
                    {
                        if (Task != null)//拒绝记录
                            UpdateEntityNoCommit(Task);
                    });
                    throw new Exception("该退回单已处理【处理结果：" + Reject.RESULT.GetDescription() + "】，请勿重新操作！");
                }
                var listCheckDetailReason = entity.Nav_ListCheckDetailReason;
                entity.Nav_ListCheckDetailReason = null;

                var listDetailQuestion = GetEntities<T_BS_SAFE_CHECK_DETAIL_QUESTION>(e => e.SAFE_CHECK_DETAIL_ID == entity.ID && !e.IS_DELETED, null, null);
                if (listDetailQuestion == null || !listDetailQuestion.Any())
                {
                    throw new Exception("获取之前的检查结果失败！");
                }
                if (listDetailQuestion.Count() > 1)
                {
                    throw new Exception("此功能只支持单一检查结果！");
                }
                T_BS_SAFE_CHECK_DETAIL_QUESTION ResultOld = listDetailQuestion.ToList()[0];


                if (entity.Nav_ListCheckDetailQuestion == null || !entity.Nav_ListCheckDetailQuestion.Any())
                {
                    throw new Exception("请选择检查结果！");
                }
                var listCheckDetailQuestion = entity.Nav_ListCheckDetailQuestion.Where(e => !e.IS_DELETED);
                if (listCheckDetailQuestion.Count() > 1)
                {
                    throw new Exception("检查结果只能1个！");
                }

                T_BS_SAFE_CHECK_DETAIL_QUESTION ResultNew = listCheckDetailQuestion.ToList()[0];

                if (ResultNew.SAFE_CHECK_QUESTION_ID == new Guid("55555555-5555-5555-5555-555555555555"))
                {
                    entity.CHECKRESULT = 10;
                }
                else
                {
                    entity.CHECKRESULT = 20;
                }

                //var CheckDetail = entity.Nav_CheckDetail;
                //entity.Nav_CheckDetail = null;
                if (entity.CHECKRESULT == 0)
                {
                    throw new Exception("请选择问题描述！");
                }
                if (entity.CHECKRESULT == 20 && string.IsNullOrEmpty(entity.ADDRESS))
                {
                    throw new Exception("请输入隐患地点！");
                }


                if (ResultOld.SAFE_CHECK_QUESTION_ID == ResultNew.SAFE_CHECK_QUESTION_ID)
                {
                    Reject.RESULT = RejectResult.ResultSame;
                }
                else
                {
                    Reject.RESULT = RejectResult.ResultChange;
                }

                //如果有修改    给所有本条明细已确认的人            发送今日提醒
                //如果没有修改  给退回的人                          发送今日提醒
                //检查明细      IS_REJECTING false  USERID_REJECT   置空  
                //如果有修改    修改之前的检查详情  修改之前的检查明细问题
                List<T_FM_NOTIFICATION_TASK> listTaskToday = new List<T_FM_NOTIFICATION_TASK>();
                var safeCheck = GetEntity<T_BS_SAFE_CHECK>(entity.SAFE_CHECK_ID);
                if (Reject.RESULT == RejectResult.ResultSame)
                {
                    //相同
                    var UserReject = GetEntity<T_FM_USER>(entity.USERID_REJECT.Value);
                    listTaskToday.Add(NotificationTaskService.InsertUserNoticeTaskModel("检查退回结果保持不变【编号：" + safeCheck.CODE + "，序号：" + entity.ROW_NO + "】", entity.ID, entity.ORG_ID, UserReject.ID, UserReject.NAME, DateTime.Now, 2, "", FMTASKTYPE.Default));
                }
                else
                {
                    //不同
                    //今日提醒接收人
                    var listUserSend = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_DETAIL_ID == Reject.SAFE_CHECK_DETAIL_ID && !e.IS_DELETED && e.SAFECHECKSTATE == 80 && !e.ISMAINCHECK && e.USER_ID != entity.CREATER_ID, null, "Nav_User");
                    if (listUserSend != null && listUserSend.Any())
                    {
                        List<Guid> listUserID = new List<Guid>();
                        List<string> listUserName = new List<string>();

                        listUserSend.ForEach(e =>
                        {
                            if (!listUserID.Contains(e.USER_ID))
                            {
                                listUserID.Add(e.USER_ID);
                                listUserName.Add(e.Nav_User.NAME);
                            }
                        });

                        listTaskToday.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("检查明细结果修改【编号：" + safeCheck.CODE + "，序号：" + entity.ROW_NO + "】", entity.ID, entity.ORG_ID, listUserID, listUserName, DateTime.Now, 2, "", FMTASKTYPE.Default));
                    }
                }

                entity.IS_REJECTING = false;
                entity.USERID_REJECT = null;

                if (Reject.RESULT == RejectResult.ResultChange)//检查明细 检查结果
                    ResultOld.SAFE_CHECK_QUESTION_ID = ResultNew.SAFE_CHECK_QUESTION_ID;
                entity.Nav_ListCheckDetailQuestion = null;

                var TaskEnd = NotificationTaskService.GetEntityTask(entity.TaskID, "BS069_SHOWPRINT");






                ////保存草稿 只保存页面数据
                this.UnifiedCommit(() =>
                {
                    if (entity != null)//拒绝记录
                        UpdateEntityNoCommit(entity);
                    UpdateEntityNoCommit(entity);//检查明细信息修改
                    if (Reject.RESULT == RejectResult.ResultChange)//如果检查结果发送改变
                        UpdateEntityNoCommit(ResultOld);
                    if (listTaskToday != null && listTaskToday.Any())//今日提醒（已确认或退回者）
                        BantchSaveEntityNoCommit(listTaskToday);
                    if (listCheckDetailReason != null && listCheckDetailReason.Any())//隐患原因
                        BantchSaveEntityNoCommit(listCheckDetailReason);
                    if (TaskEnd != null)//操作待办结束
                        UpdateEntityNoCommit(TaskEnd);
                });
                return true;
            });
        }


        ///// <summary>
        ///// 检查明细退回 重新检查登记（单条）
        ///// </summary>
        ///// <param name="entity"></param>
        ///// <returns></returns>
        //[HttpPost, Route("RejectUpdate")]
        //public JsonActionResult<bool> RejectUpdate([FromBody] T_BS_SAFE_CHECK_DETAIL_REJECT entity)
        //{
        //    return SafeExecute<bool>(() =>
        //    {
        //        if (entity.TaskID == Guid.Empty)
        //        {
        //            throw new Exception("获取待办信息失败，请刷新后再试！");
        //        }
        //        T_FM_NOTIFICATION_TASK Task = null;
        //        if (entity.RESULT != RejectResult.Default)
        //        {
        //            //数据异常 默认正常待办
        //            Task = NotificationTaskService.GetEntityTask(entity.TaskID, "BS069_SHOWPRINT", 1);

        //            this.UnifiedCommit(() =>
        //            {
        //                if (Task != null)//拒绝记录
        //                    UpdateEntityNoCommit(Task);
        //            });
        //            throw new Exception("该退回单已处理【处理结果：" + entity.RESULT.GetDescription() + "】，请勿重新操作！");
        //        }

        //        var CheckDetail = entity.Nav_CheckDetail;
        //        entity.Nav_CheckDetail = null;
        //        if (CheckDetail.CHECKRESULT == 0)
        //        {
        //            throw new Exception("请选择问题描述！");
        //        }
        //        if (CheckDetail.CHECKRESULT == 20 && string.IsNullOrEmpty(CheckDetail.ADDRESS))
        //        {
        //            throw new Exception("请输入隐患地点！");
        //        }

        //        if (CheckDetail.Nav_ListCheckDetailQuestion == null || !CheckDetail.Nav_ListCheckDetailQuestion.Any())
        //        {
        //            throw new Exception("请选择检查结果！");
        //        }
        //        else if (CheckDetail.Nav_ListCheckDetailQuestion.Count() > 1)
        //        {
        //            throw new Exception("检查结果只能1个！");
        //        }

        //        var listDetailQuestion = GetEntities<T_BS_SAFE_CHECK_DETAIL_QUESTION>(e => e.SAFE_CHECK_DETAIL_ID == CheckDetail.ID && !e.IS_DELETED, null, null);
        //        if (listDetailQuestion == null || !listDetailQuestion.Any())
        //        {
        //            throw new Exception("获取之前的检查结果失败！");
        //        }
        //        if (listDetailQuestion.Count() > 1)
        //        {
        //            throw new Exception("此功能只支持单一检查结果！");
        //        }
        //        T_BS_SAFE_CHECK_DETAIL_QUESTION ResultOld = listDetailQuestion.ToList()[0];

        //        T_BS_SAFE_CHECK_DETAIL_QUESTION ResultNew = CheckDetail.Nav_ListCheckDetailQuestion.ToList()[0];

        //        if (ResultOld.SAFE_CHECK_QUESTION_ID == ResultNew.SAFE_CHECK_QUESTION_ID)
        //        {
        //            entity.RESULT = RejectResult.ResultSame;
        //        }
        //        else
        //        {
        //            entity.RESULT = RejectResult.ResultChange;
        //        }

        //        //如果有修改    给所有本条明细已确认的人            发送今日提醒
        //        //如果没有修改  给退回的人                          发送今日提醒
        //        //检查明细      IS_REJECTING false  USERID_REJECT   置空  
        //        //如果有修改    修改之前的检查详情  修改之前的检查明细问题
        //        List<T_FM_NOTIFICATION_TASK> listTaskToday = new List<T_FM_NOTIFICATION_TASK>();
        //        if (entity.RESULT == RejectResult.ResultSame)
        //        {
        //            //相同
        //            var UserReject = GetEntity<T_FM_USER>(CheckDetail.USERID_REJECT.Value);

        //            listTaskToday.Add(NotificationTaskService.InsertUserNoticeTaskModel("检查退回结果保持不变", entity.ID, entity.ORG_ID, UserReject.ID, UserReject.NAME, DateTime.Now, 2, "", FMTASKTYPE.Default));

        //        }
        //        else
        //        {
        //            //不同
        //            //今日提醒接收人
        //            var listUserSend = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_DETAIL_ID == entity.SAFE_CHECK_DETAIL_ID && !e.IS_DELETED && e.SAFECHECKSTATE == 80 && !e.ISMAINCHECK && e.USER_ID != entity.CREATER_ID, null, "Nav_User");
        //            if (listUserSend != null && listUserSend.Any())
        //            {
        //                List<Guid> listUserID = new List<Guid>();
        //                List<string> listUserName = new List<string>();

        //                listUserSend.ForEach(e =>
        //                {
        //                    if (!listUserID.Contains(e.USER_ID))
        //                    {
        //                        listUserID.Add(e.USER_ID);
        //                        listUserName.Add(e.Nav_User.NAME);
        //                    }
        //                });

        //                listTaskToday.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("检查明细结果修改告知", entity.ID, entity.ORG_ID, listUserID, listUserName, DateTime.Now, 2, "", FMTASKTYPE.Default));
        //            }
        //        }

        //        CheckDetail.IS_REJECTING = false;
        //        CheckDetail.USERID_REJECT = null;

        //        if (entity.RESULT == RejectResult.ResultChange)//检查明细 检查结果
        //            ResultOld.SAFE_CHECK_QUESTION_ID = ResultNew.SAFE_CHECK_QUESTION_ID;
        //        CheckDetail.Nav_ListCheckDetailQuestion = null;

        //        var TaskEnd = NotificationTaskService.GetEntityTask(entity.TaskID, "BS069_SHOWPRINT");

        //        ////保存草稿 只保存页面数据
        //        this.UnifiedCommit(() =>
        //        {
        //            if (entity != null)//拒绝记录
        //                UpdateEntityNoCommit(entity);
        //            UpdateEntityNoCommit(CheckDetail);//检查明细信息修改
        //            if (entity.RESULT == RejectResult.ResultChange)//如果检查结果发送改变
        //                UpdateEntityNoCommit(ResultOld);
        //            if (listTaskToday != null && listTaskToday.Any())//今日提醒（已确认或退回者）
        //                BantchSaveEntityNoCommit(listTaskToday);
        //            if (TaskEnd != null)//操作待办结束
        //                UpdateEntityNoCommit(TaskEnd);
        //        });
        //        return true;
        //    });
        //}


        #endregion
    }
}