using OpenAuth.App.BaseApp.Base;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository;
using OpenAuth.App.Interface;
using SqlSugar;
using Microsoft.Extensions.Configuration;
using Infrastructure.Extensions;
using OpenAuth.App.ServiceApp.InsTaskHallManager.Response;
using Infrastructure;
using OpenAuth.App.BaseApp;
using Moq;

namespace OpenAuth.App.ServiceApp.InsTaskHallManager
{
    public class InsTaskHallApp : SqlSugarBaseApp<InsTask, SugarDbContext>
    {
        private readonly IConfiguration _configuration;
        private readonly ISqlSugarClient client;
        private ImMsgApp _immsgApp;
        public InsTaskHallApp(ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<InsTask> repository, IAuth auth, ISqlSugarClient sqlSugarClient,
            IConfiguration configuration, ImMsgApp immsgApp) : base(unitWork, repository, auth)
        {
            _configuration = configuration;
            this.client = sqlSugarClient;
            _immsgApp = immsgApp;
        }

        /// <summary>
        /// 任务区
        /// </summary>
        /// <returns></returns>
        public async Task<List<dynamic>> GetTaskList()
        {
            var query = await client.Queryable<InsTask>().Where(r => r.State!=2)
                .LeftJoin<InsAishp>((r, p) => r.ShpId == p.Id)
                .OrderByDescending(r=>r.CreateTime)
                .Select<dynamic>((r, p) => new
                {
                    r.Id,
                    r.TaskName,
                    r.State,
                    p.ShpCount,
                    CompleteCount = SqlFunc.Subqueryable<InsTaskgroup>().Where(a => a.TaskId == r.Id&&a.ReciveUserId!=null).Count() > 0 ? SqlFunc.Subqueryable<InsTaskgroup>().Where(a => a.TaskId == r.Id && a.ReciveUserId != null).Sum(r => (r.EndNum - r.BeginNum)+1) : 0
                }).ToListAsync();

            return query;
        }

        /// <summary>
        /// 完成任务
        /// </summary>
        /// <returns></returns>
        public async Task<List<InsTaskRes>> GetCompleteTaskList()
        {
            var query = await client.Queryable<InsTask>().Where(r => r.IsCompleted == true&&r.CompleteTime!=null)
                .Select(r => new
                {
                    id=r.Id,
                    datetime= r.CompleteTime.Value.Date
                })
                .MergeTable()
                .GroupBy(r=>r.datetime)
                .Select(r => new InsTaskRes
                {
                    count = SqlFunc.AggregateCount(r.id),
                    time= r.datetime
                })
                .MergeTable().OrderBy(r => r.time)
                .ToListAsync();

            return query;
        }

        /// <summary>
        /// 最佳牛马排行
        /// </summary>
        /// <param name="flag"></param>
        /// <returns></returns>
        public async Task<List<dynamic>> GetRankingList(string flag)
        {
            DateTime begindate = DateTime.Now;
            if (flag == "day")
            {
                DateTime today = DateTime.Now; // 获取今天的日期
                begindate= today.Date;
            }
            if (flag == "week")
            {
                DateTime today = DateTime.Today; // 获取今天的日期
                int diff = today.DayOfWeek - DayOfWeek.Monday;

                // 如果是星期天，DayOfWeek.Sunday 的值是 0，调整为 -6
                if (diff < 0)
                {
                    diff += 7;
                }
                begindate = today.AddDays(-diff);
            }
            if (flag == "month")
            {
                begindate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-01"));
            }
            var query = await client.Queryable<InsTaskgroup>()
                .Where(r => r.IsComplate == true && r.CompleteTime != null)               
                .WhereIF(!string.IsNullOrEmpty(flag), r=> r.CompleteTime>=begindate)
                .GroupBy(r => r.ReciveUserId)
                .Select(r => new 
                {
                    count = SqlFunc.AggregateCount(r.Id),
                    userid=r.ReciveUserId
                })
                .MergeTable()
                .LeftJoin<SysUser>((r, u) => r.userid == u.Id.ToString())
                .OrderByDescending((r, u) => r.count)
                .Select<dynamic>((r, u) => new
                {
                    r.count,
                    r.userid,
                    u.Name,
                    u.HeadIcon                
                })
                .ToListAsync();

            return query;
        }

        /// <summary>
        /// 在办任务
        /// </summary>
        /// <returns></returns>
        public async Task<List<dynamic>> GetTaskingList()
        {
            //查询分组内的用户
            List<string> userlist = new List<string>();
            var groupuser = client.Queryable<SysGroupuser>().ToList();
            if(groupuser.Count > 0)
            {
                userlist=groupuser.Select(r=>r.UserId).Distinct().ToList();
            }
            //根据在办任务数聚合
            var query =  client.Queryable<InsTaskgroup>()
                .Where(r => r.IsComplate == false)
                .GroupBy(r => r.ReciveUserId)
                .Select(r => new
                {
                    count = SqlFunc.AggregateCount(r.Id),
                    userid = r.ReciveUserId
                })
                .MergeTable();
            //关联用户表查询数据
            var list=await client.Queryable<SysUser>()
                .Where(u=>userlist.Contains(u.Id.ToString()))
                .LeftJoin(query ,(u,r) => r.userid == u.Id.ToString())
                .OrderByDescending((u, r) =>SqlFunc.IIF(r.count == null, 0, r.count))
                .Select<dynamic>((u, r) => new
                {
                    count=r.count==null?0:r.count,
                    u.Id,
                    u.Name,
                    u.HeadIcon
                })
                .ToListAsync();
             
            return list;
        }

