

using System;
using System.Collections.Generic;
using System.Linq;
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.BaseData.Services.DomainServices;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.PF;
using APT.MS.Domain.Entities.SE;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using MySqlX.XDevAPI.Common;
using NPOI.SS.Formula.Functions;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace APT.SC.WebApi.Controllers.Api.SE
{
    [Route("api/SE/SEYearTrainPlan")]
    public class SEYearTrainPlanController : AuthorizeApiController<T_SE_YEAR_TRAIN_PLAN>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }


        public SEYearTrainPlanController(IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IFMDepartmentService departmentService)
        {
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            DepartmentService = departmentService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SE_YEAR_TRAIN_PLAN entity)
        {
            return SafeExecute(() =>
            {
                if (entity.STATUS != PFStandardStatus.Draft && entity.STATUS != PFStandardStatus.Sign)
                {
                    throw new Exception("当前状态数据不可编辑");
                }
                var sendDepartMent = entity.Nav_YearTrainPlanDepartment;
                var Nav_YearTrainPlanDetail = entity.Nav_YearTrainPlanDetail;
                List<T_SE_YEAR_TRAIN_PLAN_CONTENT> planContents = new List<T_SE_YEAR_TRAIN_PLAN_CONTENT>();

                var files = entity.Nav_Files;
                T_FM_NOTIFICATION_TASK finishTask = null;
                var isApprove = false;
                List<T_SE_TRAIN_NOTIFY> trainNotifys = new List<T_SE_TRAIN_NOTIFY>();
                List<T_SE_TRAIN_NOTIFY_CONTENT_REL> trainNotifyContents = new List<T_SE_TRAIN_NOTIFY_CONTENT_REL>();
                List<T_FM_NOTIFICATION_TASK> sendNotices = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {

                    var planNoticeData = Nav_YearTrainPlanDetail.Where(t => t.MOON == DateTime.Now.Month && t.SEND == 0);
                    if (planNoticeData.Any())
                    {
                        var allSendUserIds = new List<Guid>();
                        var allSendUserNames = new List<string>();
                        var allSendUserTitles = new List<string>();
                        var allSendDataIds = new List<Guid>();
                        var alltoDayNotifyTitles = new List<string>();
                        foreach (var plan in planNoticeData)
                        {
                            plan.SEND = 1;
                            T_SE_TRAIN_NOTIFY trainNotify = new T_SE_TRAIN_NOTIFY
                            {
                                ID = Guid.NewGuid(),
                                LAUNCH_TIME = DateTime.Now,
                                LAUNCH_DEPARTMENT_ID = plan.RESPONSIBILITY_DEP_ID,
                                LAUNCH_USER_ID = plan.RESPONSIBILITY_USER_ID,
                                RECORD_USER_ID = plan.RESPONSIBILITY_USER_ID,
                                NAME = plan.NAME,
                                TRAIN_TYPE = plan.TYPE_ID,
                                LEVEL = plan.LEVEL,
                                TRAIN_ADDR = plan.ADDRESS,
                                TRAIN_TEACHER = plan.TEACHER,
                                TRAIN_MODEL = plan.TRAIN_MODEL,
                                CHECK_TYPE_ID = plan.CHECK_TYPE_ID.Value,
                                STATUS = SETrainNotifyStatus.草稿,
                                ORG_ID = entity.ORG_ID,
                                CODE = DateTime.Now.ToString("yyyyMMddHHmmss")
                            };
                            plan.Nav_YearTrainPlanContent.ForEach(content =>
                            {
                                T_SE_TRAIN_NOTIFY_CONTENT_REL trainNotifyContent = new T_SE_TRAIN_NOTIFY_CONTENT_REL
                                {
                                    ID = Guid.NewGuid(),
                                    ORG_ID = entity.ORG_ID,
                                    POINT_ID = (Guid)content.CONTENT_ID,
                                    NOTIFY_ID = trainNotify.ID
                                };
                                trainNotifyContents.Add(trainNotifyContent);
                            });
                            allSendUserTitles.Add("制定培训通知-" + plan.NAME);
                            allSendDataIds.Add(trainNotify.ID);
                            allSendUserIds.Add((Guid)plan.RESPONSIBILITY_USER_ID);
                            allSendUserNames.Add("");
                            trainNotifys.Add(trainNotify);
                        }
                        sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, entity.ORG_ID, allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1), (int)FMFormTypeEnum.计划任务通知, "SE014");
                    }
                    isApprove = true;
                    entity.STATUS = PFStandardStatus.Approving;
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishTask = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "SE011_SHOWPRINT");
                    }
                }
                sendDepartMent.ForEach(dep =>
                {
                    dep.Nav_Department = null;
                });
                Nav_YearTrainPlanDetail.ForEach(detail =>
                {
                    if (detail.Nav_YearTrainPlanContent != null)
                    {
                        planContents.AddRange(detail.Nav_YearTrainPlanContent);
                        detail.Nav_YearTrainPlanContent = null;
                    }
                });
                entity.Nav_YearTrainPlanDepartment = null;
                entity.Nav_YearTrainPlanDetail = null;
                entity.Nav_Files = null;
                MFlowPermitService.InsertApprove(DateTime.Now.ToString("yyyyMMddHHmmss"), "SE012", "", entity.ID, "SE011_SHOWPRINT", entity.TaskID, isApprove, () =>
                {
                    UpdateEntityNoCommit(entity);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (finishTask != null)
                        UpdateEntityNoCommit(finishTask);
                    if (sendDepartMent != null && sendDepartMent.Any())
                        BantchSaveEntityNoCommit(sendDepartMent);
                    if (planContents != null && planContents.Any())
                        BantchSaveEntityNoCommit(planContents);
                    if (Nav_YearTrainPlanDetail != null && Nav_YearTrainPlanDetail.Any())
                        BantchSaveEntityNoCommit(Nav_YearTrainPlanDetail);
                    if (trainNotifys != null && trainNotifys.Any())
                        BantchAddEntityNoCommit(trainNotifys);
                    if (sendNotices != null)
                        BantchAddEntityNoCommit(sendNotices);
                    if (trainNotifyContents != null && trainNotifyContents.Any())
                        BantchAddEntityNoCommit(trainNotifyContents);
                }, null);
                return true;
            });
        }
        /// <summary>
        /// 隐患上报 审核通过 给每个通知负责人发送通知
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("yearTrainPlanAgree")]
        public JsonActionResult<bool> yearTrainPlanAgree(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("SE/SEYearTrainPlan/yearTrainPlanAgree", id);
            });
        }
        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("Get")]
        public JsonActionResult<T_SE_YEAR_TRAIN_PLAN> Get([FromBody] KeywordFilter filter)
        {
            var trainPlan = WitEntity(null, filter);
            BaseFilter basefilter = new BaseFilter(APT.Infrastructure.Api.AppContext.CurrentSession.OrgId);
            basefilter.Include = new string[] { "Nav_TrainTypeEnum", "Nav_YearTrainPlanContent.Nav_TestEnumPoint", "Nav_TrainCheckTypeEnum", "Nav_ResponsibilityDep", "Nav_ResponsibilityUser" };
            List<T_SE_YEAR_TRAIN_PLAN_DETAIL> details = null;
            var currDep = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value;
            var AHDepartment = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人").DEPARTMENT_ID;
            if (trainPlan.Data.STATUS > PFStandardStatus.Draft&& currDep != AHDepartment)
            {
                var deps = new List<Guid>();
                DepartmentService.GetDepartmentIds(filter.GetOrgId(), new List<Guid>() { Guid.Parse(APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentId) }, ref deps);
                deps.Add(Guid.Parse(APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentId));
                details = GetEntities<T_SE_YEAR_TRAIN_PLAN_DETAIL>(t => deps.Contains((Guid)t.RESPONSIBILITY_DEP_ID), basefilter).ToList();
            }
            else
            {
                details = GetEntities<T_SE_YEAR_TRAIN_PLAN_DETAIL>(t => t.IS_DELETED == false, basefilter).ToList();
            }
            trainPlan.Data.Nav_YearTrainPlanDetail = details;
            return trainPlan;
        }
    }
}
