using Microsoft.Extensions.Options;
using YBEE.EQM.Core;

namespace YBEE.EQM.Application;

/// <summary>
/// 反馈结果管理服务
/// </summary>
[ApiDescriptionSettings(Name = "exam-result")]
[Route("exam/result")]
public class ExamResultAppService : IDynamicApiController
{
    private readonly IExamResultService _examResultService;
    private readonly EqmSiteOptions _eqmSiteOptions;
    public ExamResultAppService(IExamResultService examResultService, IOptions<EqmSiteOptions> options)
    {
        _examResultService = examResultService;
        _eqmSiteOptions = options.Value;
    }

    /// <summary>
    /// 上传统一反馈文件
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [RequestSizeLimit(long.MaxValue)]
    [RequestFormLimits(MultipartBodyLengthLimit = long.MaxValue)]
    public async Task Upload([FromForm] UploadExamResultInput input)
    {
        var savePath = Path.Combine(input.ExamPlanId.ToString(), input.ExamDataPublishId.ToString());
        var saveRoot = Path.Combine(_eqmSiteOptions.ExamResultRoot, savePath);
        if (!Directory.Exists(saveRoot))
        {
            Directory.CreateDirectory(saveRoot);
        }
        var extName = Path.GetExtension(input.File.FileName);
        var fileName = Guid.NewGuid().ToString("N") + extName;
        using var stream = File.Create(Path.Combine(saveRoot, fileName));
        await input.File.CopyToAsync(stream);
        await stream.FlushAsync();

        AddExamResultInput item = input.Adapt<AddExamResultInput>();
        item.FileName = input.File.FileName;
        item.FilePath = Path.Combine(savePath, fileName);
        item.FileSize = input.File.Length;
        item.FileExtName = Path.GetExtension(input.File.FileName);
        await _examResultService.Add(item);
    }

    /// <summary>
    /// 根据发布内容ID获取文件列表
    /// </summary>
    /// <param name="publishId"></param>
    /// <returns></returns>
    public async Task<List<ExamResultOutput>> GetListByPublishId([FromQuery][Required] int publishId)
    {
        return await _examResultService.GetListByPublishId(publishId);
    }
}
