using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
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.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.HM.WebApi.Controllers.Api
{
    [Route("api/HM/HMHazardRecord")]
    public partial class HazardRecordController : AuthorizeApiController<T_HM_HAZARD_RECORD>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        /// <summary>
        /// 作业任务分析
        /// </summary>
        public HazardRecordController(IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService)
        {
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_HM_HAZARD_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var users = entity.Nav_Users;
                var files = entity.Nav_Files;
                var details = entity.Nav_Details;
                if (!details.Any())
                {
                    throw new Exception("请添加记录明细！");
                }
                entity.Nav_Users = null;
                entity.Nav_Files = null;
                entity.Nav_Details = null;
                List<T_FM_NOTIFICATION_TASK> sendNotices = null;
                T_FM_NOTIFICATION_TASK finishNotice = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    entity.STATUS = FOPreMeetingStatusEnum.签到中;
                    var noticeTitles = new List<string>();
                    var noticeUserIds = new List<Guid>();
                    var noticeUserNames = new List<string>();
                    var noticeDataIds = new List<Guid>();
                    var userDeal = users.Where(t => t.DEAL_STATUS == FOUserShiftStatusEnum.待处理);
                    if (userDeal.Count() > 0)
                    {
                        var allusers = GetEntities<T_FM_USER>(null, new BaseFilter(entity.ORG_ID));
                        var allsendUsers = users.Where(t => t.DEAL_STATUS == FOUserShiftStatusEnum.待处理).Select(t => t.USER_ID).Distinct();
                        foreach (var user in allsendUsers)
                        {
                            var userName = allusers.Where(t => t.ID == user).FirstOrDefault();
                            noticeUserIds.Add(user);
                            noticeUserNames.Add(userName.NAME);
                            noticeTitles.Add("职业危害辨识记录待确认");
                            noticeDataIds.Add(entity.ID);
                        }
                        sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(noticeTitles, noticeDataIds, entity.ORG_ID, noticeUserIds, noticeUserNames, DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(1).ToShortDateString() + " 23:59:59"), 1, "HM099_SHOWPRINT");
                        finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID, entity.ID, "HM099_SHOWPRINT");
                    }
                    else
                    {
                        entity.STATUS = FOPreMeetingStatusEnum.审核中;
                        entity.APPROVECODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                        MFlowPermitService.InsertApprove(entity.APPROVECODE, "HM100", "", entity.ID, "HM099_SHOWPRINT", entity.TaskID, true, () =>
                        {
                        }, null, entity.NOTE_TAKER_ID,null, null, null, "HM099_SHOWPRINT");
                    }
                }
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //保存主表
                    if (users != null && users.Any())
                        BantchSaveEntityNoCommit(users);    //保存子表
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);        //保存子表
                    if (details != null && details.Any())
                        BantchSaveEntityNoCommit(details);      //保存子表
                    if (sendNotices != null && sendNotices.Any())
                        BantchSaveEntityNoCommit(sendNotices);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });
                return true;
            });
        }

        /// <summary>
        /// 获取个人的风险记录
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetHazardRecord")]
        public JsonActionResult<bool> GetHazardRecord([FromBody] T_HM_HAZARD_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var model = GetEntity<T_HM_HAZARD_RECORD>(entity.ID.ToString());
                if (model.STATUS != FOPreMeetingStatusEnum.签到中)
                    return false;
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var count = GetCount<T_HM_HAZARD_RECORD_USER>(t => t.RECORD_ID == entity.ID && t.USER_ID == userId && t.DEAL_STATUS == 0, new BaseFilter());
                if (count > 0)  //该用户在该记录中是否参与且未同意则显示同意按钮
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
        }

        /// <summary>
        /// 同意
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("PersonalAgree")]
        public JsonActionResult<bool> PersonalAgree([FromBody] T_HM_HAZARD_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var taskId = entity.TaskID;
                var recordUsers = GetEntities<T_HM_HAZARD_RECORD_USER>(t => t.RECORD_ID == entity.ID, new BaseFilter(orgId));
                var currUsers = recordUsers.Where(t => t.USER_ID == userId);
                foreach (var user in currUsers)
                {
                    user.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                    user.MODIFY_TIME = DateTime.Now;
                }
                var todoCount = recordUsers.Count(t => t.DEAL_STATUS == 0);
                #region 判断是否全部人员同意
                if (todoCount == 0)
                {
                    entity = GetEntity<T_HM_HAZARD_RECORD>(entity.ID.ToString());
                    entity.STATUS = FOPreMeetingStatusEnum.审核中;
                    #region 提交风险记录审批
                    MFlowPermitService.InsertApprove(DateTime.Now.ToString("yyyyMMddHHmmss"), "HM100", "", entity.ID, "HM099_SHOWPRINT", taskId, true, () =>
                    {
                        if (currUsers != null)
                            BantchUpdateEntityNoCommit(currUsers, "DEAL_STATUS", "MODIFY_TIME");
                        if (entity != null)
                            UpdateEntityNoCommit(entity, "STATUS");
                    }, null, entity.LIABLE_USER_ID);
                    #endregion
                }
                else
                {
                    NotificationTaskService.NotificationTaskFinish(taskId, () =>
                    {
                        if (currUsers != null)
                            BantchUpdateEntityNoCommit(currUsers, "DEAL_STATUS", "MODIFY_TIME");
                    });
                }
                #endregion
                return true;
            });
        }
        /// <summary>
        /// 审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("PersonalApprove")]
        public JsonActionResult<bool> PersonalApprove(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("HM/HMHazardRecord/PersonalApprove", id);
            });
        }
        /// <summary>
        /// 审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("RejectUpdate")]
        public JsonActionResult<bool> RejectUpdate([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute<bool>(() =>
            {
                T_PF_APPROVE modelApp = null;
                List<T_PF_APPROVE_DETAIL> listAppDetail = null;
                T_FM_NOTIFICATION_TASK taskFinish = null;
                string Msg = string.Empty;
                var record = GetEntity<T_HM_HAZARD_RECORD>(entity.DATA_ID, new string[] { "Nav_NoteTaker" });
                var recordUsers = GetEntities<T_HM_HAZARD_RECORD_USER>(t => t.RECORD_ID == entity.DATA_ID && t.USER_ID != record.NOTE_TAKER_ID, new BaseFilter(record.ORG_ID));
                bool ResultGetInfo = ApproveCallBackService.GetApproject(entity, ref modelApp, ref listAppDetail, ref taskFinish, ref Msg);
                if (!ResultGetInfo)
                    throw new Exception("驳回失败！");
                foreach (var user in recordUsers)
                {
                    user.DEAL_STATUS = 0;
                }
                record.STATUS = FOPreMeetingStatusEnum.审批拒绝;
                var sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("职业危害辨识记录-驳回", entity.DATA_ID, record.ORG_ID, (Guid)record.NOTE_TAKER_ID, record.Nav_NoteTaker.NAME, DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(1).ToShortDateString() + " 23:59:59"), 0, "HM100");
                UnifiedCommit(() =>
                {
                    if (record != null)
                        UpdateEntityNoCommit(record);   //保存主表
                    if (sendNotice != null)
                        AddEntityNoCommit(sendNotice);
                    if (recordUsers.Any())
                        BantchSaveEntityNoCommit(recordUsers);
                });

                return true;


            });
        }
        /// <summary>
        /// 归档
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("GetRejectContent")]
        public JsonActionResult<string> GetRejectContent([FromBody] T_HM_HAZARD_RECORD entity)
        {
            return SafeExecute<string>(() =>
            {
                var result = string.Empty;
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var newFilter = new BaseFilter(orgId);
                newFilter.SelectField = new List<string> { "Nav_ApproveDetails" };
                var approveInfo = this.GetEntities<T_PF_APPROVE>(t => t.DATA_ID == entity.ID, newFilter).OrderByDescending(m => m.CREATE_TIME).FirstOrDefault();
                if (approveInfo != null && approveInfo.Nav_ApproveDetails.Any())
                {
                    var detail = approveInfo.Nav_ApproveDetails.FirstOrDefault(t => t.NODE_APPROVE_STATUS == 20);
                    if (detail != null)
                    {
                        var userInfo = this.GetEntity<T_FM_USER>(t => t.ID == detail.APPROVE_USER_ID);
                        result = userInfo?.NAME + "驳回，内容：" + detail.CONTEXT;
                    }
                }
                return result;
            });
        }
    }
}
