using FirmHttpDao;
using FWindSoft.Net.Http;
using FWindSoft.Tools.SystemUtil;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using SAGA.DotNetUtils.Data;

namespace Com.FirmLib.Bll
{
    /// <summary>
    /// 文件操作相关
    /// </summary>
    public class FileBll : BaseHttpBll
    {
        public FileBll() : base(@"")
        { }
        /// <summary>
        /// 获取键值
        /// </summary>
        /// <param name="levels"></param>
        /// <returns></returns>
        public string CreateKey(params string[] levels)
        {
            string timeStr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string baseStr = "default";
            if (levels.Any())
                baseStr=string.Join("-", levels);
            return $"{baseStr}-{SystemInfoUtil.GetMacAddress()}{timeStr}";
        }
        /// <summary>
        /// 创建带后缀的键值
        /// </summary>
        /// <param name="suffix">后缀</param>
        /// <param name="levels"></param>
        /// <returns></returns>
        public string CreateKey(string suffix,params string[] levels)
        {
            string tempKey = CreateKey(levels);
            return $"{tempKey}*{suffix}";
        }
        /// <summary>
        /// 获取键值的后缀
        /// </summary>
        /// <param name="fileKey"></param>
        /// <returns></returns>
        public string GetSuffix(string fileKey)
        {
            if (string.IsNullOrEmpty(fileKey))
                return string.Empty;
            var index = fileKey.LastIndexOf("*");
            if (index < 0 || index >= (fileKey.Count() - 1))
                return fileKey;
            return fileKey.Substring(index + 1);
        }
        #region 图片相关
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="validate"></param>
        /// <param name="key"></param>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public bool UploadImage(FileUrlValidate validate, string key, byte[] bytes)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(BllHttpSetting.Instance.FileUri);
            builder.Append(@"/image-service/common/image_upload");
            QueryParameters parameter = new QueryParameters();
            parameter.Add("systemId", validate.SystemId);
            parameter.Add("secret", validate.Secret);
            parameter.Add("key", key);
            parameter.Add("overwrite", true.ToString());
            builder.Append(parameter.ToString());
            HttpClient client = new HttpClient();
            var flag = false;
            using (MemoryStream stream = new MemoryStream(bytes))
            {
                var result = client.PostAsync(new Uri(builder.ToString(), UriKind.RelativeOrAbsolute), new StreamContent(stream));
                  var stringResult = HandlerTaskResponse(result, new RequestInfo(builder.ToString()));
                flag = HandlerResult(stringResult, null, (jo) => { this.ErrorMessage = jo["ResultMsg"].ToString(); });
            }


            return flag;
        }
        /// <summary>
        /// 获取图片地址
        /// </summary>
        /// <param name="validate"></param>
        /// <param name="key"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public string CreateImageUrl(FileUrlValidate validate, string key, double width, double height)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(BllHttpSetting.Instance.FileUri);
            builder.Append($"/image-service/common/image_get?systemId={validate.SystemId}&key={key}");
            if (width != 0)
            {
                builder.Append($"&width={width}");
            }
            if (height != 0)
            {
                builder.Append($"&width={height}");
            }
            return builder.ToString();
        }
        public string CreateImageUrl(FileUrlValidate validate, string key)
        {
            return CreateImageUrl(validate, key, 0, 0);
        }
        #endregion


        #region 文件相关
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="validate"></param>
        /// <param name="key"></param>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public bool UploadFile(FileUrlValidate validate, string key, byte[] bytes)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(BllHttpSetting.Instance.FileUri);
            builder.Append(@"/image-service/common/file_upload");
            QueryParameters parameter = new QueryParameters();
            parameter.Add("systemId", validate.SystemId);
            parameter.Add("secret", validate.Secret);
            parameter.Add("key", key);
            parameter.Add("overwrite", true.ToString());
            builder.Append(parameter.ToString());
            HttpClient client = HttpClientManager.CreateClient();
            var flag = false;
            using (MemoryStream stream = new MemoryStream(bytes))
            {
                var result = client.PostAsync(new Uri(builder.ToString(), UriKind.RelativeOrAbsolute), new StreamContent(stream));
                var stringResult = HandlerTaskResponse(result, new RequestInfo(builder.ToString()));
                flag = HandlerResult(stringResult, null, (jo) => { this.ErrorMessage = jo["ResultMsg"].ToString(); });
            }


            return flag;
        }
        /// <summary>
        /// 获取文件下载Url
        /// </summary>
        /// <param name="validate"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public string CreateFileUrl(FileUrlValidate validate, string key)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(BllHttpSetting.Instance.FileUri);
            builder.Append($"/image-service/common/file_get/{key}?systemId={validate.SystemId}");
           
            return builder.ToString();
        }
        #endregion
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public byte[] DownLoadFile(string url)
        {
            byte[] bytes = null;
            try
            {
                HttpClient client = HttpClientManager.CreateClient();
                var resultBytes = client.GetByteArrayAsync(url);
                bytes = resultBytes.Result;
                //var stream = resultStream.Result;
                //if (stream != null)
                //{
                //    bytes = new byte[stream.Length];
                //    stream.Read(bytes, 0, bytes.Length);
                //    // 设置当前流的位置为流的开始
                //    //stream.Seek(0, SeekOrigin.Begin);
                //    stream.Dispose();
                //}
                return bytes;
            }
            catch (Exception)
            {                
            }
            return bytes;
        }
        /// <summary>
        /// 下载文件到本地路径
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public bool DownLoadFile(string url,string path)
        {
            var bytes = DownLoadFile(url);
            if (bytes == null)
                return false;
            File.WriteAllBytes(path, bytes);
            return true;
        }
    }
}
