using SqlSugar;
using Tiobon.Core.DataAccess;

namespace Tiobon.Core.Controllers;

/// <summary>
/// 文件服务
/// </summary>
[Produces("application/json")]
[Route("api/File"), ApiExplorerSettings(GroupName = Grouping.GroupName_System)]
public class FileController : BaseApiController
{
    public ITiobonArticleServices _TiobonArticleServices { get; set; }
    private readonly ILogger<TiobonController> _logger;
    /// <summary>
    /// 配置信息
    /// </summary>
    private readonly IConfiguration _configuration;
    private readonly IWebHostEnvironment _hostingEnvironment;
    private readonly IGhre_AttachmentServices _ghre_AttachmentServices;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="logger"></param>
    /// <param name="configuration"></param>
    /// <param name="hostingEnvironment"></param>
    /// <param name="ghre_AttachmentServices"></param>
    public FileController(ILogger<TiobonController> logger, IConfiguration configuration, IWebHostEnvironment hostingEnvironment, IGhre_AttachmentServices ghre_AttachmentServices)
    {
        _logger = logger;
        _configuration = configuration;
        _hostingEnvironment = hostingEnvironment;
        _ghre_AttachmentServices = ghre_AttachmentServices;
    }

    #region 上传图片
    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="fileList"></param>
    /// <returns></returns>
    [HttpPost, Route("UploadImage")]
    public async Task<ServiceResult<string>> UploadImageAsync(IFormFileCollection fileList)
    {
        string filePath = null;
        using var _context = ContextFactory.CreateContext();

        if (fileList.Count > 0)
        {
            filePath = !string.IsNullOrEmpty(filePath) ? filePath : "upload";
            foreach (var file in fileList)
            {

                var ext = string.Empty;
                if (string.IsNullOrEmpty(file.FileName) == false)
                {
                    var dotPos = file.FileName.LastIndexOf('.');
                    ext = file.FileName.Substring(dotPos + 1);
                }

                string pathHeader = "wwwroot/" + filePath;
                if (!Directory.Exists(pathHeader))
                    Directory.CreateDirectory(pathHeader);

                string fileName = StringHelper.GetSysID();
                filePath = "/" + filePath + "/" + $"{fileName}.{ext}";
                //var filepath = Path.Combine(pathHeader, file.FileName);
                using (var stream = global::System.IO.File.Create("wwwroot/" + filePath))
                {
                    await file.CopyToAsync(stream);
                }
                Ghre_Attachment fileAttachment = new Ghre_Attachment();
                fileAttachment.Id = SnowFlakeSingle.Instance.NextId();
                fileAttachment.AttachFileName = file.FileName;
                fileAttachment.CreateBy = App.User.ID;
                fileAttachment.CreateTime = DateTime.Now;
                fileAttachment.AttachmentName = fileName;
                fileAttachment.AttachFileExtension = ext;
                fileAttachment.AttachFileSize = file.Length;
                fileAttachment.PhysicsPath = filePath;
                fileAttachment.AttachmentType = file.ContentType;
                //url = fileName + "." + ext;
                _context.Add(fileAttachment);
                _context.SaveChanges();

            }
        }
        return Success<string>(filePath);

    }

