using SystemTop= System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using TVShoppingCallCenter_ZLJ.Models.Dtos;
using System.Utility.File;
using System.Utility.Encrypt;

namespace TVShoppingCallCenter_ZLJ.Controllers
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class UploadController : BaseController
    {
        #region 影响阅读的默认图
        string defaultfile = "data:image/jpeg;base64,[encoded data, 7076 characters]";
        string defaultphoto = "data:image/jpeg;base64,[encoded data, 13320 characters]";
        #endregion

        private readonly string uploadKey="10838107";
        private readonly IConfiguration _configuration;
        private readonly IHostingEnvironment _hostingEnvironment;
        public UploadController(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
        {
            _configuration = configuration;
            _hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="cols"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Post(IFormCollection cols)
        {
            try
            {
                string type = cols["uploadtype"];
                if (string.IsNullOrEmpty(type)) type = _configuration["appSettings:FileType"].ToString();
                string webRootPath = _hostingEnvironment.WebRootPath;
                string contentRootPath = _hostingEnvironment.ContentRootPath;
                // url 路径
                string urlpre = "/api/Upload/";
                // 物理路径
                string pre = _configuration["appSettings:PhysicalPath"].ToString();
                var path = (string.IsNullOrEmpty(pre) ? contentRootPath + "/upload/" : pre) + type + "/";
                path = path + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";

                FileHelper.CreateNewFolder(path);
                List<FileClass.FileInfo> strfiles = new List<FileClass.FileInfo>();
                
                string filesjson = cols["filesjson"];
                if (!string.IsNullOrEmpty(filesjson))
                {
                    List<FileClass.Base64Info> jsons = filesjson.ToList<FileClass.Base64Info>();
                    foreach (var l in jsons)
                    {
                        int delLength = l.fileurl.IndexOf(',') + 1;
                        string strimg = l.fileurl.Substring(delLength, l.fileurl.Length - delLength);
                        byte[] bData = Convert.FromBase64String(strimg);

                        string fileExt = Path.GetExtension(l.filename); //文件扩展名，含“.”
                        long fileSize = bData.Length; //获得文件大小，以字节为单位

                        string newFileName = Guid.NewGuid().ToString().Replace("-", "") + fileExt; //随机生成新的文件名

                        using (var stream = new FileStream(path + newFileName, FileMode.Create))
                        {
                            await stream.WriteAsync(bData, 0, bData.Length);
                        }
                        string filemd5 = FileHelper.GetMD5HashFromFile(path + newFileName);
                        string key = EncryptHelper.EncryptDES(path + newFileName + "||" + l.filename, uploadKey);


                        FileClass.FileInfo fl = new FileClass.FileInfo();
                        fl.fileext = fileExt;
                        fl.filename = l.filename;
                        fl.filesize = fileSize.ToString();
                        fl.fileurl = urlpre + key;

                        try
                        {
                            string slname = FileHelper.GetThumbImg(path, newFileName, fileExt);
                            if (slname != "")
                            {
                                string slkey = EncryptHelper.EncryptDES(path + slname + "||" + l.filename, uploadKey);
                                fl.filesmallurl = urlpre + slkey;
                            }
                        }
                        catch (Exception ex)
                        {
                            LogDefault.Error("生成缩略图失败，原因：" + ex.ToString());
                            fl.filesmallurl = urlpre + key;
                        }

                        fl.filemd5 = filemd5;

                        strfiles.Add(fl);
                    }
                }

                foreach (var file in cols.Files)
                {
                    string fileName = file.FileName;
                    string fileExt = Path.GetExtension(fileName); //文件扩展名，含“.”
                    long fileSize = file.Length; //获得文件大小，以字节为单位
                    string newFileName = Guid.NewGuid().ToString().Replace("-","") + fileExt; //随机生成新的文件名

                    using (var stream = new FileStream(path + newFileName, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                    string filemd5 = FileHelper.GetMD5HashFromFile(path + newFileName);
                    string key = EncryptHelper.EncryptDES(path + newFileName + "||" + fileName,uploadKey);

                    FileClass.FileInfo fl = new FileClass.FileInfo();
                    fl.fileext = fileExt;
                    fl.filename = fileName;
                    fl.filesize = fileSize.ToString();
                    fl.fileurl = urlpre + key;

                    try
                    {
                        string slname = FileHelper.GetThumbImg(path, newFileName, fileExt);
                        if (slname != "")
                        {
                            string slkey = EncryptHelper.EncryptDES(path + slname + "||" + fileName, uploadKey);
                            fl.filesmallurl = urlpre + slkey;
                        }
                    }
                    catch (Exception ex)
                    {
                        LogDefault.Error("生成缩略图失败，原因：" + ex.ToString());
                        fl.filesmallurl = urlpre + key;
                    }

                    fl.filemd5 = filemd5;

                    strfiles.Add(fl);
                }
                return Success("上传成功", strfiles);
            }
            catch (Exception ex)
            {
                return Error("上传失败，原因：" + ex.ToString()+ex.StackTrace);
            }
        }

        
        /// <summary>
        /// 下载附件
        /// </summary>
        /// <param name="key"></param>
        /// <param name="isdel"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("{key}")]
        public IActionResult Get(string key, int isdel = 0)
        {
            isdel = 0;
            string pathname = EncryptHelper.DecryptDES(key,uploadKey);
            string[] strs = pathname.Split("||");
            if (isdel > 0)
            {
                if(FileHelper.delFile(strs[0]))
                    return Success("删除成功");
                else
                    return Success("删除失败");
            }

            if (FileHelper.FileExists(strs[0]))
            {
                //var stream = System.IO.File.OpenRead(strs[0]);

                var fileExt = Path.GetExtension(strs[1]);
                ////获取文件的ContentType
                //var provider = new FileExtensionContentTypeProvider();
                //var memi = provider.Mappings[fileExt];

                //return File(stream, memi, Path.GetFileName(strs[1]));

                //IE在处理 Response Header 的时候，对header的长度限制在150字节左右。而一个汉字编码成UTF-8是9个字节，那么17个字便是153个字节，所以会
                SystemTop.Net.Mime.ContentDisposition cd = new SystemTop.Net.Mime.ContentDisposition
                {
                    FileName = GetSubstr(strs[1]),   // Path.GetFileName(strs[1]),
                    Inline = false  // false = prompt the user for downloading;  true = browser to try to show the file inline
                };
                Response.Headers.Add("Content-Disposition", cd.ToString());
                Response.Headers.Add("X-Content-Type-Options", "nosniff");
               
                return File(SystemTop.IO.File.ReadAllBytes(strs[0]), "application/octet-stream");
            }
            else
            {
                string[] filetypes = new string[] { ".jpg", ".jpeg", ".gif", ".bmp", ".png" };

                var defaultbase64 = defaultfile;
                if (filetypes.Contains(Path.GetExtension(strs[1])))
                {
                    defaultbase64 = defaultphoto;
                }

                int delLength = defaultbase64.IndexOf(',') + 1;
                string strimg = defaultbase64.Substring(delLength, defaultbase64.Length - delLength);
                byte[] bData = Convert.FromBase64String(strimg);

                //return File(bData, "image/jpeg", "error.jpg");

                SystemTop.Net.Mime.ContentDisposition cd = new SystemTop.Net.Mime.ContentDisposition
                {
                    FileName = "error.jpg",
                    Inline = false  // false = prompt the user for downloading;  true = browser to try to show the file inline
                };
                Response.Headers.Add("Content-Disposition", cd.ToString());
                Response.Headers.Add("X-Content-Type-Options", "nosniff");

                return File(bData, "image/jpeg");
            }
        }


        /// <summary>
        /// 获取缩短的文件标题 - 例如：aaaaaa..bbbb.pfd
        /// </summary>
        /// <param name="unicodeString"></param>
        /// <returns></returns>
        public string GetSubstr(string str)
        {

            try
            {
                //类型 .pdf - 截取.后面的字符串
                string Extension = str.Substring(str.LastIndexOf("."));
                //名称 - 截取.前面的字符串
                string title = str.Remove(str.LastIndexOf("."));
                //名称不为空
                if (!string.IsNullOrEmpty(title))
                {
                    if (title.Length > 9)
                    {
                        //IE在处理 Response Header 的时候，对header的长度限制在150字节左右。而一个汉字编码成UTF-8是9个字节，那么17个字便是153个字节，所以会
                        string Str_before = title.Substring(0, 5);
                        string Str_after = title.Substring(title.Length - 4, 4);
                        //拼接字符串 例如：aaaaaa..bbbb.pfd
                        return Str_before + ".." + Str_after + Extension;
                    }
                    return title + Extension;
                }
                return str;
            }
            catch (Exception ex)
            {
                return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
        }

    }
}