
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using Microsoft.AspNetCore.Cors;
using System.Collections.Generic;
using System.Linq;
using Mall.WebApi.Filter;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.ThirdCore.Oss;

namespace Mall.WebApi.Controllers.File
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class FileController : ControllerBase
    {
        /// <summary>
        /// 上传文件到本地临时文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult LocalFileUploadImport()
        {
            try
            {
                var files = Request.Form.Files;
                if (files.Count == 0)
                {
                    return new ApiResult { resultCode = (int)ResultCode.Fail, message = "未选择文件", data = "" };
                }
                
                string filename = files[0].FileName;
                string fileExtention = System.IO.Path.GetExtension(files[0].FileName);
                //验证文件格式
                List<string> ExtList = new List<string>() {
                    ".xls",
                    ".xlsx",
                    ".csv"
                };
                if (!ExtList.Contains(fileExtention)) {
                    return new ApiResult { resultCode = (int)ResultCode.Fail, message = "文件格式有误", data = "" };
                }
                string path = Guid.NewGuid().ToString() + fileExtention; 
                string basepath = AppContext.BaseDirectory;
                string path_server = basepath + "\\upfile\\temporary\\" + path;
                if (!Directory.Exists(basepath + "\\upfile\\temporary"))
                {
                    Directory.CreateDirectory(basepath + "\\upfile\\temporary");
                }
                using (FileStream fstream = new FileStream(path_server, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    files[0].CopyTo(fstream);
                }

                return ApiResult.Success("", new { Name = filename, Path = path_server });
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "LocalFileUploadImport");
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 上传文件到本地临时文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UploadBlob()
        {
            try
            {
                var files = Request.Form.Files;
                if (files.Count == 0)
                {
                    return new ApiResult { resultCode = (int)ResultCode.Fail, message = "未选择文件", data = "" };
                }

                string filename = files[0].FileName;
                string fileExtention = System.IO.Path.GetExtension(files[0].FileName);
                //验证文件格式
                List<string> ExtList = new List<string>() {
                    ".p12"
                };
                if (!ExtList.Contains(fileExtention))
                {
                    return new ApiResult { resultCode = (int)ResultCode.Fail, message = "文件格式有误", data = "" };
                }
                string path = Guid.NewGuid().ToString() + fileExtention;
                string basepath = AppContext.BaseDirectory;
                string path_server = basepath + "\\App_Data\\Certs\\WeChatApp\\" + path;
                if (!Directory.Exists(basepath + "\\App_Data\\Certs\\WeChatApp\\"))
                {
                    Directory.CreateDirectory(basepath + "\\App_Data\\Certs\\WeChatApp\\");
                }
                using (FileStream fstream = new FileStream(path_server, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    files[0].CopyTo(fstream);
                }
                return ApiResult.Success("", new { Name = filename, Path = path_server });
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "UploadBlob");
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="request"></param>
        /// <param name="files"></param>
        /// <returns></returns>
        public virtual ApiResult UploadTencent()
        {
            try
            {
                var files = Request.Form.Files;
                if (files.Count == 0)
                {
                    return new ApiResult { resultCode = (int)ResultCode.Fail, message = "未选择文件", data = "" };
                }
                string filename = files[0].FileName;
                string fileExtention = System.IO.Path.GetExtension(files[0].FileName);
                string path = Guid.NewGuid().ToString() + fileExtention;
                string basepath = AppContext.BaseDirectory;
                string path_server = basepath + "\\SaleBefore\\Goods\\" + path;
                if (!Directory.Exists(basepath + "\\SaleBefore\\Goods\\"))
                {
                    Directory.CreateDirectory(basepath + "\\SaleBefore\\Goods\\");
                }
                using (FileStream fstream = new FileStream(path_server, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    files[0].CopyTo(fstream);
                }
                IOssService ossService = OssService.Get();
                OssResult result = ossService.UploadFile(path_server,null);
                try
                {
                    System.IO.File.Delete(path_server);
                }
                catch { 
                
                }
                return ApiResult.Success("", Common.Config.GetFileUrl(result.data.ToString()));
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "FileUpload");
                return ApiResult.Failed();
            }
        }
    }
}
