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.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Api;
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/HMEvaluationPlan")]
    public partial class EvaluationPlanController : AuthorizeApiController<T_HM_EVALUATION_PLAN>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }

        public EvaluationPlanController(IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IFMDepartmentService departmentService)
        {
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            DepartmentService = departmentService;
        }
        /// <summary>
        /// 新增保存
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_HM_EVALUATION_PLAN entity)
        {
            return SafeExecute<bool>(() =>
            {
                var Nav_Details = entity.Nav_Details;
                var files = entity.Nav_Files;
                entity.Nav_Details = null;
                entity.Nav_Files = null;
                entity.RELEASE_USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.INITIATING_DEPARTMENT == null)
                {
                    var user = GetEntity<T_FM_USER>(t => t.ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID);
                    if (user != null)
                        entity.INITIATING_DEPARTMENT = user.DEPARTMENT_ID;
                }
                T_FM_NOTIFICATION_TASK notice = null;
                T_FM_NOTIFICATION_TASK finishNotice = null;
                List<T_HM_EVALUATION_DETAIL_AREA> areas = new List<T_HM_EVALUATION_DETAIL_AREA>();
                List<T_HM_EVALUATION_DETAIL_IDENTIFYING> identifyings = new List<T_HM_EVALUATION_DETAIL_IDENTIFYING>();

                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (Nav_Details.Count() == 0)
                    {
                        throw new Exception("请填写子表内容");
                    }
                    Nav_Details.Where(t => t.IS_DELETED == false).ForEach(detail =>
                    {
                        if (detail.START_TIME == null || detail.START_TIME == null)
                            throw new Exception("请填写开始时间和结束时间");
                        if (detail.START_TIME > detail.END_TIME)
                            throw new Exception("开始时间不能大于结束时间");
                        if (detail.Nav_Areas == null)
                        {
                            throw new Exception("辨识区域不能为空");
                        }
                    });
                    if (files == null || files.Count <= 0)
                    {
                        throw new Exception("附件未上传，无法发送");
                    }
                    if (entity.DEPUTY_GROUP_LEADER_ID == null || entity.GROUP_LEADER_ID == null)
                    {
                        throw new Exception("组长或副组长未填写");
                    }
                    entity.AUDIT_OPINION = "";
                    entity.DEPUTY_GROUP_LEADER_OPINION = HMOpinionEnmu.未选择;
                    entity.GROUP_LEADER_OPINION = HMOpinionEnmu.未选择;
                    var sendUser = entity.DEPUTY_GROUP_LEADER_ID;
                    if (entity.DEPUTY_GROUP_LEADER_ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID)
                    {
                        sendUser = entity.GROUP_LEADER_ID;
                        entity.DEPUTY_GROUP_LEADER_OPINION = HMOpinionEnmu.同意;
                    }
                    entity.STATUS = FOPreMeetingStatusEnum.审核中;
                    //发消息
                    notice = NotificationTaskService.InsertUserNoticeTaskModel(entity.EVALUATION_DATE.Year + "年度风险评价计划审核表", entity.ID, entity.ORG_ID, (Guid)sendUser, "", DateTime.Now,
                    DateTime.Parse(DateTime.Now.AddDays(1).ToShortDateString() + " 23:59:59"), (int)FMNoticeTypeEnum.消息, "HM042_SHOWPRINT");
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID,entity.ID);
                    }
                }
                Nav_Details.ForEach(detail =>
                {
                    if (detail.Nav_Areas != null)
                    {
                        areas.AddRange(detail.Nav_Areas);
                        detail.Nav_Areas = null;
                    }
                    if (detail.Nav_Identifyings != null)
                    {
                        identifyings.AddRange(detail.Nav_Identifyings);
                        detail.Nav_Identifyings = null;
                    }
                });
                UnifiedCommit(() =>
                {
                    if (areas.Any())
                        BantchSaveEntityNoCommit(areas);    //保存孙表
                    if (identifyings.Any())
                        BantchSaveEntityNoCommit(identifyings);    //保存孙表
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //保存主表
                    if (Nav_Details.Any())
                        BantchSaveEntityNoCommit(Nav_Details);    //保存子表
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);    //保存子表
                    if (notice != null)
                        AddEntityNoCommit(notice);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
                });
                return true;
            });
        }

        /// <summary>
        /// 获取组长
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEvaluationPlan")]
        public JsonActionResult<bool> GetEvaluationPlan([FromBody] T_HM_EVALUATION_PLAN entity)
        {
            return SafeExecute<bool>(() =>
            {
                var model = GetEntity<T_HM_EVALUATION_PLAN>(entity.ID.ToString());
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var deputy = model.DEPUTY_GROUP_LEADER_ID == userId && (model.DEPUTY_GROUP_LEADER_OPINION == 0 || model.DEPUTY_GROUP_LEADER_OPINION == null);
                var leader = model.GROUP_LEADER_ID == userId && (model.GROUP_LEADER_OPINION == 0 || model.GROUP_LEADER_OPINION == null);

                if (deputy || leader)  //该用户在该记录中是否参与且未同意则显示同意按钮
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
        }
        /// <summary>
        /// 获取个人的班组前会议活动
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetUserDealStatus")]
        public JsonActionResult<bool> GetUserDealStatus([FromBody] T_HM_EVALUATION_PLAN entity)
        {
            return SafeExecute<bool>(() =>
            {
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var count = GetCount<T_HM_EVALUATION_DETAIL>(t => t.PLAN_ID == entity.ID && t.CHARGE_USER_ID == userID && t.DEAL_STATUS == 0, new BaseFilter(APT.Infrastructure.Api.AppContext.CurrentSession.OrgId));
                if (count > 0)  //该用户在该记录中是否参与且未同意则显示同意按钮
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
        }
        /// <summary>
        /// 同意
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("ChargeUserAgree")]
        public JsonActionResult<bool> ChargeUserAgree([FromBody] T_HM_EVALUATION_PLAN entity)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var curruUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.CHECK_STATUS == 1)
                {
                    T_HM_EVALUATION_PLAN model = GetEntity<T_HM_EVALUATION_PLAN>(entity.ID.ToString());
                    if (model.GROUP_LEADER_ID == curruUserId)
                        model.GROUP_LEADER_OPINION = HMOpinionEnmu.同意;
                    if (model.DEPUTY_GROUP_LEADER_ID == curruUserId)
                        model.DEPUTY_GROUP_LEADER_OPINION = HMOpinionEnmu.同意;
                    if (model.GROUP_LEADER_OPINION == HMOpinionEnmu.同意)
                    {
                        //var companycode=GetEntity<T_FM_BASE_CONFIG>(t=>t.IS_DELETED==false);
                        //if(companycode.NAME.Equals("XLK"))
                        //{
                        var detailUsers = GetEntities<T_HM_EVALUATION_DETAIL>(t => t.PLAN_ID == entity.ID, new BaseFilter(orgId));
                        foreach (var user in detailUsers)
                        {
                            user.DEAL_STATUS = (int)FOUserShiftStatusEnum.已处理;
                            user.MODIFY_TIME = DateTime.Now;
                        }
                        model.STATUS = FOPreMeetingStatusEnum.审核中;
                        model.APPROVECODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                        MFlowPermitService.InsertApprove(model.APPROVECODE, "HM043", "", entity.ID, "HM042_SHOWPRINT", entity.TaskID, true, () =>
                        {
                            UpdateEntityNoCommit(model, "STATUS");
                            BantchUpdateEntityNoCommit(detailUsers, "DEAL_STATUS", "MODIFY_TIME");
                        });
                        return true;
                        //}
                        //var noticeTitles = new List<string>();
                        //var noticeUserIds = new List<Guid>();
                        //var noticeUserNames = new List<string>();
                        //var noticeDataIds = new List<Guid>();
                        //model.STATUS = FOPreMeetingStatusEnum.签到中;
                        //model.MODIFY_TIME = DateTime.Now;
                        //BaseFilter baseFilter = new BaseFilter(orgId);
                        //baseFilter.Include = new string[] { "Nav_ChargeUser" };
                        //var users = GetEntities<T_HM_EVALUATION_DETAIL>(t => t.PLAN_ID == entity.ID, baseFilter).Select(t=>t.CHARGE_USER_ID).Distinct();
                        //foreach (var item in users)
                        //{
                        //    noticeTitles.Add("年度风险评价计划审核表-待确认");
                        //    noticeDataIds.Add(entity.ID);
                        //    noticeUserIds.Add((Guid)item);
                        //    noticeUserNames.Add("");
                        //}
                        //NotificationTaskService.SendAndFinishNotificationTask(noticeTitles, noticeDataIds, orgId, noticeUserIds, noticeUserNames, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "HM042_SHOWPRINT", entity.TaskID, () =>
                        //{
                        //    UpdateEntityNoCommit(model, "STATUS", "GROUP_LEADER_OPINION", "MODIFY_TIME");
                        //});
                    }
                    else
                    {
                        NotificationTaskService.SendAndFinishNotificationTask(model.EVALUATION_DATE.Year + "年度风险评价计划审核表", entity.ID, orgId, (Guid)model.GROUP_LEADER_ID, "", DateTime.Now,
                        DateTime.Parse(DateTime.Now.AddDays(1).ToShortDateString() + " 23:59:59"), (int)FMNoticeTypeEnum.消息, "HM042_SHOWPRINT", entity.TaskID, () =>
                        {
                            UpdateEntityNoCommit(model, "STATUS", "DEPUTY_GROUP_LEADER_OPINION");
                        });
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(entity.AUDIT_OPINION))
                    {
                        throw new Exception("驳回时,请填写审核意见!");
                    }
                    else
                    {
                        T_HM_EVALUATION_PLAN model = GetEntity<T_HM_EVALUATION_PLAN>(entity.ID.ToString(), "Nav_ReleaseUser");
                        if (model.DEPUTY_GROUP_LEADER_ID == curruUserId)
                        {
                            model.DEPUTY_GROUP_LEADER_OPINION = HMOpinionEnmu.不同意;
                        }
                        else if (model.GROUP_LEADER_ID == curruUserId)
                        {
                            model.GROUP_LEADER_OPINION = HMOpinionEnmu.不同意;
                        }
                        model.AUDIT_OPINION = entity.AUDIT_OPINION;
                        model.STATUS = FOPreMeetingStatusEnum.审批拒绝;
                        NotificationTaskService.SendAndFinishNotificationTask(model.EVALUATION_DATE.Year + "年度风险评价计划-待修改", entity.ID, orgId, (Guid)model.RELEASE_USER_ID, model.Nav_ReleaseUser.NAME, DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(1).ToShortDateString() + " 23:59:59"), 0, "HM043", entity.TaskID, () =>
                         {
                             if (model != null)
                                 this.UpdateEntityNoCommit(model, "DEPUTY_GROUP_LEADER_OPINION", "GROUP_LEADER_OPINION", "AUDIT_OPINION", "STATUS");
                         });
                    }
                }

                return true;
            });
        }
        /// <summary>
        /// 签到
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("UserSignin")]
        public JsonActionResult<bool> UserSignin([FromBody] T_HM_EVALUATION_PLAN entity)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var users = GetEntities<T_HM_EVALUATION_DETAIL>(t => t.PLAN_ID == entity.ID, new BaseFilter(orgId));
                var signUsers = users.Where(t => t.CHARGE_USER_ID == userID);
                foreach (var user in signUsers)
                {
                    user.DEAL_STATUS = (int)FOUserShiftStatusEnum.已处理;
                    user.MODIFY_TIME = DateTime.Now;
                }

                var todoCount = users.Count(t => t.DEAL_STATUS == 0);

                if (todoCount == 0)
                {
                    T_HM_EVALUATION_PLAN model = GetEntity<T_HM_EVALUATION_PLAN>(entity.ID.ToString());
                    model.STATUS = FOPreMeetingStatusEnum.审核中;
                    model.APPROVECODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    MFlowPermitService.InsertApprove(model.APPROVECODE, "HM043", "", entity.ID, "HM042_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        UpdateEntityNoCommit(model, "STATUS");
                        BantchUpdateEntityNoCommit(users, "DEAL_STATUS", "MODIFY_TIME");
                    });
                }
                else
                {
                    if (users != null)
                    {
                        NotificationTaskService.NotificationTaskFinish(entity.TaskID, () =>
                        {
                            BantchUpdateEntityNoCommit(users, "DEAL_STATUS", "MODIFY_TIME");
                        });
                    }
                }

                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/HMEvaluationPlan/PersonalApprove", id);
            });
        }
    }
}
