using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;

namespace SupplierManager.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FileUploadController : ControllerBase
    {

        public static string[] FolderG = new string[] {"face" };

        [Authorize()]
        [HttpPost()]
        public async Task<IActionResult> UploadFile([FromForm] UploadFileModel model)
        {
            if (model.File == null || model.File.Length == 0)
            {
                return BadRequest("没有上传任何文件");
            }

            try
            {
                // 获取文件名和扩展名
                string originalFileName = Path.GetFileNameWithoutExtension(model.File.FileName);
                string fileExtension = Path.GetExtension(model.File.FileName); // 包含扩展名前的点（如.jpg）

                // 生成8位GUID（取完整GUID的前8位字符）
                string guidPart = Guid.NewGuid().ToString("N")[..16];

                // 组合新文件名：原文件名_8位GUID.扩展名
                string newFileName = $"{originalFileName}_{guidPart}{fileExtension}";

                var filePath = Path.Combine(Directory.GetCurrentDirectory(),
                                          $"wwwroot/Uploads/{model.Folder}",
                                          newFileName);

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await model.File.CopyToAsync(stream);
                }
                return Ok(new { FileName = newFileName });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Message = ex.Message });
            }
        }

        public record DF
        {
            public string? FileName { get; set; }
        }
        // 示例：通过文件名获取图片
        [Authorize()]
        [HttpPost()]
        public IActionResult DownloadFile([FromBody]DF imageName)
        {
            try
            {
                // 拼接图片物理路径（假设图片存放在项目的 wwwroot/images 目录下）
                var imagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/", imageName.FileName);

                // 检查文件是否存在
                if (!System.IO.File.Exists(imagePath))
                {
                    return NotFound("Image not found");
                }
                if (imageName.FileName.Contains(".."))
                {
                    return BadRequest("Invalid file name");
                }


                // 读取文件流并返回
                var imageStream = System.IO.File.OpenRead(imagePath);

                // 根据扩展名自动设置 Content-Type（MIME类型）
                var mimeType = GetMimeType(imageName.FileName);

                return File(imageStream, mimeType);
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Internal server error: {ex.Message}");
            }
        }

        [Authorize()]
        [HttpPost()]
        public IActionResult GetFileNameList()
        {
            try
            {
                // 拼接图片物理路径（假设图片存放在项目的 wwwroot/images 目录下）
                var filePath = Path.Combine(Directory.GetCurrentDirectory(),
                                          $"wwwroot/Download/customization","");

                string[] files= System.IO.Directory.GetFiles(filePath);
                var myfiles= files.Select(A=>Path.GetFileName(A));
                return Ok(new { FileNameList = myfiles });
               
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Internal server error: {ex.Message}");
            }
        }

        // 获取 MIME 类型映射
        private string GetMimeType(string fileName)
        {
            var extension = Path.GetExtension(fileName).ToLowerInvariant();
            return 
                extension switch
                {
                    ".jpg" => "image/jpeg",
                    ".jpeg" => "image/jpeg",
                    ".png" => "image/png",
                    ".gif" => "image/gif",
                    ".xls" =>"application/vnd.ms-excel",
                    ".xlsx"=>"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    _ => "application/octet-stream" // 默认类型
                };
        }
    }
    public class UploadFileModel
    {
        public IFormFile File { get; set; }
        public string Folder { get; set; }
    }
}
