using MilitaryTrainingManagement.Configuration;
using MilitaryTrainingManagement.Services.Interfaces;
using Microsoft.Extensions.Options;
using SixLabors.ImageSharp;

namespace MilitaryTrainingManagement.Services.Implementations;

/// <summary>
/// 文件上传服务实现
/// </summary>
public class FileUploadService : IFileUploadService
{
    private readonly ILogger<FileUploadService> _logger;
    private readonly FileStorageOptions _storageOptions;

    // 照片尺寸限制（放宽限制以适应各种照片）
    private const int MinPhotoWidth = 100;
    private const int MaxPhotoWidth = 4000;
    private const int MinPhotoHeight = 100;
    private const int MaxPhotoHeight = 4000;
    private const long MaxPhotoSize = 10 * 1024 * 1024; // 10MB
    private const long MaxDocumentSize = 20 * 1024 * 1024; // 20MB

    private static readonly string[] AllowedPhotoExtensions = { ".jpg", ".jpeg", ".png" };
    private static readonly string[] AllowedDocumentExtensions = { ".pdf", ".doc", ".docx", ".jpg", ".jpeg", ".png" };

    public FileUploadService(IOptions<FileStorageOptions> storageOptions, ILogger<FileUploadService> logger)
    {
        _storageOptions = storageOptions.Value;
        _logger = logger;
    }

    public async Task<string> UploadPhotoAsync(IFormFile file)
    {
        var validation = await ValidatePhotoAsync(file);
        if (!validation.IsValid)
        {
            throw new ArgumentException(validation.ErrorMessage);
        }

        return await SaveFileAsync(file, "photos");
    }

    public async Task<string> UploadDocumentAsync(IFormFile file)
    {
        ValidateDocument(file);
        return await SaveFileAsync(file, "documents");
    }


    public async Task<PhotoValidationResult> ValidatePhotoAsync(IFormFile file)
    {
        if (file == null || file.Length == 0)
        {
            return PhotoValidationResult.Failure("照片文件不能为空");
        }

        if (file.Length > MaxPhotoSize)
        {
            return PhotoValidationResult.Failure($"照片文件大小不能超过{MaxPhotoSize / 1024 / 1024}MB");
        }

        var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
        if (!AllowedPhotoExtensions.Contains(extension))
        {
            return PhotoValidationResult.Failure($"照片格式必须是: {string.Join(", ", AllowedPhotoExtensions)}");
        }

        try
        {
            using var stream = file.OpenReadStream();
            using var image = await Image.LoadAsync(stream);

            var width = image.Width;
            var height = image.Height;

            // 验证照片尺寸（放宽限制）
            if (width < MinPhotoWidth || width > MaxPhotoWidth)
            {
                return PhotoValidationResult.Failure($"照片宽度应在{MinPhotoWidth}-{MaxPhotoWidth}像素之间，当前为{width}像素");
            }

            if (height < MinPhotoHeight || height > MaxPhotoHeight)
            {
                return PhotoValidationResult.Failure($"照片高度应在{MinPhotoHeight}-{MaxPhotoHeight}像素之间，当前为{height}像素");
            }

            // 不再严格验证宽高比，允许各种照片
            return PhotoValidationResult.Success(width, height);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "照片验证失败");
            return PhotoValidationResult.Failure("无法读取照片文件，请确保文件格式正确");
        }
    }

    public async Task DeleteFileAsync(string filePath)
    {
        if (string.IsNullOrEmpty(filePath))
            return;

        var fullPath = GetFullPath(filePath);
        if (File.Exists(fullPath))
        {
            await Task.Run(() => File.Delete(fullPath));
            _logger.LogInformation("已删除文件: {FilePath}", filePath);
        }
    }

    public string GetFullPath(string relativePath)
    {
        return Path.Combine(_storageOptions.BasePath, relativePath);
    }

    private void ValidateDocument(IFormFile file)
    {
        if (file == null || file.Length == 0)
        {
            throw new ArgumentException("文档文件不能为空");
        }

        if (file.Length > MaxDocumentSize)
        {
            throw new ArgumentException($"文档文件大小不能超过{MaxDocumentSize / 1024 / 1024}MB");
        }

        var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
        if (!AllowedDocumentExtensions.Contains(extension))
        {
            throw new ArgumentException($"文档格式必须是: {string.Join(", ", AllowedDocumentExtensions)}");
        }
    }

    private async Task<string> SaveFileAsync(IFormFile file, string subFolder)
    {
        var uploadsPath = Path.Combine(_storageOptions.BasePath, subFolder);
        Directory.CreateDirectory(uploadsPath);

        var fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName).ToLowerInvariant()}";
        var filePath = Path.Combine(uploadsPath, fileName);

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

        _logger.LogInformation("文件已保存: {FilePath}", filePath);
        
        // 返回带 URL 前缀的完整访问路径
        var relativePath = Path.Combine(subFolder, fileName).Replace("\\", "/");
        return $"{_storageOptions.UrlPrefix.TrimEnd('/')}/{relativePath}";
    }
}