        /// <summary>
        /// 组排名
        /// </summary>
        /// <returns></returns>
        public async Task<List<dynamic>> GetGroupRankingList()
        {
            //查询分组内的用户
            List<string> userlist = new List<string>();
            var groupuser = client.Queryable<SysGroupuser>().ToList();
            if (groupuser.Count > 0)
            {
                userlist = groupuser.Select(r => r.UserId).Distinct().ToList();
            }
            //根据在办任务数聚合
            var query = client.Queryable<InsTaskgroup>()
                .Where(r => r.IsComplate == true)
                .GroupBy(r => r.ReciveUserId)
                .Select(r => new
                {
                    count = SqlFunc.AggregateCount(r.Id),
                    userid = r.ReciveUserId
                })
                .MergeTable();
            //关联用户表查询数据
            var list = await client.Queryable<SysGroupuser>()
                .LeftJoin(query, (u, r) => r.userid == u.UserId)
                .GroupBy((u,r)=>u.GroupId)
                .Select((u, r) => new
                {
                    count=SqlFunc.AggregateSumNoNull(r.count),
                    groupid=u.GroupId
                })
                .MergeTable()
                .LeftJoin<SysGroup>((g,t)=>g.groupid==t.Id)
                .OrderByDescending((g, t) => g.count)
                .Select<dynamic>((g, t) => new
                {
                    count = g.count == null ? 0 : g.count,
                    t.Name
                })
                .ToListAsync();

            return list;
        }

        #region 领取任务
        /// <summary>
        /// 根据任务id获取分组任务
        /// </summary>
        /// <param name="id">任务id</param>
        /// <returns></returns>
        public async Task<List<InsTaskgroup>> GetgrouptaskList(string id)
        {
            var query = await client.Queryable<InsTaskgroup>().Where(r=>r.ReciveUserId==null)
                .Where(r => r.TaskId==id)
                .ToListAsync();

            return query;
        }

        /// <summary>
        /// 领取任务
        /// </summary>
        /// <param name="groupIds">分组任务id</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<Response<bool>> ReciveTask(List<string> groupIds)
        {
            var userId = _auth.GetUserId();
            if (string.IsNullOrEmpty(userId))
            {
                throw new Exception("登录失效");
            }
            var taskId = "";
            using(var uwo = UnitWork.CreateContext())
            {
                foreach (var item in groupIds)
                {
                    var taskGroup = await client.Queryable<InsTaskgroup>().Where(t => t.Id == item).FirstAsync();
                    if (taskGroup != null&&taskGroup.ReciveUserId==null)
                    {
                        var task = await client.Queryable<InsTask>().Where(t => t.Id == taskGroup.TaskId).FirstAsync();
                        taskId = task.Id;
                        //更新分组任务信息
                        await uwo.InsTaskgroup.UpdateSetColumnsTrueAsync(r => new InsTaskgroup
                        {
                            ReciveTime = DateTime.Now,
                            ReciveUserId = userId,
                        }, r => r.Id == taskGroup.Id);

                        if (task != null)
                        {
                            //查询并判断任务是否领完
                            var groups = await client.Queryable<InsTaskgroup>()
                                .Where(t => t.TaskId == task.Id && string.IsNullOrEmpty(t.ReciveUserId))
                                .ToListAsync();
                            short state = 1;
                            if (groups.Count == 0)
                            {
                                state=2;
                            }
                            //更新任务状态
                            await uwo.InsTask.UpdateSetColumnsTrueAsync(r => new InsTask
                            {
                                State = state
                            }, r => r.Id == task.Id);
                        }
                    }
                    else
                    {
                        throw new Exception("任务已被领取");
                    }
                }

                var flag = uwo.Commit();
                var content = new
                {
                    queryid = taskId,
                    message = "有新接手的任务"
                };
                var contents = Json.ToJson(content);
                if (flag)
                {
                    try
                    {
                        await _immsgApp.SendMsgAll("InsTask", contents, groupIds[0]);
                        return new Response<bool>
                        {
                            Result = flag,
                            Message = "领取成功"
                        };
                    }
                    catch
                    {
                        return new Response<bool>
                        {
                            Result = flag,
                            Message = "领取成功，推送失败"
                        };
                    }
                }
                else
                {
                    return new Response<bool>
                    {
                        Result = flag,
                        Message = "领取失败"
                    };
                }

            }
        }
        #endregion
    }
}