    [HttpPost, Route("Upload")]
    public async Task<ServiceResult<FileUploadResult>> UploadAsync(FileUpload upload)
    {
        string filePath = null;
        using var _context = ContextFactory.CreateContext();

        filePath = !string.IsNullOrEmpty(filePath) ? filePath : "upload";
        var ext = string.Empty;
        if (string.IsNullOrEmpty(upload.file.FileName) == false)
        {
            var dotPos = upload.file.FileName.LastIndexOf('.');
            ext = upload.file.FileName.Substring(dotPos + 1);
        }

        upload.fileName = upload.fileName ?? upload.file.FileName;

        string pathHeader = "wwwroot/files/" + filePath;
        if (!Directory.Exists(pathHeader))
            Directory.CreateDirectory(pathHeader);
        long fileName = SnowFlakeSingle.instance.getID();

        filePath = "/files/" + filePath + "/" + $"{upload.fileName}_{fileName}.{ext}";
        //var filepath = Path.Combine(pathHeader, file.FileName);
        using (var stream = global::System.IO.File.Create("wwwroot/" + filePath))
        {
            await upload.file.CopyToAsync(stream);
        }
        var fileAttachment = new Ghre_Attachment();
        fileAttachment.Id = SnowFlakeSingle.Instance.NextId();
        fileAttachment.AttachmentNo = upload.file.FileName;
        fileAttachment.AttachFileName = upload.file.FileName;
        fileAttachment.CreateBy = App.User.ID;
        fileAttachment.CreateTime = DateTime.Now;
        fileAttachment.AttachmentName = fileName.ToString();
        fileAttachment.AttachFileExtension = ext;
        fileAttachment.AttachFileSize = upload.file.Length;
        fileAttachment.PhysicsPath = filePath;
        fileAttachment.RelativePath = filePath;
        fileAttachment.FileURL = filePath;
        fileAttachment.ThumbnailPath = filePath;
        fileAttachment.AttachmentType = upload.file.ContentType;
        //url = fileName + "." + ext;
        _context.Add(fileAttachment);
        _context.SaveChanges();
        return Success(new FileUploadResult()
        {
            Id = fileAttachment.Id,
            AttachFileExtension = fileAttachment.AttachFileExtension,
            AttachFileName = fileAttachment.AttachFileName,
            AttachmentName = fileAttachment.AttachmentName,
            AttachmentNo = fileAttachment.AttachmentNo,
            FileURL = fileAttachment.FileURL,
            PhysicsPath = fileAttachment.PhysicsPath,
            RelativePath = fileAttachment.RelativePath,
            ThumbnailPath = fileAttachment.ThumbnailPath,
            AttachFileSize = fileAttachment.AttachFileSize,
        });

    }
    #endregion


    #region 获取图片
    /// <summary>
    /// 获取图片
    /// </summary>
    /// <param name="Id">主键ID</param>
    /// <returns></returns>
    [HttpGet("Download/{Id}"), AllowAnonymous]
    public async Task<IActionResult> Download(long Id)
    {
        try
        {
            var webRootPath = _hostingEnvironment.WebRootPath;

            using var _context = ContextFactory.CreateContext();
            var file = await _ghre_AttachmentServices.QueryById(Id);
            if (file == null)
                return Ok("找不到文件");

            var filePath = $"{webRootPath}{"\\" + file.PhysicsPath}";

            var contentTypDict = new Dictionary<string, string> {
                    {"jpg","image/jpeg"},
                    {"jpeg","image/jpeg"},
                    {"jpe","image/jpeg"},
                    {"png","image/png"},
                    {"gif","image/gif"},
                    {"ico","image/x-ico"},
                    {"tif","image/tiff"},
                    {"tiff","image/tiff"},
                    {"fax","image/fax"},
                    {"wbmp","image//vnd.wap.wbmp"},
                    {"rp","image/vnd.rn-realpix"}
                };
            var contentTypeStr = "image/jpeg";
            //未知的图片类型
            contentTypeStr = contentTypDict[file.AttachFileExtension];

            using (var sw = new FileStream(filePath, FileMode.Open))
            {
                var bytes = new byte[sw.Length];
                sw.Read(bytes, 0, bytes.Length);
                sw.Close();
                return new FileContentResult(bytes, contentTypeStr);
            }

        }
        catch (Exception ex)
        {
            return Ok($"下载异常：{ex.Message}");
        }
    }
    #endregion

    #region 分片上传
    /// <summary>
    /// 分片上传
    /// </summary>
    /// <param name="upload"></param>
    /// <returns></returns>
    [HttpPost("UploadLarge")]
    public async Task<ServiceResult<FileUploadResult>> UploadLargeAsync([FromForm] ChunkUpload upload)
    {
        return await _ghre_AttachmentServices.UploadVideoAsync(upload);
    }
    #endregion

}