
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;
using Mall.Module.BaseSetUp;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Authorization;

namespace Mall.WebApi.Controllers.File
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class FileController : ControllerBase
    {
        MallBaseModule mallBaseModule = new MallBaseModule();

        /// <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);
                }

                #region 查询后台文件存储配置
                string q = Request.Query["MallBaseId"];
                int MallBaseId = Convert.ToInt32(q == "" ? "0" : q);
                bool IsDefault = true;
                if (MallBaseId > 0)
                {
                    var fileModel = mallBaseModule.GetFileStoreList(new Model.Entity.BaseSetUp.RB_File_Store { MallBaseId = MallBaseId, IsDefault = 1 }).FirstOrDefault();
                    if (fileModel != null)
                    {
                        if (fileModel.StoreType == Common.Enum.MallBase.StoreTypeEnum.Tencent)
                        {
                            if (string.IsNullOrEmpty(fileModel.Region))
                            {
                                fileModel.Region = Common.Config.TencentOSS.GetStringValue("region");
                            }
                            if (string.IsNullOrEmpty(fileModel.SecretId))
                            {
                                fileModel.SecretId = Common.Config.TencentOSS.GetStringValue("accessKeyId");
                            }
                            if (string.IsNullOrEmpty(fileModel.SecretKey))
                            {
                                fileModel.SecretKey = Common.Config.TencentOSS.GetStringValue("accessKeySecret");
                            }
                            if (string.IsNullOrEmpty(fileModel.Bucket))
                            {
                                fileModel.Bucket = Common.Config.TencentOSS.GetStringValue("bucket");
                            }
                            IsDefault = false;
                            IOssService ossService = OssService.GetTencent(fileModel.Region, fileModel.SecretId, fileModel.SecretKey, fileModel.Bucket);
                            OssResult result = ossService.UploadFile(path_server, null);
                            try
                            {
                                System.IO.File.Delete(path_server);
                            }
                            catch
                            {
                            }
                            return ApiResult.Success("", Common.Config.GetFileUrl(result.data.ToString()));
                        }
                        else if (fileModel.StoreType == Common.Enum.MallBase.StoreTypeEnum.Alicloud)
                        {
                            IsDefault = false;
                            if (string.IsNullOrEmpty(fileModel.Region))
                            {
                                fileModel.Region = Common.Config.AliOSS.GetStringValue("region");
                            }
                            if (string.IsNullOrEmpty(fileModel.SecretId))
                            {
                                fileModel.SecretId = Common.Config.AliOSS.GetStringValue("accessKeyId");
                            }
                            if (string.IsNullOrEmpty(fileModel.SecretKey))
                            {
                                fileModel.SecretKey = Common.Config.AliOSS.GetStringValue("accessKeySecret");
                            }
                            if (string.IsNullOrEmpty(fileModel.Bucket))
                            {
                                fileModel.Bucket = Common.Config.AliOSS.GetStringValue("bucket");
                            }
                            IOssService ossService = OssService.GetAli(fileModel.Region, fileModel.SecretId, fileModel.SecretKey, fileModel.Bucket);
                            OssResult result = ossService.UploadFile(path_server, null);
                            try
                            {
                                System.IO.File.Delete(path_server);
                            }
                            catch
                            {
                            }
                            return ApiResult.Success("", Common.Config.GetAliFileUrl(result.data.ToString()));
                        }
                    }
                }
                #endregion
                if (IsDefault)
                {
                    IOssService ossService = OssService.GetTencent();
                    OssResult result = ossService.UploadFile(path_server, null);
                    try
                    {
                        System.IO.File.Delete(path_server);
                    }
                    catch
                    {
                    }
                    return ApiResult.Success("", Common.Config.GetFileUrl(result.data.ToString()));
                }
                return ApiResult.Failed();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "FileUpload");
                return ApiResult.Failed();
            }
        }
    }
}
