using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using XYY.Core.Standard.AliYun;
using XYY.Core.Standard.Mvc;
namespace XYY.Api.Order.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FileController : ApiControllerBase
    {
        IAliYunPostFileSerivce aliYunPostFileSerivce;

        public FileController(IAliYunPostFileSerivce aliYunPostFileSerivce)
        {
            this.aliYunPostFileSerivce = aliYunPostFileSerivce;
        }

        [AllowAnonymous]
        public async Task<IActionResult> UpdateLoadFile()
        {
            
            //生成Guid文件防止重复
            var filelist = (await Request.ReadFormAsync()).Files;
            if (filelist != null && filelist.Count > 0)
            {
                var file = filelist[0];
                string fielName = Guid.NewGuid() + file.FileName.Substring(file.FileName.LastIndexOf('.'));
                string url =
                    aliYunPostFileSerivce.PostHttpFile(file.OpenReadStream(), fielName);
                return Content(url);
            }
            else
            {
                return Error("请上传一个文件");
            }
        }

        [AllowAnonymous]
        public async Task<IActionResult> UpdateLoadFileRestore(string q)
        {
            System.Net.WebClient webClient = new System.Net.WebClient();
            var data = await webClient.DownloadDataTaskAsync(q);
            Uri uri = new Uri(q);
            string fileName = HttpUtility.UrlDecode(uri.Segments.Last());
            return File(fileName, data);
        }
    }
}
