using CloudBuilder.AI.Entity;
using CloudBuilder.Core.DependencyInjection.Form;
using CloudBuilder.Core.DependencyInjection.Request;
using CloudBuilder.Core.Request;
using CloudBuilder.Core.Service;
using CloudBuilder.Gui;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using Microsoft.Extensions.DependencyInjection;

namespace CloudBuilder.AI.Gui.Request
{
    public class DmsFileRequestHelper
    {
        private const int CHUNK_SIZE = 512 * 1024; // 512KB 分块大小

        private IServiceRequest serviceRequest;
        public BookDmsFileViewEntity UploadFile(string fileName, string folderName)
        {
            var fileInfo = new FileInfo(fileName);
            var chunks = SplitFile(fileName);
            string uid = Guid.NewGuid().ToString();
            string fileFullName = fileInfo.Name;

            return UploadChunk(chunks, fileFullName, uid, 1, folderName);
        }

        // 分块上传方法
        private BookDmsFileViewEntity UploadChunk(IList<byte[]> chunks, string fileName, string uid, int index, string folderName)
        {
            BookDmsFileViewEntity dmsFileEntity = new BookDmsFileViewEntity();
            try
            {
                var fileExtension = Path.GetExtension(fileName);
                var chunk = chunks[index - 1];

                using (var formData = new MultipartFormDataContent())
                {
                    var content = new ByteArrayContent(chunk);
                    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");

                    formData.Add(content, fileName,
                        $"{uid}-{index}-{chunks.Count}{fileExtension}");

                    IContext context = ApplicationServiceContext.Context;
                    using (var scope = ApplicationServiceContext.ServiceProvider.CreateScope())
                    {
                        serviceRequest = scope.ServiceProvider.GetService<IServiceRequest>()!;

                        serviceRequest.AddHeaders("FilePath", folderName);

                        serviceRequest.SetContext(context);

                        Task.Run(async () => dmsFileEntity = await serviceRequest.PostAsync<BookDmsFileViewEntity>("/DmsFile/UploadFile", formData)).GetAwaiter().GetResult();
                    }

                    if (index < chunks.Count)
                    {
                        dmsFileEntity = UploadChunk(chunks, fileName, uid, index + 1, folderName);
                    }
                }
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            return dmsFileEntity;
        }

        // 文件分块方法
        private IList<byte[]> SplitFile(string filePath)
        {
            var chunks = new List<byte[]>();
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                long fileSize = fileStream.Length;
                long start = 0;
                while (start < fileSize)
                {
                    long remaining = fileSize - start;
                    int chunkSize = (int)Math.Min(CHUNK_SIZE, remaining);

                    byte[] buffer = new byte[chunkSize];
                    fileStream.Read(buffer, 0, chunkSize);

                    chunks.Add(buffer);
                    start += CHUNK_SIZE;
                }
            }
            return chunks;
        }

        public void DownloadFile(int fileId, string saveFilePath)
        {
            try
            {
                ServiceHelper.GetService<IServiceRequest>()!.DownloadFile("/DmsFile/DownloadFile?fileId=" + fileId, saveFilePath, null, OpenFile);
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }

        private void OpenFile(string fileFullName)
        {
            Process.Start(new ProcessStartInfo
            {
                FileName = fileFullName,
                UseShellExecute = true // 使用Windows Shell执行
            });
        }
    }
}
