using Newtonsoft.Json;
using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using HttpResult = Qiniu.Http.HttpResult;

namespace AutoTurnOver.Utility
{
    /// <summary>
    /// 七牛云辅助类
    /// </summary>
    public class QiNiuCloudHelper
    {
        public static readonly string AccessKey = ConfigHelper.GetValue("QiNiu:AccessKey");
        public static readonly string SecretKey = ConfigHelper.GetValue("QiNiu:SecretKey");

        public static readonly string PicServerUrl = ConfigHelper.GetValue("QiNiu:CdnUrl");

        /// <summary>
        /// 七牛存储节点
        /// </summary>
        private static readonly string Bucket = "bailun-kaoqin-img";



        #region 上传文件
        public static async Task<string> UploadAsync(Stream stream, string saveFile)
        {
            var resultData = await UploadStreamAsync(stream, saveFile);
            if (resultData.Code != 200)
            {
                throw new Exception(resultData.RefText);
            }
            return PicServerUrl + "/" + saveFile;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="saveFile"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static async Task<HttpResult> UploadStreamAsync(string saveFile, byte[] content)
        {
            Mac mac = new Mac(AccessKey, SecretKey);

            // 设置上传策略，详见：https://developer.qiniu.com/kodo/manual/1206/put-policy
            PutPolicy putPolicy = new PutPolicy();
            putPolicy.Scope = Bucket + ":" + saveFile;  //覆盖式更新

            // putPolicy.SetExpires(3600);
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
            Config config = new Config();
            // 设置上传区域
            config.Zone = Zone.ZoneCnSouth;
            // 设置 http 或者 https 上传
            //config.UseHttps = true;
            //config.UseCdnDomains = true;
            //config.ChunkSize = ChunkUnit.U512K;
            FormUploader target = new FormUploader(config);
            var result = await target.UploadStream(new MemoryStream(content), saveFile, token, null);
            return result;
        }

        public static async Task<HttpResult> UploadStreamAsync(Stream stream, string saveFile)
        {
            Mac mac = new Mac(AccessKey, SecretKey);

            // 设置上传策略，详见：https://developer.qiniu.com/kodo/manual/1206/put-policy
            PutPolicy putPolicy = new PutPolicy();
            putPolicy.Scope = Bucket + ":" + saveFile;  //覆盖式更新

            // putPolicy.SetExpires(3600);
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
            Config config = new Config();
            // 设置上传区域
            config.Zone = Zone.ZoneCnSouth;
            // 设置 http 或者 https 上传
            //config.UseHttps = true;
            //config.UseCdnDomains = true;
            //config.ChunkSize = ChunkUnit.U512K;
            FormUploader target = new FormUploader(config);
            var result = await target.UploadStream(stream, saveFile, token, null);
            return result;
        }
        #endregion




        #region 获取七牛云缩略图，默认为550宽高

        /// <summary>
        /// 获取七牛云等比缩放缩略图，默认为550宽高，可用于放大的配置
        /// </summary>
        /// <param name="url">七牛云图片路径(clouddn.com格式）</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <param name="quantity">图片质量，0-100</param>
        /// <returns></returns>
        public static string GetQiNiuScaleThumbnail(string url, int width = 550, int height = 550, int quantity = 75)
        {
            var imgFunc = $"imageMogr2/thumbnail/!{width}x{height}r/blur/1x0/quality/{quantity}";
            if (url.Contains("clouddn.com") && !url.Contains("imageMogr2") && width > 0 && height > 0)  //代表七牛云图片路径
            {
                return url + "?" + imgFunc;
            }
            return url;
        }
        #endregion

        /// <summary>
        /// 获取缩略图
        /// </summary>
        /// <param name="url">七牛云图片路径(clouddn.com格式）</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns></returns>
        public static string GetQiNiuThumbnail(string url, int width = 100, int height = 100)
        {
            var imgFunc = $"imageView2/2/w/{width}/h/{height}/q/75|imageslim";
            if (url.Contains("clouddn.com") && !url.Contains("imageView2") && width > 0 && height > 0)  //代表七牛云图片路径
            {
                return url + "?" + imgFunc;
            }
            return url;
        }

        /// <summary>
        /// 根据指定宽高强制缩放
        /// </summary>
        /// <param name="url"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        public static string GetQiNiuScaleLimitSizeThumbnail(string url, int width = 550, int height = 550, int quantity = 75)
        {
            var imgFunc = $"imageMogr2/auto-orient/thumbnail/{width}x{height}!/blur/1x0/quality/{quantity}|imageslim";
            if (!string.IsNullOrWhiteSpace(url) && IsSupportQiniu(url) && !url.Contains("imageMogr2") && !url.Contains("imageView2") && width > 0 && height > 0)  //代表七牛云图片路径
            {
                return ReplaceLocalUrlToQiniuUrl(url) + "?" + imgFunc;
            }

            return ReplaceLocalUrlToQiniuUrl(url);
        }

        /// <summary>
        /// 本地文件路径替换为七牛云图片路径
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string ReplaceLocalUrlToQiniuUrl(string url)
        {

            if (!string.IsNullOrWhiteSpace(url) && url.Contains("http://oyd60abh0.bkt.clouddn.com"))
            {
                url = url.Replace("http://oyd60abh0.bkt.clouddn.com", "http://img.blsct.com");
            }
            return url;

        }

        /// <summary>
        /// 是否支持七牛云
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool IsSupportQiniu(string url)
        {
            if (!string.IsNullOrWhiteSpace(url))
            {
                return url.Contains("clouddn.com") || url.Contains("img.blsct.com");
            }
            return false;
        }

        #region 查找文件路径
        /// <summary>
        /// 查找文件路径
        /// </summary>
        /// <param name="saveFile"></param>
        /// <returns></returns>
        public static string CreatePublishListingUrl(string saveFile)
        {
            string url = "";
            try
            {
                url = DownloadManager.CreatePublishUrl(PicServerUrl, saveFile);
            }
            catch (Exception ex)
            {
                string error = ex.ToString();
            }
            return url;
        }
        #endregion

    }
    /// <summary>
    /// 七牛云图片格式
    /// </summary>
    public class QiNiuFileInfo
    {
        [JsonProperty("size")]
        public long Size { get; set; }
        [JsonProperty("format")]
        public string Format { get; set; }
        [JsonProperty("width")]
        public int Width { get; set; }
        [JsonProperty("height")]
        public int Height { get; set; }
        [JsonProperty("colorModel")]
        public string ColorModel { get; set; }
    }
}
