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

namespace YBEE.EQM.Application;

/// <summary>
/// 监测数据上报类型管理服务
/// </summary>
public class ExamDataReportService : IExamDataReportService, ITransient
{
    private readonly IRepository<ExamDataReport> _rep;
    private readonly IResourceFileService _resourceFileService;

    public ExamDataReportService(IRepository<ExamDataReport> rep, IResourceFileService resourceFileService)
    {
        _rep = rep;
        _resourceFileService = resourceFileService; 
    }

    #region 创建更新
    /// <summary>
    /// 添加上报类型
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Add(AddExamDataReportInput input)
    {
        if (await _rep.AnyAsync(t => t.ExamPlanId == input.ExamPlanId && t.Type == input.Type))
        {
            throw Oops.Oh(ErrorCode.E2002, "该类型");
        }
        var item = input.Adapt<ExamDataReport>();
        await item.InsertAsync();
    }
    /// <summary>
    /// 更新上报类型
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Update(UpdateExamDataReportInput input)
    {
        var item = await _rep.FirstOrDefaultAsync(t => t.Id == input.Id) ?? throw Oops.Oh(ErrorCode.E2001);
        item.Remark = input.Remark;
        await item.UpdateIncludeAsync(new[] { nameof(item.BeginTime), nameof(item.EndTime), nameof(item.Remark) });
    }
    /// <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.READY)
        {
            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.FirstOrDefaultAsync(t => t.Id == input.Id) ?? throw Oops.Oh(ErrorCode.E2001);
        if (item.Status != ExamStatus.READY)
        {
            throw Oops.Oh(ErrorCode.E2006);
        }
        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) });
    }

    /// <summary>
    /// 添加附件
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task AddAttachment(AddAttachmentInput input)
    {
        var item = await _rep.FirstOrDefaultAsync(t => t.Id == input.SourceId) ?? throw Oops.Oh(ErrorCode.E2001);
        item.Attachments = AttachmentUtil.InsertInto(item.Attachments, input.Adapt<AttachmentItem>());
        await item.UpdateIncludeAsync(new[] { nameof(item.Attachments) });
    }
    /// <summary>
    /// 删除附件
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task DelAttachment(DeleteAttachmentInput input)
    {
        var item = await _rep.FirstOrDefaultAsync(t => t.Id == input.SourceId) ?? throw Oops.Oh(ErrorCode.E2001);
        var attachments = AttachmentUtil.GetList(item.Attachments);
        var a = attachments.FirstOrDefault(t => t.FileId == input.FileId);
        if (a != null)
        {
            attachments.Remove(a);
            item.Attachments = JSON.Serialize(attachments);
            await item.UpdateIncludeAsync(new[] { nameof(item.Attachments) });

            await _resourceFileService.Del(new() { Id = a.FileId });
            if (a.ThumbFileId.HasValue && a.ThumbFileId > 0)
            {
                await _resourceFileService.Del(new() { Id = a.ThumbFileId.Value });
            }
        }
    }

    #endregion

    #region 查询
    /// <summary>
    /// 根据ID获取监测数据上报类型
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<ExamDataReportOutput> GetById(int id)
    {
        var item = await _rep.DetachedEntities.FirstOrDefaultAsync(t => t.Id == id) ?? throw Oops.Oh(ErrorCode.E2001);
        return item.Adapt<ExamDataReportOutput>();
    }
    /// <summary>
    /// 根据监测计划ID获取数据上报类型列表
    /// </summary>
    /// <param name="examPlanId"></param>
    /// <returns></returns>
    public async Task<List<ExamDataReportOutput>> GetListByExamPlanId(int examPlanId)
    {
        var items = await _rep.DetachedEntities.Where(t => t.ExamPlanId == examPlanId).ProjectToType<ExamDataReportOutput>().OrderBy(t => t.Type).ToListAsync();
        var orgCount = await _rep.Change<ExamOrg>().DetachedEntities.Where(t => t.ExamPlanId == examPlanId).CountAsync();

        foreach (var item in items)
        {
            var reportedCount = await _rep.Change<ExamOrgDataReport>().DetachedEntities.Where(t => t.Type == item.Type && t.ExamOrg.ExamPlanId == examPlanId && t.Status == DataReportStatus.REPORTED).CountAsync();
            item.ReportedCount = reportedCount;
            item.Count = orgCount;
        }
        return items;
    }
    #endregion
}
