using Microsoft.AspNetCore.SignalR;
using OASystem.API.OAMethodLib.Hub.HubClients;
using OASystem.API.OAMethodLib.Hub.Hubs;
using OASystem.API.OAMethodLib.SignalR.Hubs;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.Entities.PersonnelModule;
using OASystem.Infrastructure.Repositories.PersonnelModule;
using ILogger = Microsoft.Extensions.Logging.ILogger;

namespace OASystem.API.OAMethodLib.Quartz.Business
{
    public static class TaskNotification
    {

        private readonly static ILogger _logger;
        private readonly static TaskAllocationRepository _taskAllocationRep = AutofacIocManager.Instance.GetService<TaskAllocationRepository>();
        private readonly static IHubContext<ChatHub, IChatClient> _hubContext = AutofacIocManager.Instance.GetService<IHubContext<ChatHub, IChatClient>>();

        /// <summary>
        /// 任务通知
        /// </summary>
        public static async void PostTaskMessageNotification() 
        {
            //_logger.LogInformation("调用任务消息推送 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "【在线人数】：" + JsonConvert.SerializeObject(UserStore.OnlineUser));

            //在此处编写任务业务代码
            #region 消息处理

            var data =  _taskAllocationRep._sqlSugar
                                         .Queryable<Pm_TaskAllocation>()
                                         .Where(it => it.IsDel == 0 &&
                                                      !string.IsNullOrEmpty(it.PredictEndTime) &&
                                                      Convert.ToDateTime(it.PredictEndTime).ToString("yyyy-MM-dd").Equals(DateTime.Now.ToString("yyyy-MM-dd"))
                                               )
                                         .ToList();
            if (data.Count > 0)
            {
                //处理要任务提醒的员工
                List<int> primaryIds = new List<int>();
                primaryIds = data.Select(it => it.Id).ToList();
                var subData = _taskAllocationRep._sqlSugar
                                                .Queryable<Pm_TaskRelevanceUser>()
                                                .Where(it => it.IsDel == 0 &&
                                                             primaryIds.Contains(it.TAId) &&
                                                             (int)it.TaskStatus <= (int)TaskEnum.UnderWay
                                                      )
                                                .ToList();

                var depDatas = _taskAllocationRep._sqlSugar.Queryable<Sys_Department>().Where(it => it.IsDel == 0).ToList();
                var groupDatas = _taskAllocationRep._sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).ToList();
                var userDatas = _taskAllocationRep._sqlSugar.Queryable<Sys_Users>().Where(it => it.IsDel == 0).ToList();


                List<int> userIds = new List<int>();

                _taskAllocationRep._sqlSugar.BeginTran();
                foreach (var item in data)
                {
                    string depName = string.Empty;
                    string groupName = string.Empty;
                    var depData = depDatas.Where(it => it.Id == item.DepId).FirstOrDefault();
                    if (depData != null) { depName = depData.DepName; }
                    if (item.DiId == -1) { groupName = "其他"; }
                    else
                    {
                        var groupData = groupDatas.Where(it => it.Id == item.DiId).FirstOrDefault();
                        if (groupData != null) { groupName = groupData.TeamName; }
                    }

                    var subData1 = subData.Where(it => it.TAId == item.Id).ToList();

                    foreach (var subItem in subData1)
                    {
                        string realityStartTime = string.Empty;
                        string userName = string.Empty;
                        if (!string.IsNullOrEmpty(subItem.BeginTime))
                        {
                            realityStartTime = subItem.BeginTime;
                        }
                        else
                        {
                            if (subItem.TaskStatus == TaskerEnum.NotStarted) realityStartTime = "未开始";
                            else if (subItem.TaskStatus == TaskerEnum.HaveKnown) realityStartTime = "已知晓";
                        }

                        var userData = userDatas.Where(it => it.Id == subItem.UserId).FirstOrDefault();
                        if (userData != null) { userName = userData.CnName; }
                        string msgContent = string.Format(@$"归属团组：{groupName}<br/>
                                                            任务参与者：{userName}");
                        Sys_Message _Message = new Sys_Message()
                        {
                            Type = MessageTypeEnum.TaskProgressUpdate,
                            Title = item.TaskName,
                            IssuerId = 4, //管理员
                            Content = msgContent,
                            ReleaseTime = DateTime.Now,
                            CreateUserId = 4,
                            CreateTime = DateTime.Now,
                            DeleteTime = "1990-01-01 00:00:00.000",
                            DiId = item.DiId,
                        };
                        var msgAddId = _taskAllocationRep._sqlSugar.Insertable(_Message).ExecuteReturnIdentity();
                        if (msgAddId < 0)
                        {
                            _taskAllocationRep._sqlSugar.RollbackTran();
                            _logger.LogError("任务通知消息推送失败!");
                            return;
                        }

                        Sys_MessageReadAuth _MessageReadAuth = new Sys_MessageReadAuth()
                        {
                            MsgId = msgAddId,
                            ReadableUId = subItem.UserId,
                            IsRead = 0,
                            ReadTime = Convert.ToDateTime("1990-01-01 00:00:00.000"),
                            CreateUserId = 4,
                            CreateTime = DateTime.Now,
                            DeleteTime = "1990-01-01 00:00:00.000"
                        };

                        var msgAuthAddId = _taskAllocationRep._sqlSugar.Insertable(_MessageReadAuth).ExecuteReturnIdentity();
                        if (msgAuthAddId < 0)
                        {
                            _taskAllocationRep._sqlSugar.RollbackTran();
                            _logger.LogError("任务通知消息推送失败!");
                            return;
                        }
                        userIds.Add(subItem.UserId);
                    }
                }
                _taskAllocationRep._sqlSugar.CommitTran();
                //推送消息
               await _hubContext.Clients.Clients(UserStore.OnlineUser.Where(it => userIds.Contains(it.UserId)).Select(it => it.ConnectionId).ToList()).ReceiveMessage("您有新的任务相关消息");

                _logger.LogInformation("任务消息推送成功 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "【在线人数】：" + JsonConvert.SerializeObject(UserStore.OnlineUser));
            }
            #endregion
        }
    }
}
