using Infrastructure;
using Infrastructure.Extensions;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.Task.Request;
using OpenAuth.App.ServiceApp.Task.Response;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;

namespace OpenAuth.App.ServiceApp.Task;

public class PersonTaskApp : SqlSugarBaseApp<InsTask, SugarDbContext>
{
    public PersonTaskApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<InsTask> repository, IAuth auth) :
        base(unitWork, repository, auth)
    {
    }

    /// <summary>
    /// 个人任务列表
    /// </summary>
    /// <param name="req"></param>
    /// <returns></returns>
    public async Task<Response<PageInfo<List<InsTaskExtend>>>> Load(PersonTaskQuery req)
    {
        var userId = _auth.GetUserId();
        if (string.IsNullOrEmpty(userId))
        {
            throw new Exception("登录失效");
        }


        var userIds = await Repository.ChangeRepository<SugarRepositiry<SysGroup>>()
            .AsQueryable().InnerJoin<SysGroupuser>((a, b) => a.Id == b.GroupId)
            .Where(a => a.GroupLeaderId == userId)
            .Select((a, b) => b.UserId)
            .ToListAsync();

        userIds.Add(userId);

        RefAsync<int> total = 0;
        var result = await Repository.AsQueryable()
            .RightJoin<InsTaskgroup>((a, b) => a.Id == b.TaskId)
            .Where((a, b) => userIds.Contains(b.ReciveUserId))
            .WhereIF(!string.IsNullOrEmpty(req.key),(a,b)=>a.TaskName.Contains(req.key))
            .Select((a, b) => new InsTaskExtend
            {
                RowNumber = SqlSugar.SqlFunc.RowNumber(b.Id),
                TaskName = a.TaskName, // 任务名称
                GroupName = b.GroupName, // 任务分组包
                Sort = b.Sort, // 序号
                BeginNum = b.BeginNum,
                EndNum = b.EndNum,
                TubanNum = b.EndNum - b.BeginNum + 1,
                TaskId = b.TaskId,
                CreateTime = a.CreateTime, // 创建时间
                ReciveTime = b.ReciveTime, // 接收时间
                ReciveUserId = b.ReciveUserId, //任务接收人
                IsComplate = b.IsComplate, // 完成情况
                CompleteTime = b.CompleteTime,
                Remark = b.Remark,
                TaskGroupId = b.Id,
                TaskState = a.State,
                TaskIsCompleted = a.IsCompleted,
                TaskCreateTime = a.CreateTime,
                TaskRemark = a.Remark
            })
            .ToPageListAsync(req.page, req.limit, total);
        return new Response<PageInfo<List<InsTaskExtend>>>
        {
            Result = new PageInfo<List<InsTaskExtend>>
            {
                Items = result,
                Total = total
            }
        };
    }

    public async Task<Response<InsTaskExtend>> GetTaskDetail(string taskGroupId)
    {
        var result = await Repository.AsQueryable()
            .RightJoin<InsTaskgroup>((a, b) => a.Id == b.TaskId)
            .InnerJoin<InsAishp>((a, b, c) => a.ShpId == c.Id)
            .Where((a, b) => b.Id == taskGroupId)
            .Select((a, b,c) => new InsTaskExtend
            {
                TaskName = a.TaskName, // 任务名称
                GroupName = b.GroupName, // 任务分组包
                Sort = b.Sort, // 序号
                BeginNum = b.BeginNum,
                ShpName = c.ShpName,
                EndNum = b.EndNum,
                TubanNum = b.EndNum - b.BeginNum + 1,
                TaskId = b.TaskId,
                CreateTime = a.CreateTime, // 创建时间
                ReciveTime = b.ReciveTime, // 接收时间
                ReciveUserId = b.ReciveUserId, //任务接收人
                IsComplate = b.IsComplate, // 完成情况
                CompleteTime = b.CompleteTime,
                Remark = b.Remark,
                TaskGroupId = b.Id,
                TaskState = a.State,
                TaskIsCompleted = a.IsCompleted,
                TaskCreateTime = a.CreateTime,
                TaskRemark = a.Remark,
                CreateUserName = a.CreateUserName
            }).FirstAsync();
        if (result == null)
        {
            return new Response<InsTaskExtend>
            {
                Code = 500,
                Message = "未找到任务"
            };
        }

        result.PrePhaseList = await Repository.ChangeRepository<SugarRepositiry<InsTasktif>>()
            .AsQueryable()
            .RightJoin<InsTif>((a, b) => a.TifId == b.Id)
            .Where(a => a.TaskId == result.TaskId && a.TifType == 0)
            .Select((a, b) => b.TifName).ToListAsync();
        result.NextPhaseList = await Repository.ChangeRepository<SugarRepositiry<InsTasktif>>()
            .AsQueryable()
            .RightJoin<InsTif>((a, b) => a.TifId == b.Id)
            .Where(a => a.TaskId == result.TaskId && a.TifType == 1)
            .Select((a, b) => b.TifName).ToListAsync();
        return new Response<InsTaskExtend>
        {
            Result = result
        };
    }

    public async Task<Response<bool>> SubmitTask(string taskGroupId, string remark)
    {
        // 修改任务分包状态
        var userId = _auth.GetUserId();
        if (string.IsNullOrEmpty(userId))
        {
            throw new Exception("登录失效");
        }

        var taskGroup = await Repository
            .ChangeRepository<SugarRepositiry<InsTaskgroup>>()
            .AsQueryable()
            .FirstAsync(t => t.Id == taskGroupId);

        if (taskGroup == null)
        {
            return new Response<bool>
            {
                Code = 500,
                Message = "未找到任务",
                Result = false
            };
        }

        using var uow = UnitWork.CreateContext();

        await uow.InsTaskgroup.UpdateSetColumnsTrueAsync(t =>
            new InsTaskgroup
            {
                IsComplate = true,
                Remark = remark,
                CompleteTime = DateTime.Now
            }, t => t.Id == taskGroup.Id);
        // 校验任务是否完成 
        var unCompletedCount = await Repository.ChangeRepository<SugarRepositiry<InsTaskgroup>>()
            .AsQueryable()
            .Where(t => t.TaskId == taskGroup.TaskId)
            .Where(t => t.IsComplate.Equals(false))
            .CountAsync();
        // 不存在未完成任务
        if (unCompletedCount == 0)
        {
            //更新任务状态
            await uow.InsTask.UpdateSetColumnsTrueAsync(t => new InsTask
            {
                Id = taskGroup.TaskId,
                IsCompleted = true,
                CompleteTime = DateTime.Now
            }, t => t.Id == taskGroup.TaskId);
        }

        uow.Commit();
        return new Response<bool>
        {
            Result = true
        };
    }

    public async Task<Response<bool>> ReturnTask(string taskGroupId, string remark)
    {
        var userId = _auth.GetUserId();
        if (string.IsNullOrEmpty(userId))
        {
            throw new Exception("登录失效");
        }

        var taskGroup = await Repository
            .ChangeRepository<SugarRepositiry<InsTaskgroup>>()
            .AsQueryable()
            .FirstAsync(t => t.Id == taskGroupId);
        if (taskGroup.IsComplate)
        {
            return new Response<bool>
            {
                Code = 500,
                Message = "任务已处理完成，无法退回",
                Result = false
            };
        }

        await Repository
            .ChangeRepository<SugarRepositiry<InsTaskgroup>>()
            .UpdateSetColumnsTrueAsync(t => new InsTaskgroup
                {
                    Id = taskGroup.Id,
                    IsComplate = false,
                    ReciveUserId = null,
                    ReciveTime = null,
                    Remark = remark
                },
                t => t.Id == taskGroupId);
        return new Response<bool>
        {
            Result = true
        };
    }
}