using IRaCIS.Core.Application.Helper;
using MassTransit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using RestSharp;
using SharpCompress.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IRaCIS.Core.Application.Service.MinimalApiService
{
    [ApiExplorerSettings(GroupName = "Institution")]
    public class FileToPDFService(IWebHostEnvironment _hostEnvironment) : ServiceBase
    {

        [AllowAnonymous]
        [RoutePattern(HttpMethod = "Post")]
        public async Task<IResult> UploadFileAsync([FromForm] IFormFile file)
        {
            var tempFileName = NewId.NextGuid() + file.FileName;
            var tempPDFName = Path.GetFileNameWithoutExtension(tempFileName) + ".pdf";


            // 获取wwwroot目录
            var wwwRootPath = Path.Combine(FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment), "temp");

            // 检查wwwroot/temp目录是否存在,不存在则创建
            if (!Directory.Exists(wwwRootPath))
            {
                Directory.CreateDirectory(wwwRootPath);
            }

            // 文件保存路径
            var pdfFilePath = Path.Combine(wwwRootPath, tempPDFName);
            var tempFilePath = Path.Combine(wwwRootPath, tempFileName);


            using var stream = File.OpenWrite(tempFilePath);
            await file.CopyToAsync(stream);

            FileConvertHelper.ConvertWordToPdf(tempFilePath, Path.GetDirectoryName(pdfFilePath));

            var fileBytes = await File.ReadAllBytesAsync(pdfFilePath);

            // 清理临时上传的文件和pdf
            if (File.Exists(pdfFilePath))
            {
                File.Delete(pdfFilePath);
            }
            if (File.Exists(tempFilePath))
            {
                File.Delete(tempFilePath);
            }

            new FileExtensionContentTypeProvider().Mappings.TryGetValue(Path.GetExtension(tempPDFName), out var contentType);

            return Results.File(fileBytes, contentType);

        }


        public async Task<IResult> GetPDFFileAsync(string fileUrl)
        {
            var tempFileName = NewId.NextGuid() + Path.GetFileName(fileUrl);
            var tempPDFName = Path.GetFileNameWithoutExtension(tempFileName) + ".pdf";


            // 获取wwwroot目录
            var wwwRootPath = Path.Combine(FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment), "temp");

            // 检查wwwroot/temp目录是否存在,不存在则创建
            if (!Directory.Exists(wwwRootPath))
            {
                Directory.CreateDirectory(wwwRootPath);
            }

            // 文件保存路径
            var pdfFilePath = Path.Combine(wwwRootPath, tempPDFName);
            var tempFilePath = Path.Combine(wwwRootPath, tempFileName);


            //请求url获取文件
            var client = new RestClient(fileUrl);

            var request = new RestRequest(fileUrl, Method.Get);

            var response = await client.ExecuteAsync(request);

            // 检查响应是否成功
            if (response.IsSuccessful)
            {
                // 将响应内容写入到本地文件
                await File.WriteAllBytesAsync(tempFilePath, response.RawBytes);

                FileConvertHelper.ConvertWordToPdf(tempFilePath, Path.GetDirectoryName(pdfFilePath));

                var fileBytes = await File.ReadAllBytesAsync(pdfFilePath);

                // 清理临时上传的文件和pdf
                if (File.Exists(pdfFilePath))
                {
                    File.Delete(pdfFilePath);
                }
                if (File.Exists(tempFilePath))
                {
                    File.Delete(tempFilePath);
                }

                new FileExtensionContentTypeProvider().Mappings.TryGetValue(Path.GetExtension(tempPDFName), out var contentType);

                return Results.File(fileBytes, contentType);
            }
            else
            {
                Console.WriteLine($"下载文件失败: {response.ErrorMessage}");

                return Results.Problem("下载文件失败", statusCode: StatusCodes.Status500InternalServerError);

            }


        }

    }
}