using Furion.DatabaseAccessor.Extensions;
using YBEE.EQM.Core;

namespace YBEE.EQM.Application;

/// <summary>
/// 监测计划管理服务
/// </summary>
public class ExamPlanService(IRepository<ExamPlan> rep, IEducationStageYearsService educationStageYearsService) : IExamPlanService, ITransient
{

    #region 创建更新
    /// <summary>
    /// 添加监测计划
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Add(AddExamPlanInput input)
    {
        var ey = await educationStageYearsService.GetByEducationStage(input.EducationStage);
        //var maxExam = await _rep.Where(t => t.EducationStage == input.EducationStage && t.ExamPeriodType == input.ExamPeriodType && t.ExamType == input.ExamType && t.SemesterId == input.SemesterId).OrderByDescending(t => t.Sequence).FirstOrDefaultAsync();
        var maxExam = await rep.Where(t => t.EducationStage == input.EducationStage && t.SemesterId == input.SemesterId).OrderByDescending(t => t.Sequence).FirstOrDefaultAsync();
        short seq = maxExam?.Sequence ?? 0;
        var item = input.Adapt<ExamPlan>();
        item.Sequence = (short)(seq + 1);
        item.EducationYears = ey.EducationYears;
        await item.InsertAsync();
    }
    /// <summary>
    /// 更新监测计划
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Update(UpdateExamPlanInput input)
    {
        if (!await rep.AnyAsync(t => t.Id == input.Id))
        {
            throw Oops.Oh(ErrorCode.E2001);
        }
        var item = input.Adapt<ExamPlan>();
        await item.UpdateIncludeAsync(new[] { nameof(item.Name), nameof(item.FullName), nameof(item.ShortName), nameof(item.Remark), nameof(item.Config) });
    }
    /// <summary>
    /// 删除监测计划
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Del(BaseId input)
    {
        var item = await rep.FirstOrDefaultAsync(t => t.Id == input.Id) ?? throw Oops.Oh(ErrorCode.E2001);
        if (item.Status == ExamStatus.ACTIVE || item.Status == ExamStatus.STOPPED)
        {
            throw Oops.Oh(ErrorCode.E3001, "已使用监测计划");
        }
        await item.DeleteAsync();
    }
    #endregion

    #region 状态变更
    /// <summary>
    /// 开始监测
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Start(BaseId input)
    {
        var item = await rep.Include(t => t.ExamOrgs).FirstOrDefaultAsync(t => t.Id == input.Id) ?? throw Oops.Oh(ErrorCode.E2001);
        if (item.Status != ExamStatus.READY)
        {
            throw Oops.Oh(ErrorCode.E2006);
        }
        if (!item.ExamOrgs.Any())
        {
            throw Oops.Oh(ErrorCode.E2007, "监测机构");
        }
        item.Status = ExamStatus.ACTIVE;
        item.BeginTime = DateTime.Now;
        await item.UpdateIncludeAsync(new[] { nameof(item.Status), nameof(item.BeginTime) });
    }
    /// <summary>
    /// 结束监测
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Stop(BaseId input)
    {
        var item = await rep.FirstOrDefaultAsync(t => t.Id == input.Id) ?? throw Oops.Oh(ErrorCode.E2001);
        if (item.Status != ExamStatus.ACTIVE)
        {
            throw Oops.Oh(ErrorCode.E2006);
        }
        item.Status = ExamStatus.STOPPED;
        item.EndTime = DateTime.Now;
        await item.UpdateIncludeAsync(new[] { nameof(item.Status), nameof(item.EndTime) });
    }
    /// <summary>
    /// 取消监测
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Cancel(BaseId input)
    {
        var item = await rep.FirstOrDefaultAsync(t => t.Id == input.Id) ?? throw Oops.Oh(ErrorCode.E2001);
        if (item.Status == ExamStatus.ACTIVE)
        {
            throw Oops.Oh(ErrorCode.E2006);
        }
        item.Status = ExamStatus.CANCELLED;
        item.EndTime = DateTime.Now;
        await item.UpdateIncludeAsync(new[] { nameof(item.Status), nameof(item.EndTime) });
    }
    #endregion

    #region 查询统计
    /// <summary>
    /// 根据ID获取监测计划
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<ExamPlanOutput> GetById(int id)
    {
        var item = await rep.DetachedEntities.ProjectToType<ExamPlanOutput>()
                                              .FirstOrDefaultAsync(t => t.Id == id) ?? throw Oops.Oh(ErrorCode.E2001);
        return item;
        //return item.Adapt<ExamPlanOutput>();
    }
    /// <summary>
    /// 分页查询监测计划列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<PageResult<ExamPlanOutput>> QueryPageList(ExamPlanPageInput input)
    {
        var query = GetQueryBase(input);
        var ret = await query.OrderByDescending(t => t.CreateTime).ProjectToType<ExamPlanOutput>().ToADPagedListAsync(input.PageIndex, input.PageSize);
        return ret;
    }
    /// <summary>
    /// 获取我的单据状态数量
    /// </summary>
    /// <returns></returns>
    public async Task<List<StatusCount>> QueryStatusCount(ExamPlanPageInput input)
    {
        var query = GetQueryBase(input);
        if (query == null)
        {
            return [];
        }

        var counts = await query.GroupBy(t => t.Status).Select(t => new StatusCount { Status = (int)t.Key, Count = t.Count() }).ToListAsync();
        return counts;
    }
    /// <summary>
    /// 获取最近5个抽测参照成绩监测计划
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<List<ExamPlanOutput>> GetSampleRefPlanList(int id)
    {
        var examPlan = await rep.DetachedEntities.FirstOrDefaultAsync(t => t.Id == id) ?? throw Oops.Oh(ErrorCode.E2001);
        var items = await rep.DetachedEntities.Where(t => t.Id < id && t.EducationStage == examPlan.EducationStage)
                                              .OrderByDescending(t => t.SemesterId).ThenByDescending(t => t.Id)
                                              .Take(5)
                                              .ProjectToType<ExamPlanOutput>()
                                              .ToListAsync();
        return items;
    }
    #endregion

    #region 私有方法
    /// <summary>
    /// 构建查询
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    private IQueryable<ExamPlan> GetQueryBase(ExamPlanPageInput input)
    {
        var name = !string.IsNullOrEmpty(input.Name?.Trim());
        var searchBeginTime = !string.IsNullOrEmpty(input.SearchBeginTime?.Trim());
        var searchEndTime = !string.IsNullOrEmpty(input.SearchEndTime?.Trim());
        var query = rep.DetachedEntities.Where((name, u => EF.Functions.Like(u.Name, $"%{input.Name.Trim()}%") || EF.Functions.Like(u.FullName, $"%{input.Name.Trim()}%") || EF.Functions.Like(u.ShortName, $"%{input.Name.Trim()}%")))
                                         .Where(input.EducationStage.HasValue, t => t.EducationStage == input.EducationStage)
                                         //.Where(input.ExamPeriodType.HasValue, t => t.ExamPeriodType == input.ExamPeriodType)
                                         //.Where(input.ExamType.HasValue, t => t.ExamType == input.ExamType)
                                         .Where(input.SemesterId.HasValue, t => t.SemesterId == input.SemesterId)
                                         .Where(input.Status.HasValue, t => t.Status == input.Status)
                                         .Where((searchBeginTime, u => u.CreateTime >= DateTime.Parse(input.SearchBeginTime)))
                                         .Where((searchEndTime, u => u.CreateTime <= DateTime.Parse(input.SearchEndTime)));
        return query;
    }
    #endregion
}
