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 InfluxData.Net.InfluxDb.Models.Responses;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.HM.WebApi.Controllers.Api
{
    [Route("api/HM/HMRiskRecord")]
    public partial class RiskRecordController : AuthorizeApiController<T_HM_RISK_RECORD>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }

        IPFCodeRuleService CodeRuleService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        /// <summary>
        /// 作业任务分析
        /// </summary>
        public RiskRecordController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService)
        {
            NotificationTaskService = notificationTaskService;
            CodeRuleService = codeRuleService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_HM_RISK_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var details = entity.Nav_Details;
                var allAreas = details.Select(t => t.AREA_ID);
                var users = GetEntities<T_HM_RISK_RECORD_USER>(t => t.RECORD_ID == entity.ID && allAreas.Contains(t.AREA_ID), new BaseFilter(entity.ORG_ID));
                var identifyings = entity.Nav_Identifyings;
                var files = entity.Nav_Files;
                entity.Nav_Users = null;
                entity.Nav_Identifyings = null;
                entity.Nav_Files = null;
                entity.Nav_Details = null;
                List<T_HM_RISK_RECORD_DETAIL_WORKDUTY> workdutys = new List<T_HM_RISK_RECORD_DETAIL_WORKDUTY>();
                List<T_HM_RISK_RECORD_DETAIL_EQUIPMENT> equipments = new List<T_HM_RISK_RECORD_DETAIL_EQUIPMENT>();
                List<T_HM_RISK_RECORD_DETAIL_FACILITIES> facilities = new List<T_HM_RISK_RECORD_DETAIL_FACILITIES>();
                details.ForEach(detail =>
                {
                    if (detail.Nav_EvaluateRiskRecordWorkduty != null)
                    {
                        workdutys.AddRange(detail.Nav_EvaluateRiskRecordWorkduty);
                        detail.Nav_EvaluateRiskRecordWorkduty = null;
                    }
                    if (detail.Nav_EvaluateRiskRecordEquipment != null)
                    {
                        equipments.AddRange(detail.Nav_EvaluateRiskRecordEquipment);
                        detail.Nav_EvaluateRiskRecordEquipment = null;
                    }
                    if (detail.Nav_EvaluateRiskRecordFacilities != null)
                    {
                        facilities.AddRange(detail.Nav_EvaluateRiskRecordFacilities);
                        detail.Nav_EvaluateRiskRecordFacilities = null;
                    }
                    if(detail.LIABLE_USER_ID == null)
                    {
                        var liableUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == detail.DEPARTMENT_LIABLE_ID && t.APPROVE_ROLE_ID == detail.POST_LIABLE_ID);
                        if(liableUser != null)
                        {
                            detail.LIABLE_USER_ID=liableUser.ID;
                        }
                        else
                        {
                            throw new Exception("未能找到对应责任人！");
                        }
                    }
                });
                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.DistinctBy(t=>t.USER_ID).Where(t => t.DEAL_STATUS == FOUserShiftStatusEnum.待处理);
                    if (userDeal.Count() > 0)
                    {
                        var allusers = GetEntities<T_FM_USER>(null, new BaseFilter(entity.ORG_ID));
                        //var allareas = GetEntities<T_HM_RISK_AREA>(null, new BaseFilter(entity.ORG_ID));
                        foreach (var user in userDeal)
                        {
                            if (user.DEAL_STATUS != FOUserShiftStatusEnum.已处理)
                            {
                                var userName = allusers.Where(t => t.ID == user.USER_ID).FirstOrDefault();
                                //var userArea = allareas.Where(t => t.ID == user.AREA_ID).FirstOrDefault();
                                noticeUserIds.Add(user.USER_ID);
                                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, "HM063_SHOWPRINT");
                        finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID,entity.ID, "HM063_SHOWPRINT");
                    }
                    else
                    {
                        entity.STATUS = FOPreMeetingStatusEnum.审核中;
                        entity.APPROVECODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                        MFlowPermitService.InsertApprove(entity.APPROVECODE, "HM064", "", entity.ID, "HM063_SHOWPRINT", entity.TaskID, true, () =>
                        {
                        }, null, entity.NOTE_TAKER_ID,null,null,null, "HM063_SHOWPRINT");
                    }
                }
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //保存主表
                    if (users != null && users.Any())
                        BantchSaveEntityNoCommit(users);    //保存子表
                    if (identifyings != null && identifyings.Any())
                        BantchSaveEntityNoCommit(identifyings);     //保存子表
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);        //保存子表
                    if (details != null && details.Any())
                        BantchSaveEntityNoCommit(details);      //保存子表
                    if (workdutys != null && workdutys.Any())
                        BantchSaveEntityNoCommit(workdutys);      //保存孙表
                    if (equipments != null && equipments.Any())
                        BantchSaveEntityNoCommit(equipments);      //保存孙表
                    if (facilities != null && facilities.Any())
                        BantchSaveEntityNoCommit(facilities);      //保存孙表
                    if (sendNotices != null && sendNotices.Any())
                        BantchSaveEntityNoCommit(sendNotices);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                });
                return true;
            });
        }

        /// <summary>
        /// 获取个人的风险记录
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetRiskRecord")]
        public JsonActionResult<bool> GetRiskRecord([FromBody] T_HM_RISK_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var model = GetEntity<T_HM_RISK_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_RISK_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="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullGet")]
        public JsonActionResult<T_HM_RISK_RECORD> FullGet([FromBody] KeywordFilter filter)
        {
            if (filter.Parameter1 == null)
            {
                filter.Include = new string[] { "Nav_Request", "Nav_InitiatingDepartment",
                "Nav_Identifyings.Nav_Identifying", "Nav_Files.Nav_ImgFile.Nav_File","Nav_NoteTaker"
                };
            }
            var result = WitEntity(null, filter);
            var ID = new Guid(filter.FilterGroup.Rules.ToList()[0].Value.ToString());
            var filter1 = new BaseFilter(filter.GetOrgId());
            filter1.Include = new string[] { "Nav_EvaluateRiskRecordEquipment.Nav_Equipment", "Nav_EvaluateRiskRecordWorkduty.Nav_Workduty", "Nav_Area", "Nav_Identifying", "Nav_Type", "Nav_OperationStep", "Nav_LiableUser", "Nav_DepartmentLiable", "Nav_PostLiable" };
            var detailData = GetEntities<T_HM_RISK_RECORD_DETAIL>(t => t.RECORD_ID == ID, filter1);
            var record = GetEntity<T_HM_RISK_RECORD>(ID);
            var filter2 = new BaseFilter(filter.GetOrgId());
            filter2.Include = new string[] { "Nav_Area","Nav_Users.Nav_User" };
            var riskUsers = GetEntities<T_HM_RISK_TASK_DETAIL>(t => t.TASK_ID == record.TASK_ID && t.RECORD_USER_ID == record.NOTE_TAKER_ID,filter2);
            List<T_HM_RISK_RECORD_USER> Nav_Users = new List<T_HM_RISK_RECORD_USER>();
            result.Data.Nav_Users= Nav_Users;
            foreach ( var riskUser in riskUsers)
            {
                var userNames = "";
                foreach(var user in riskUser.Nav_Users)
                {
                    userNames += user.Nav_User.NAME+" ";
                }
                T_HM_RISK_AREA area = new T_HM_RISK_AREA();
                T_FM_USER fmuser = new T_FM_USER();
                T_HM_RISK_RECORD_USER item =new T_HM_RISK_RECORD_USER()
                {
                    Nav_Area = area,
                    Nav_User = fmuser,
                };
                item.Nav_Area.NAME = riskUser.Nav_Area.NAME;
                item.Nav_User.NAME = userNames;
                result.Data.Nav_Users.Add(item);
            }
            result.Data.Nav_Details = detailData.ToList();
            if (result.Data != null)
            {
                result.Data.Nav_Details = result.Data.Nav_Details.OrderBy(t => t.AREA_ID).ThenBy(n=>n.IDENTIFYING_ID).ThenBy(x=>x.TYPE_ID).ThenBy(c=>c.RISK_NAME).ToList();
            }
            return result;
        }
        /// <summary>
        /// 同意
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("PersonalAgree")]
        public JsonActionResult<bool> PersonalAgree([FromBody] T_HM_RISK_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var userAll = GetEntities<T_HM_RISK_RECORD_USER>(t => t.RECORD_ID == entity.ID, new BaseFilter(orgId));
                var users = userAll.Where(t => t.USER_ID == userId);
                foreach (var user in users)
                {
                    user.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                }
                var todoCount = userAll.Where(t => t.DEAL_STATUS == 0).Count();
                #region 判断是否全部人员同意
                if (todoCount == 0)
                {
                    var riskRecord = GetEntity<T_HM_RISK_RECORD>(entity.ID);
                    riskRecord.STATUS = FOPreMeetingStatusEnum.审核中;
                    MFlowPermitService.InsertApprove(DateTime.Now.ToString("yyyyMMddHHmmss"), "HM064", "", entity.ID, "HM063_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        UpdateEntityNoCommit(riskRecord, "STATUS");
                        if (users != null && users.Any())
                            BantchUpdateEntityNoCommit(users, "DEAL_STATUS");
                    }, null, userId);
                }
                else
                {
                    NotificationTaskService.NotificationTaskFinish(entity.TaskID, () =>
                    {
                        if (users != null && users.Any())
                            BantchUpdateEntityNoCommit(users, "DEAL_STATUS");
                    });
                }
                #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/HMRiskRecord/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_RISK_RECORD>(entity.DATA_ID, new string[] { "Nav_NoteTaker" });
                var recordUsers = GetEntities<T_HM_RISK_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.Now.AddHours(24), 0, "HM064");
                UnifiedCommit(() =>
                {
                    if (record != null)
                        UpdateEntityNoCommit(record);   //保存主表
                    if (sendNotice != null)
                        AddEntityNoCommit(sendNotice);
                    if (recordUsers.Any())
                        BantchSaveEntityNoCommit(recordUsers);
                });

                return true;


            });
        }
    }
}
