using System.IO;
using System.Threading.Tasks;
using GxPress.Common.Exceptions;
using GxPress.Common.Tools;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace GxPress.Api.AdminControllers
{
    /// <summary>
    /// 文件管理
    /// </summary>
    [Route("api/admin/file")]
    [ApiController]
    public class AdminFileController : ControllerBase
    {
        private readonly IWebHostEnvironment _environment;

        public AdminFileController(IWebHostEnvironment environment)
        {
            _environment = environment;
        }

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("upload")]
        public async Task<ResultPath> Upload(IFormFile file)
        {
            if (file == null) throw new BusinessException("请选择需要上传的文件");

            byte[] bytes;
            await using (var ms = new MemoryStream())
            {
                file.CopyTo(ms);
                bytes = ms.ToArray();
            }

            var saveResult = FileHelper.SaveFile(StringUtils.GetWebRootPath(_environment.WebRootPath), file.FileName,
                bytes);
            saveResult.AbsolutePath ="https://" + Request.Host.Host +
                                      (Request.Host.Port > 0 ? $":{Request.Host.Port}" : string.Empty) +
                                      saveResult.RelativePath;
            return saveResult;
        }

        //上传文件到本地缓存文件夹,返回一个预览地址
        //真正提交的时候把缓存文件异步保存到七牛云

        //下载,从七牛云下载文件?
        /// <summary>
        /// 上传用户Excel
        /// </summary>
        /// <returns></returns>
        [HttpPost("upload-user-excel")]
        public async Task<ResultPath> UploadUserExcel(IFormFile file)
        {

            if (file == null) throw new BusinessException("请选择需要上传的文件");
            byte[] bytes;
            await using (var ms = new MemoryStream())
            {
                file.CopyTo(ms);
                bytes = ms.ToArray();
            }

            var saveResult = FileHelper.SaveFile(StringUtils.GetWebRootPath(_environment.WebRootPath), file.FileName,
                bytes);
            saveResult.AbsolutePath = Request.Scheme + "://" + Request.Host.Host +
                                      (Request.Host.Port > 0 ? $":{Request.Host.Port}" : string.Empty) +
                                      saveResult.RelativePath;
            

            return saveResult;
        }
    }
}