
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OpenAuth.App;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository.Domain;

namespace OpenAuth.WebApi.Controllers
{
    /// <summary>  文件上传</summary>
    /// <remarks>   yubaolee, 2019-03-08. </remarks>

    [Route("api/[controller]/[action]")]
    [ApiController]
    //[ApiExplorerSettings(GroupName = "文件管理_Files")]
    public class FilesController : ControllerBase
    {

        private FileApp _app;

        public FilesController(FileApp app)
        {
            _app = app;
        }

        ///// <summary>
        ///// 加载附件列表
        ///// </summary>
        //[HttpGet]
        //public async Task<TableData> Load([FromQuery] QueryFileListReq request)
        //{
        //    return await _app.Load(request);
        //}
        /// <summary>
        /// 加载附件列表
        /// </summary>
        [HttpGet]
        public async Task<Response<PageInfo<List<SysUploadFile>>>> Load([FromQuery] QueryFileListReq request)
        {

            var result = new Response<PageInfo<List<SysUploadFile>>>();
            try
            {
                return await _app.Load(request);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public Response Delete([FromBody] long[] ids)
        {
            var result = new Response();
            try
            {
                _app.Delete(ids);

            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }

        /// <summary>
        ///  批量上传文件接口
        /// <para>客户端文本框需设置name='files'</para>
        /// </summary>
        /// <param name="files"></param>
        /// <returns>服务器存储的文件信息</returns>
        [HttpPost]
        [RequestSizeLimit(214748364800)]
        [AllowAnonymous]
        public Response<IList<SysUploadFile>> Upload(IFormFileCollection files)
        {
            var result = new Response<IList<SysUploadFile>>();
            try
            {
                result.Result = _app.Add(files);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }


        /// <summary>
        ///  批量上传文件接口
        /// <para>客户端文本框需设置name='files'</para>
        /// </summary>
        /// <param name="file"></param>
        /// <returns>服务器存储的文件信息</returns>
        [HttpPost]
        [RequestSizeLimit(214748364800)]
        [AllowAnonymous]
        public Response<SysUploadFile> UploadSingle(IFormFile file)
        {
            var result = new Response<SysUploadFile>();
            try
            {
                result.Result = _app.Add(file);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }
        //断点续传
        private readonly string _uploadFolder = "Uploads"; // 上传文件的存储路径
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> UploadFileChunk(IFormFile file, [FromForm] string fileName, [FromForm] int chunkIndex, [FromForm] int totalChunks)
        {
            if (!Directory.Exists(_uploadFolder))
            {
                Directory.CreateDirectory(_uploadFolder);
            }
            if (file == null || file.Length == 0)
            {
                return BadRequest("Invalid file chunk.");
            }

            var filePath = Path.Combine(_uploadFolder, $"{fileName}.part_{chunkIndex}");

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            // Check if all chunks are uploaded
            if (IsAllChunksUploaded(fileName, totalChunks))
            {
                MergeChunks(fileName, totalChunks);
            }

            return Ok(new { Message = "Chunk uploaded successfully." });
        }
        private bool IsAllChunksUploaded(string fileName, int totalChunks)
        {
            for (int i = 0; i < totalChunks; i++)
            {
                var filePath = Path.Combine(_uploadFolder, $"{fileName}.part_{i}");
                if (!System.IO.File.Exists(filePath))
                {
                    return false;
                }
            }
            return true;
        }
        private void MergeChunks(string fileName, int totalChunks)
        {
            var finalFilePath = Path.Combine(_uploadFolder, fileName);
            using (var finalFile = new FileStream(finalFilePath, FileMode.Create))
            {
                for (int i = 0; i < totalChunks; i++)
                {
                    var chunkFilePath = Path.Combine(_uploadFolder, $"{fileName}.part_{i}");
                    using (var chunkFile = new FileStream(chunkFilePath, FileMode.Open))
                    {
                        chunkFile.CopyTo(finalFile);
                    }
                    System.IO.File.Delete(chunkFilePath); // 删除临时分片文件
                }
            }
        }
        [HttpGet]
        [AllowAnonymous]
        public IActionResult GetUploadStatus([FromQuery] string fileName)
        {
            var chunkFiles = Directory.GetFiles(_uploadFolder, $"{fileName}.part_*");
            var uploadedChunks = chunkFiles.Length;

            return Ok(new { UploadedChunks = uploadedChunks });
        }
    }
}
