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.IServices.FM;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.SE;
using APT.MS.Domain.Enums;
using APT.Utility;
using log4net.Core;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using Renci.SshNet.Common;
using static APT.SC.WebApi.Controllers.Api.BI.BIController;

namespace APT.SC.WebApi.Controllers.Api.SE
{
    [Route("api/SE/SETrainNotify")]
    public class SETTrainNotifyController : AuthorizeApiController<T_SE_TRAIN_NOTIFY>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public SETTrainNotifyController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SE_TRAIN_NOTIFY entity)
        {
            return SafeExecute(() =>
            {
                if (entity == null)
                {
                    throw new Exception("请注意培训时长不能为小数");
                }
                if (entity.STATUS >= SETrainNotifyStatus.通知中)
                {
                    throw new Exception("通知发送，不可更改");
                }
                var Nav_TrainContentList = entity.Nav_TrainContentList;
                if (Nav_TrainContentList.Count()==0)
                {
                    throw new Exception("请选择培训内容");
                }
                var Nav_TrainUserList = entity.Nav_TrainUserList.Where(t => t.USER_ID != Guid.Empty);
                var Nav_Files = entity.Nav_Files;
                List<T_FM_NOTIFICATION_TASK> sendNoticeTask = null;
                T_FM_NOTIFICATION_TASK finishNoticeTask = null;


                foreach (var item in Nav_TrainContentList)
                {
                    item.Nav_Point = null;
                };
                if (entity.LAUNCH_TIME == null)
                {
                    entity.LAUNCH_TIME = DateTime.Now;
                }
                if (entity.CODE == null)
                {
                    entity.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                }
                if (entity.LAUNCH_USER_ID == null)
                {
                    entity.LAUNCH_USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                }
                if (entity.LAUNCH_DEPARTMENT_ID == null)
                {
                    entity.LAUNCH_DEPARTMENT_ID = GetEntity<T_FM_USER>(entity.LAUNCH_USER_ID.ToString()).DEPARTMENT_ID;
                }
                var noDeleteUsers = Nav_TrainUserList.Where(t => t.IS_DELETED == false);
                var hasDuplicates = noDeleteUsers.GroupBy(x => x.USER_ID).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
                if (hasDuplicates.Any())
                {
                    BaseFilter filter = new BaseFilter(entity.ORG_ID);
                    filter.SelectField = new string[] { "NAME" };
                    var duplicateName = string.Join(",", GetEntities<T_FM_USER>(t => hasDuplicates.Contains(t.ID), filter).Select(t => t.NAME));
                    throw new Exception("人员:" + duplicateName + " 重复!");
                }
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    entity.LAUNCH_TIME = DateTime.Now;
                    var transferUsersCount = Nav_TrainUserList.Count(t => t.IS_DELETED == false && t.TRANSFER_TRAINING == true);
                    if (entity.CREATE_NOTIFY_RECORD == false && transferUsersCount > 0)
                    {
                        throw new Exception("未触发培训记录不能转训!");
                    }
                    if (entity.CREATE_NOTIFY_RECORD && entity.RECORD_USER_ID == null)
                    {
                        throw new Exception("触发培训记录请选择记录人!");
                    }
                    if (entity.TRAIN_END_TIME <= entity.TRAIN_START_TIME)
                    {
                        throw new Exception("培训结束时间需大于培训开始时间");
                    }
                    if (Nav_TrainContentList == null)
                    {
                        throw new Exception("培训内容不可为空!");
                    }
                    if (Nav_TrainUserList == null || Nav_TrainUserList.Where(t => t.IS_DELETED == false).Count() == 0)
                    {
                        throw new Exception("培训人员不可为空!");
                    }
                    if (entity.HOURS == 0)
                    {
                        throw new Exception("培训时长不能为0!");
                    }
                    entity.STATUS = SETrainNotifyStatus.通知中;
                    //触发培训通知给所有培训人员
                    var allSendUserNames = new List<string>();

                    var sendUsers = Nav_TrainUserList.Where(t => t.IS_DELETED == false && t.USER_ID != entity.LAUNCH_USER_ID).Select(t => t.USER_ID).ToList();
                    var sendUserAll = Nav_TrainUserList.Where(t => t.IS_DELETED == false).Select(t => t.USER_ID).ToList();

                    BaseFilter userFilter = new BaseFilter(entity.ORG_ID);
                    userFilter.Include = new string[] { "Nav_Person.Nav_Post", "Nav_Department" };
                    var userNames = GetEntities<T_FM_USER>(t => sendUserAll.Contains(t.ID), userFilter);
                    foreach (var user in Nav_TrainUserList)
                    {
                        user.DEPARTMENT_NAME = userNames.FirstOrDefault(t => t.ID == user.USER_ID).Nav_Department.NAME;
                        user.POST_NAME = userNames.FirstOrDefault(t => t.ID == user.USER_ID).Nav_Person.Nav_Post.NAME;
                    }
                    foreach (var user in sendUsers)
                    {
                        allSendUserNames.Add(userNames.FirstOrDefault(t => t.ID == user).NAME);
                    }
                    //2023/04/23当前人自动签到
                    var currTrainUser = Nav_TrainUserList.FirstOrDefault(t => t.USER_ID == entity.LAUNCH_USER_ID);
                    if (currTrainUser != null)
                    {
                        currTrainUser.IS_LEAVE = SETrainYesNoEnum.参加;
                    }

                    sendNoticeTask = NotificationTaskService.InsertUserNoticeTaskModels("培训通知-" + entity.NAME + "-确认", entity.ID, entity.ORG_ID, sendUsers, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.消息, "SE013_SHOWPRINT");


                    if (entity.TaskID != Guid.Empty)
                    {
                        finishNoticeTask = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "SE013_SHOWPRINT");
                    }
                }
                entity.Nav_Files = null;
                entity.Nav_TrainUserList = null;
                entity.Nav_TrainContentList = null;
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (Nav_TrainContentList != null && Nav_TrainContentList.Any())
                        BantchSaveEntityNoCommit(Nav_TrainContentList);
                    if (Nav_TrainUserList != null && Nav_TrainUserList.Any())
                        BantchSaveEntityNoCommit(Nav_TrainUserList);
                    if (Nav_Files != null && Nav_Files.Any())
                        BantchSaveEntityNoCommit(Nav_Files);
                    if (sendNoticeTask != null && sendNoticeTask.Any())
                        BantchAddEntityNoCommit(sendNoticeTask);
                    if (finishNoticeTask != null)
                        UpdateEntityNoCommit(finishNoticeTask);

                });
                return true;
            });
        }

        /// 参加/请假
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("TrainPersonStatus")]
        public JsonActionResult<bool> AttendStatus([FromBody] T_SE_TRAIN_NOTIFY_PERSONS entity)
        {
            return SafeExecute(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                T_FM_NOTIFICATION_TASK finishTask = null;
                T_SE_TRAIN_NOTIFY model = null;
                var allUsers = GetEntities<T_SE_TRAIN_NOTIFY_PERSONS>(t => t.NOTIFY_ID == entity.NOTIFY_ID, new BaseFilter(orgId));
                var updateUsers = allUsers.Where(t => t.USER_ID == entity.USER_ID);
                foreach (var updateUser in updateUsers)
                {
                    updateUser.IS_LEAVE = entity.IS_LEAVE;
                    updateUser.LEAVE_REASON = entity.LEAVE_REASON;
                    updateUser.MODIFY_TIME = DateTime.Now;
                }
                finishTask = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                var todoCount = allUsers.Count(t => t.IS_LEAVE == SETrainYesNoEnum.未签到);
                if (todoCount == 0)
                {
                    model = GetEntity<T_SE_TRAIN_NOTIFY>(entity.NOTIFY_ID);
                    if (model.CREATE_NOTIFY_RECORD && model.STATUS != SETrainNotifyStatus.归档)
                    {
                        model.STATUS = SETrainNotifyStatus.签到完成;
                    }
                    else
                    {
                        model.STATUS = SETrainNotifyStatus.归档;
                    }
                    model.MODIFY_TIME = DateTime.Now;
                }

                UnifiedCommit(() =>
                {
                    if (updateUsers != null)
                        BantchUpdateEntityNoCommit(updateUsers, "IS_LEAVE", "LEAVE_REASON", "MODIFY_TIME");
                    if (model != null)
                        UpdateEntityNoCommit(model, "STATUS", "MODIFY_TIME");
                    if (finishTask != null)
                        UpdateEntityNoCommit(finishTask);
                });
                return true;
            });
        }
        /// 参加/请假
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("overTimeSign")]
        public JsonActionResult<bool> overTimeSign([FromBody] T_SE_TRAIN_NOTIFY_PERSONS entity)
        {
            return SafeExecute(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                T_FM_NOTIFICATION_TASK finishTask = null;
                var allUsers = GetEntities<T_SE_TRAIN_NOTIFY_PERSONS>(t => t.NOTIFY_ID == entity.NOTIFY_ID, new BaseFilter(orgId));
                var updateUsers = allUsers.Where(t => t.USER_ID == entity.USER_ID);
                foreach (var updateUser in updateUsers)
                {
                    updateUser.IS_LEAVE = SETrainYesNoEnum.参加;
                    updateUser.MODIFY_TIME = DateTime.Now;
                }
                finishTask = NotificationTaskService.GetTaskFinishModel(entity.TaskID);

                UnifiedCommit(() =>
                {
                    if (updateUsers != null)
                        BantchUpdateEntityNoCommit(updateUsers, "IS_LEAVE", "LEAVE_REASON", "MODIFY_TIME");
                    if (finishTask != null)
                        UpdateEntityNoCommit(finishTask);
                });
                return true;
            });
        }
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_SE_TRAIN_NOTIFY> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitOrderPaged(t => t.ORIGINAL_NOTIFY_ID != null, pageFilter);
        }
        public class notifyData
        {
            public T_SE_TRAIN_NOTIFY mainNotify { get; set; }

            public List<T_SE_TRAIN_RECORD> subRecords { get; set; }

        }
        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("Get")]
        public JsonActionResult<notifyData> Get([FromBody] KeywordFilter filter)
        {
            return SafeExecute<notifyData>(() =>
            {
                List<Guid> notifys = new List<Guid>();
                notifyData notifyDatas = new notifyData();
                notifyDatas.mainNotify = GetEntity<T_SE_TRAIN_NOTIFY>(filter.Parameter1, new string[] { "Nav_LaunchDepartment", "Nav_LaunchUser", "Nav_TrainType", "Nav_TrainCheckType", "Nav_TrainContentList", "Nav_TrainContentList.Nav_Point", "Nav_TrainUserList", "Nav_TrainUserList.Nav_User", "Nav_TrainUserList.Nav_User.Nav_Department", "Nav_TrainUserList.Nav_User.Nav_Person.Nav_Post", "Nav_Files.Nav_ImgFile.Nav_File" });
                var subnotifys = GetEntities<T_SE_TRAIN_NOTIFY>(t => t.ORIGINAL_NOTIFY_ID == Guid.Parse(filter.Parameter1), new BaseFilter(filter.GetOrgId()));
                notifys.Add(notifyDatas.mainNotify.ID);
                foreach (var item in subnotifys)
                {
                    notifys.Add(item.ID);
                }
                var recordFilter = new BaseFilter(filter.GetOrgId());
                recordFilter.Include = new string[] { "Nav_Notify.Nav_LaunchDepartment", "Nav_Users.Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File", "Nav_Papers", "Nav_Files" };
                var allRecords = GetEntities<T_SE_TRAIN_RECORD>(t => notifys.Contains(t.NOTIFY_ID), recordFilter).ToList();
                notifyDatas.subRecords = allRecords;
                return notifyDatas;
            });
        }
    }
}
