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.HM;
using APT.MS.Domain.Entities.WB;
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.WB
{
    [Route("api/WB/WBHiddenDangerNotify")]
    public class WBHiddenDangerNotifyController : AuthorizeApiController<T_WB_HIDDEN_DANGER_NOTIFY>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        public WBHiddenDangerNotifyController(IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService)
        {
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_WB_HIDDEN_DANGER_NOTIFY entity)
        {
            return SafeExecute(() =>
            {
                //T_FM_NOTIFICATION_TASK finishNotice = null;
                //T_FM_NOTIFICATION_TASK sendNotice = null;
                var Nav_Details = entity.Nav_Details;
                var Nav_Files = entity.Nav_Files;
                entity.Nav_Details = null;
                entity.Nav_Files = null;
                List<T_WB_HIDDEN_DANGER_NOTIFY_DETAIL_FILE> Files = new List<T_WB_HIDDEN_DANGER_NOTIFY_DETAIL_FILE>();
                entity.LAUNCH_USER_ID = (Guid)APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                foreach (var item in Nav_Details)
                {
                    item.ROW_NUM = item.ROW_NUM + 1;
                    if (item.Nav_Files != null && item.Nav_Files.Count() > 0)
                    {
                        item.Nav_Files.ForEach(nf =>
                        {
                            nf.PARENT_ID = item.ID;
                        });
                        Files.AddRange(item.Nav_Files);
                        item.Nav_Files = null;
                    }
                }

                T_PF_APPROVE approve = null;
                ICollection<T_PF_APPROVE_DETAIL> listApproveDetail = null;
                T_FM_NOTIFICATION_TASK finishTask = null;
                T_FM_NOTIFICATION_TASK nextTask = null;
                string CALLBACK_INTERFACE = "";
                List<string> listDATA_ID = new List<string>();

                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    var project = GetEntity<T_WB_PROJECT_INPUT>(entity.PROJECT_ID, "Nav_SceneUser");
                    //var userID = project.SCENE_USER_ID;
                    //var userNAME = GetEntity<T_FM_USER>(userID).NAME;
                    //entity.STATUS = PFStandardStatus.Approving;
                    //sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("外包工程隐患整改通知单-审批", entity.ID, entity.ORG_ID, userID, userNAME, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB037_SHOWPRINT");
                    //if (entity.TaskID != Guid.Empty)
                    //{
                    //    finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID);
                    //}

                    Dictionary<int, T_FM_USER> dicApproveUser = new Dictionary<int, T_FM_USER>();
                    dicApproveUser.Add(1, project.Nav_SceneUser);//建设项目现场负责人
                    string Msg = "";
                    approve = MFlowPermitService.GetApproveInfo("WB037", null, entity.ID, "WB037_SHOWPRINT", entity.TaskID, "WB037_SHOWPRINT", null, dicApproveUser, null, "", ref Msg, ref finishTask, ref nextTask, ref CALLBACK_INTERFACE, ref listDATA_ID);
                    if (Msg != null && !string.IsNullOrEmpty(Msg))
                    {
                        throw new Exception(Msg);//如果有问题 进行提示
                    }
                    listApproveDetail = approve.Nav_ApproveDetails;
                    approve.Nav_ApproveDetails = null;

                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (Nav_Details != null && Nav_Details.Any())
                        BantchSaveEntityNoCommit(Nav_Details);
                    if (Nav_Files != null && Nav_Files.Any())
                        BantchSaveEntityNoCommit(Nav_Files);
                    if (Files != null && Files.Any())
                        BantchSaveEntityNoCommit(Files);
                    //if (sendNotice != null)
                    //    AddEntityNoCommit(sendNotice);
                    //if (finishNotice != null)
                    //    UpdateEntityNoCommit(finishNotice);

                    if (approve != null)
                        UpdateEntity(approve);
                    if (listApproveDetail != null && listApproveDetail.Any())
                        BantchSaveEntityNoCommit(listApproveDetail);
                    if (finishTask != null)
                        UpdateEntity(finishTask);
                    if (nextTask != null)
                        UpdateEntity(nextTask);
                });


                //执行信息
                if (!string.IsNullOrEmpty(CALLBACK_INTERFACE))
                {
                    if (CALLBACK_INTERFACE.EndsWith("New"))
                    {
                        this.UnifiedCommit(() =>
                        {
                            ApproveCallBackService.CallBackNew(CALLBACK_INTERFACE, approve, false);
                        });
                    }
                    else
                    {
                        this.UnifiedCommit(() =>
                        {
                            ApproveCallBackService.CallBack(CALLBACK_INTERFACE, listDATA_ID);
                        });
                    }
                }

                return true;
            });
        }
        /// <summary>
        /// 签到
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("recordSign")]
        public JsonActionResult<bool> recordSign([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var id = Guid.Parse(filter.Parameter1);
                var taskID = Guid.Parse(filter.Parameter2);
                var userID = Guid.Parse(filter.Parameter3);
                var orgId = filter.GetOrgId();
                var sendUserID = Guid.Empty;
                var sendUserNAME = "";
                var users = GetEntities<T_WB_SAFE_CHECK_TASK_DETAIL_USER>(t => t.Nav_Record.Nav_Parent.ID == id, new BaseFilter(orgId));
                var currUser = users.FirstOrDefault(t => t.USER_ID == userID);
                T_FM_NOTIFICATION_TASK finishTask = null;
                T_FM_NOTIFICATION_TASK sendNotice = null;
                currUser.DEAL_STATUS = UserDealStatusEnum.已处理;
                currUser.MODIFY_TIME = DateTime.Now;
                T_WB_SAFE_CHECK_TASK model = null;
                var todoCount = users.Count(t => t.DEAL_STATUS == 0);
                if (todoCount == 0)
                {
                    model = GetEntity<T_WB_SAFE_CHECK_TASK>(id);
                    model.STATUS = PFStandardStatus.Reading;
                }
                if (taskID != Guid.Empty)
                {
                    finishTask = NotificationTaskService.FOGetTaskFinishModel(taskID, id);
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(model);
                    UpdateEntityNoCommit(currUser);
                    if (sendNotice != null)
                        AddEntityNoCommit(sendNotice);
                    if (finishTask != null)
                        UpdateEntityNoCommit(finishTask);

                });
                return true;
            });
        }

        ///// <summary>
        ///// 审核通过
        ///// </summary>
        ///// <param name="pageFilter"></param>
        ///// <returns></returns>
        //[HttpPost, Route("UserAgree")]
        //public JsonActionResult<bool> UserAgree([FromBody] T_WB_HIDDEN_DANGER_NOTIFY entity)
        //{
        //    return SafeExecute<bool>(() =>
        //    {
        //        entity = GetEntity<T_WB_HIDDEN_DANGER_NOTIFY>(entity.ID);
        //        var notify = GetEntity<T_WB_HIDDEN_DANGER_NOTIFY>(t => t.ID == entity.ID);
        //        var currUser = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
        //        T_FM_NOTIFICATION_TASK sendNotice = null;
        //        notify.STATUS = PFStandardStatus.Archived;
        //        T_WB_HIDDEN_DANGER_RECORD record = new T_WB_HIDDEN_DANGER_RECORD();
        //        record.ID = Guid.NewGuid();
        //        record.ORG_ID = entity.ORG_ID;
        //        record.NOTIFY_ID = entity.ID;
        //        List<T_WB_HIDDEN_DANGER_RECORD_DETAIL> recordDetails = new List<T_WB_HIDDEN_DANGER_RECORD_DETAIL>();
        //        List<T_WB_HIDDEN_DANGER_RECORD_DETAIL_BEFORE_FILE> beforeFiles = new List<T_WB_HIDDEN_DANGER_RECORD_DETAIL_BEFORE_FILE>();

        //        BaseFilter recordFilter = new BaseFilter(entity.ORG_ID);
        //        recordFilter.Include = new string[] { "Nav_Files" };
        //        var notifyDetails = GetEntities<T_WB_HIDDEN_DANGER_NOTIFY_DETAIL>(t => t.PARENT_ID == entity.ID, recordFilter);
        //        foreach (var notifyDetail in notifyDetails)
        //        {
        //            T_WB_HIDDEN_DANGER_RECORD_DETAIL recordDetail = new T_WB_HIDDEN_DANGER_RECORD_DETAIL();
        //            recordDetail.ID = Guid.NewGuid();
        //            recordDetail.ORG_ID = entity.ORG_ID;
        //            recordDetail.PARENT_ID = record.ID;
        //            recordDetail.ROW_NUM = notifyDetail.ROW_NUM;
        //            recordDetail.MineType = notifyDetail.MineType;
        //            //recordDetail.AREA = notifyDetail.AREA;
        //            recordDetail.AREA_ID = notifyDetail.AREA_ID;
        //            recordDetail.CHECK_CONTENT = notifyDetail.CHECK_CONTENT;
        //            recordDetail.CHECK_BASIS = notifyDetail.CHECK_BASIS;
        //            recordDetail.REMARK = notifyDetail.REMARK;
        //            recordDetail.ADRESS = notifyDetail.ADRESS;
        //            recordDetail.END_TIME = notifyDetail.END_TIME;
        //            recordDetails.Add(recordDetail);
        //            foreach (var file in notifyDetail.Nav_Files)
        //            {
        //                T_WB_HIDDEN_DANGER_RECORD_DETAIL_BEFORE_FILE file1 = new T_WB_HIDDEN_DANGER_RECORD_DETAIL_BEFORE_FILE();
        //                file1.ID = file.ID;
        //                file1.ORG_ID = file.ORG_ID;
        //                file1.IMG_FILE_ID = file.IMG_FILE_ID;
        //                file1.PARENT_ID = recordDetail.ID;
        //                beforeFiles.Add(file1);
        //            }
        //        }
        //        var project = GetEntity<T_WB_PROJECT_INPUT>(entity.PROJECT_ID);
        //        var user = GetEntity<T_FM_USER>(t => t.CODE == project.WB_USER_CODE);
        //        sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("外包工程隐患整改记录", record.ID, entity.ORG_ID, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB039");
        //        var finishTask = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID);
        //        UnifiedCommit(() =>
        //        {
        //            UpdateEntityNoCommit(notify);
        //            if (finishTask != null)
        //                UpdateEntityNoCommit(finishTask);
        //            if (sendNotice != null)
        //                AddEntityNoCommit(sendNotice);
        //            if (record != null)
        //                AddEntityNoCommit(record);
        //            if (recordDetails != null && recordDetails.Any())
        //                BantchSaveEntityNoCommit(recordDetails);
        //            if (beforeFiles != null && beforeFiles.Any())
        //                BantchSaveEntityNoCommit(beforeFiles);

        //        });
        //        return true;
        //    });
        //}

        /// <summary>
        /// 检查制表申请 审批流回调
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("UserAgreeNew")]
        public JsonActionResult<bool> UserAgreeNew([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBackNew("WB/WBHiddenDangerNotify/UserAgreeNew", entity);
            });
        }

        /// <summary>
        /// 签到
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("UserDisAgree")]
        public JsonActionResult<bool> UserDisAgree([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var id = Guid.Parse(filter.Parameter1);
                var taskID = Guid.Parse(filter.Parameter2);
                var orgId = Guid.Parse(filter.Parameter3);
                var opinion = filter.Parameter4;

                if (string.IsNullOrEmpty(opinion))
                {
                    throw new Exception("请填写理由！");
                }
                var checkRecord = GetEntity<T_WB_HIDDEN_DANGER_NOTIFY>(t => t.ID == id);
                checkRecord.STATUS = PFStandardStatus.Rejected;
                checkRecord.AUDIT_OPINION = opinion;
                checkRecord.AUDIT_OPINION += "<br/>审核时间：" + DateTime.Now;
                var finishTask = NotificationTaskService.FOGetTaskFinishModel(taskID, id);

                var sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("外包工程隐患整改通知单-审批驳回", id, orgId, (Guid)checkRecord.LAUNCH_USER_ID, GetEntity<T_FM_USER>(t => t.ID == checkRecord.LAUNCH_USER_ID).NAME, DateTime.Now, DateTime.Now.AddDays(7), 1, "WB037");
                UnifiedCommit(() =>
                {
                    if (sendNotice != null)
                        AddEntityNoCommit(sendNotice);
                    if (finishTask != null)
                        UpdateEntityNoCommit(finishTask);
                    if (checkRecord != null)
                        UpdateEntityNoCommit(checkRecord);
                });
                return true;
            });
        }
    }
}
