namespace Tiobon.Core.Services;

/// <summary>
/// 附件 (服务)
/// </summary>
public class Ghre_AttachmentServices : BaseServices<Ghre_Attachment, Ghre_AttachmentDto, InsertGhre_AttachmentInput, EditGhre_AttachmentInput>, IGhre_AttachmentServices
{
    private readonly IBaseRepository<Ghre_Attachment> _dal;
    public Ghre_AttachmentServices(IBaseRepository<Ghre_Attachment> dal)
    {
        this._dal = dal;
        base.BaseDal = dal;
    }

    public async Task<ServiceResult<FileUploadResult>> UploadVideoAsync(ChunkUpload upload)
    {
        var file = upload.file;
        var path = $"{$"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}upload/{upload.masterId}/{Path.DirectorySeparatorChar}{upload.id}{Path.DirectorySeparatorChar}"}";
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);
        using (var stream = File.Create(path + $"{upload.chunkIndex}"))
        {
            await file.CopyToAsync(stream);
        }

        if (upload.chunkIndex == upload.totalChunks - 1)
        {
            var ext = string.Empty;
            if (string.IsNullOrEmpty(file.FileName) == false)
            {
                var dotPos = upload.fileName.LastIndexOf('.');
                ext = upload.fileName.Substring(dotPos + 1);
            }
            var id = SnowFlakeSingle.Instance.NextId();
            await FileMerge(upload.id, "." + ext, id, upload.masterId);
            using var _context = ContextFactory.CreateContext();


            var filePath = $"/files/upload/{upload.masterId}/{id}.{ext}";
            var fileAttachment = new Ghre_Attachment();
            fileAttachment.Id = SnowFlakeSingle.Instance.NextId();
            fileAttachment.AttachmentNo = upload.file.FileName;
            fileAttachment.AttachFileName = upload.file.FileName;
            fileAttachment.CreateBy = App.User.ID;
            fileAttachment.CreateTime = DateTime.Now;
            fileAttachment.AttachmentName = upload.fileName;
            fileAttachment.AttachFileExtension = ext;
            fileAttachment.AttachFileSize = upload.file.Length;
            fileAttachment.PhysicsPath = filePath;
            fileAttachment.RelativePath = filePath;
            fileAttachment.FileURL = filePath;
            fileAttachment.ThumbnailPath = filePath;
            fileAttachment.AttachmentType = upload.file.ContentType;
            //url = fileName + "." + ext;
            _context.Add(fileAttachment);
            _context.SaveChanges();
            return ServiceResult<FileUploadResult>.OprateSuccess("", new FileUploadResult()
            {
                Id = fileAttachment.Id,
                AttachFileExtension = fileAttachment.AttachFileExtension,
                AttachFileName = fileAttachment.AttachFileName,
                AttachmentName = fileAttachment.AttachmentName,
                AttachmentNo = fileAttachment.AttachmentNo,
                FileURL = "/Advanced" + fileAttachment.FileURL,
                PhysicsPath = "/Advanced" + fileAttachment.PhysicsPath,
                RelativePath = "/Advanced" + fileAttachment.RelativePath,
                ThumbnailPath = "/Advanced" + fileAttachment.ThumbnailPath,
                AttachFileSize = fileAttachment.AttachFileSize,
            });
        }
        return ServiceResult<FileUploadResult>.OprateSuccess("", null);
    }

    public static async Task<object> FileMerge(string lastModified, string fileExts, long NewfileName, string masterId)
    {
        string erro = "";
        bool ok = false;
        try
        {
            string wwwroot = $"{Directory.GetCurrentDirectory()}/wwwroot/files/upload/{masterId}/";
            var temporary = Path.Combine(wwwroot, lastModified);//临时文件夹
            //fileName = Request.Form["fileName"];//文件名
            string fileExt = fileExts;//获取文件后缀
            var files = Directory.GetFiles(temporary);//获得下面的所有文件
            DirectoryInfo di = new DirectoryInfo(wwwroot + NewfileName + "/");
            if (!di.Exists)
                di.Create();

            var finalPath = Path.Combine(wwwroot, NewfileName + fileExt);//最终的文件名（demo中保存的是它上传时候的文件名，实际操作肯定不能这样）
            var fs = new FileStream(finalPath, FileMode.Create);
            foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排一下序，保证从0-N Write
            {
                var bytes = File.ReadAllBytes(part);
                await fs.WriteAsync(bytes, 0, bytes.Length);
                bytes = null;
                //System.IO.File.Delete(part);//删除分块
            }
            fs.Close();

            //Directory.Delete(temporary);//删除文件夹
            ok = true;
        }
        catch (Exception ex)
        {
            erro = ex.Message;
        }
        return ok;
    }
}