using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.DrawingCore.Imaging;
using System.IO;
using Library;
using System.Collections;
using LitJson;
using System.Globalization;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using Aliyun.OSS;

namespace MySystem.Areas.Api.Controllers
{
    [Area("Api")]
    [Route("Api/[controller]/[action]")]
    public class PublicMethodController : BaseController
    {
        public PublicMethodController(IHttpContextAccessor accessor) : base(accessor)
        {
        }
        #region 图片验证码
        public FileContentResult CheckCode()
        {
            string code = function.get_Random(4);
            var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 120, 40);
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Gif);
            function.WriteCookie(_accessor.HttpContext, "checkcode", code);
            return File(stream.ToArray(), "image/gif");
        }
        #endregion

        #region 图片验证码
        public FileContentResult PictureCode(string Tag = "")
        {
            string code = function.get_Random(4);
            var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 120, 40);
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Gif);
            RedisDbconn.Instance.Set(Tag, code);
            RedisDbconn.Instance.SetExpire(Tag, 600);
            return File(stream.ToArray(), "image/jpg");
        }
        #endregion


        #region 前端上传oss返回参数
        public JsonResult OssInfo(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string dir = data["dir"].ToString(); //文件上传路径        
            if (string.IsNullOrEmpty(data["dir"].ToString()))
            {
                return Json(new AppResultJson() { Status = "1", Info = "文件上传路径不能为空" });
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            var OssUrl = OssHost;
            var AccessKeyId = OssKey;
            var AccessKeySecret = OssSecret;
            var endpoint = "https://" + OssEndpoint;

            // 构造OssClient实例。 endpoint 格式:https://oss-cn-beijing.aliyuncs.com
            var ossClient = new OssClient(endpoint, AccessKeyId, AccessKeySecret);
            var config = new PolicyConditions();
            config.AddConditionItem(PolicyConditions.CondContentLengthRange, 1, 1024L * 1024 * 1024 * 5);// 文件大小范围：单位byte
            config.AddConditionItem(MatchMode.StartWith, PolicyConditions.CondKey, dir);
            var expire = DateTimeOffset.Now.AddMinutes(30);// 过期时间

            // 生成 Policy，并进行 Base64 编码
            var policy = ossClient.GeneratePostPolicy(expire.LocalDateTime, config);
            var policyBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(policy));

            // 计算签名
            var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(AccessKeySecret));
            var bytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(policyBase64));
            var Signature = Convert.ToBase64String(bytes);

            Obj.Add("OssUrl", OssUrl);
            Obj.Add("AccessKeyId", AccessKeyId);
            // Obj.Add("AccessKeySecret", AccessKeySecret);
            Obj.Add("Policy", policyBase64);
            Obj.Add("Expiration", expire);
            Obj.Add("Signature", Signature);
            Obj.Add("dir", dir);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        #endregion



        #region 编辑器上传图片

        public object EditorUpload([FromForm] IFormCollection rf)
        {
            //文件保存目录路径
            String savePath = "/up/v2/";

            //文件保存目录URL
            String saveUrl = "/up/v2/";

            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable();
            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

            //最大文件大小
            long maxSize = 1073741824000;

            IFormFile imgFile = rf.Files["imgFile"];
            if (imgFile == null)
            {
                showError("请选择文件。");
            }

            String dirPath = function.getPath(AppConfig.Oss.PathName + savePath);
            if (!Directory.Exists(dirPath))
            {
                //showError("上传目录不存在。");
                Directory.CreateDirectory(dirPath);
            }

            String fileName = imgFile.FileName;
            String dirName = "";
            if (String.IsNullOrEmpty(dirName))
            {
                if (fileName.ToLower().EndsWith(".mp4") || fileName.ToLower().EndsWith(".mp3"))
                {
                    dirName = "media";
                }
                else
                {
                    dirName = "image";
                }
            }
            if (!extTable.ContainsKey(dirName))
            {
                showError("目录名不正确。");
            }

            String fileExt = Path.GetExtension(fileName).ToLower();

            if (imgFile.Length > maxSize)
            {
                showError("上传文件大小超过限制。");
            }

            if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");
            }

            //创建文件夹
            dirPath += dirName + "/";
            saveUrl += dirName + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
            dirPath += ymd + "/";
            saveUrl += ymd + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            String filePath = dirPath + newFileName;
            using var fs = new FileStream(filePath, FileMode.Create);
            imgFile.CopyTo(fs);
            String fileUrl = saveUrl + newFileName;
            if (dirName != "media")
            {
                if (!function.check_pic(filePath))
                {
                    System.IO.File.Delete(filePath);
                    return null;
                }
                if (function.getImgRule(filePath)["width"] > 2000)
                {
                    String newFileName_sl = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + "_sl" + fileExt;
                    function.imgcut(2000, filePath, dirPath + newFileName_sl);
                    System.IO.File.Delete(filePath);
                    fileUrl = saveUrl + newFileName_sl;
                }
            }

            Hashtable hash = new Hashtable();
            hash["error"] = 0;
            hash["url"] = AppConfig.Oss.SourceHost + "/" + AppConfig.Oss.PathName + fileUrl;
            OssHelper.Instance.ScanQueue(fileUrl, "");
            return JsonMapper.ToJson(hash);
        }

        private object showError(string message)
        {
            Hashtable hash = new Hashtable();
            hash["error"] = 1;
            hash["message"] = message;
            return JsonMapper.ToJson(hash);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }



        #endregion

        #region 系统-上传文件

        public JsonResult UploadFile([FromForm] IFormCollection rf)
        {
            IFormFile imgFile = rf.Files["file"];
            string path = MySystemLib.SystemPublicFuction.GetFilePath(imgFile, AppConfig.Oss.PathName + "/uploadfile/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/");
            OssHelper.Instance.ScanQueue(path, "");
            Dictionary<string, string> obj = new Dictionary<string, string>();
            obj.Add("FileName", path);
            return Json(obj);
        }

        #endregion

        #region 系统-上传图片
        public JsonResult UploadPhoto([FromForm] IFormCollection rf)
        {
            IFormFile imgFile = rf.Files["Icon"];
            string Icon = MySystemLib.SystemPublicFuction.GetPicPath(imgFile, AppConfig.Oss.PathName + "/upload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/");
            OssHelper.Instance.ScanQueue(Icon, "");
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Icon });
        }

        #endregion

        #region 系统-上传图片
        public JsonResult UploadPhotoByBase64(string value)
        {
            value = value.Replace("data:image/png;base64,", "");
            string base64str = HttpUtility.UrlDecode(value).Replace(" ", "+");
            string dummyData = base64str.Replace("%", "").Replace(",", "").Replace(" ", "+");
            if (dummyData.Length % 4 > 0)
            {
                dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
            }
            string Icon = function.base64StringToImage(dummyData, "/" + AppConfig.Oss.PathName + "/upload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/", "MT" + function.MD5_16(Guid.NewGuid().ToString()) + ".png");
            // OssHelper.Instance.ScanQueue(Icon, "");
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Icon });
        }
        #endregion

        #region 系统-layui上传文件
        public JsonResult LayUIUpload([FromForm] IFormCollection rf, string Path = "", string Resize = "")
        {
            IFormFile imgFile = rf.Files[0];
            string Icon = MySystemLib.SystemPublicFuction.GetFilePath(imgFile, Path + "/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/", false);
            string piccut = "";
            if (!string.IsNullOrEmpty(Resize) && (imgFile.FileName.ToLower().EndsWith(".png") || imgFile.FileName.EndsWith(".jpg")))
            {
                JsonData data = JsonMapper.ToObject(Resize);
                int width = int.Parse(data["width"].ToString());
                int height = int.Parse(data["height"].ToString());
                int quality = int.Parse(data["quality"].ToString());
                piccut = Icon.Replace(".", "s.");
                function.imgcut2(width, height, function.getPath(Icon), function.getPath(piccut));
                System.IO.File.Delete(function.getPath(Icon));
            }
            else
            {
                piccut = Icon;
            }
            return Json(new AppResultJson() { Status = "1", Info = "", Data = piccut });
        }

        #endregion

        #region 图片转base64

        public string ImgToBase64(string path)
        {
            path = HttpUtility.UrlDecode(path);
            return function.imageToBase64String(function.getPath(path));
        }

        #endregion
    }
}