using Microsoft.AspNetCore.Http;
using NPOI.HPSF;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
//using System.DrawingCore;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
namespace Shentun.Peis
{
    public class ImageHelper
    {
        /// 
        /// 将Base64字符串转换为图片并保存到本地
        /// 
        /// base64字符串
        /// 图片保存地址,如:/Content/Images/10000
        /// 
        public static string Base64StrToImage(string base64Str, string savePath)
        {
            var ret = "";
            try
            {
                base64Str = base64Str.Substring(base64Str.IndexOf(",") + 1);
                var bitmap = Base64StrToImage(base64Str);
                if (bitmap != null)
                {
                    string ImageSuffix = "";
                    if (ImageFormat.Png.Guid == bitmap.RawFormat.Guid)
                    {
                        ImageSuffix = ".png";
                    }
                    else if (ImageFormat.Gif.Guid == bitmap.RawFormat.Guid)
                    {
                        ImageSuffix = ".gif";
                    }
                    else
                    {
                        ImageSuffix = ".jpg";
                    }
                    savePath = savePath + ImageSuffix;
                    //创建文件夹
                    var folderPath = savePath.Substring(0, savePath.LastIndexOf('/'));
                    if (!Directory.Exists(folderPath))
                    {
                        Directory.CreateDirectory(folderPath);
                    }
                    //图片后缀格式
                    var suffix = savePath.Substring(savePath.LastIndexOf('.') + 1, savePath.Length - savePath.LastIndexOf('.') - 1).ToLower();
                    var suffixName = suffix == "png" ? ImageFormat.Png :
                        suffix == "jpg" || suffix == "jpeg" ? ImageFormat.Jpeg :
                        suffix == "bmp" ? ImageFormat.Bmp :
                        suffix == "gif" ? ImageFormat.Gif : ImageFormat.Jpeg;
                    //这里复制一份对图像进行保存,否则会出现“GDI+ 中发生一般性错误”的错误提示
                    var bmpNew = new Bitmap(bitmap);
                    //  bmpNew.Save(_hostingEnvironment.ContentRootPath + savePath, suffixName);
                    var s1 = Directory.GetCurrentDirectory();
                    string saveurl = Path.Combine(s1, savePath);
                    bmpNew.Save(saveurl, suffixName);
                    bmpNew.Dispose();
                    bitmap.Dispose();
                    ret = savePath;
                }
                else
                {
                    ret = "";
                }
            }
            catch (Exception ex)
            {
                ret = "";
            }
            return ret;
        }
        /// 
        /// 将Byte[]转换为图片并保存到本地
        /// 
        /// base64字符串
        /// 图片保存地址,如:/Content/Images/10000
        /// 
        public static string ByteToImage(byte[] photo, string savePath)
        {
            var ret = "";
            try
            {
                MemoryStream ms = new MemoryStream(photo);
                Bitmap bitmap = new Bitmap(ms);
                ms.Close();
                if (bitmap != null)
                {
                    string ImageSuffix = "";
                    if (ImageFormat.Png.Guid == bitmap.RawFormat.Guid)
                    {
                        ImageSuffix = ".png";
                    }
                    else if (ImageFormat.Gif.Guid == bitmap.RawFormat.Guid)
                    {
                        ImageSuffix = ".gif";
                    }
                    else
                    {
                        ImageSuffix = ".jpg";
                    }
                    savePath = savePath + ImageSuffix;
                    //创建文件夹
                    var folderPath = savePath.Substring(0, savePath.LastIndexOf('/'));
                    if (!Directory.Exists(folderPath))
                    {
                        Directory.CreateDirectory(folderPath);
                    }
                    //图片后缀格式
                    var suffix = savePath.Substring(savePath.LastIndexOf('.') + 1, savePath.Length - savePath.LastIndexOf('.') - 1).ToLower();
                    var suffixName = suffix == "png" ? ImageFormat.Png :
                        suffix == "jpg" || suffix == "jpeg" ? ImageFormat.Jpeg :
                        suffix == "bmp" ? ImageFormat.Bmp :
                        suffix == "gif" ? ImageFormat.Gif : ImageFormat.Jpeg;
                    //这里复制一份对图像进行保存,否则会出现“GDI+ 中发生一般性错误”的错误提示
                    var bmpNew = new Bitmap(bitmap);
                    //  bmpNew.Save(_hostingEnvironment.ContentRootPath + savePath, suffixName);
                    var s1 = Directory.GetCurrentDirectory();
                    string saveurl = Path.Combine(s1, savePath);
                    bmpNew.Save(saveurl, suffixName);
                    bmpNew.Dispose();
                    bitmap.Dispose();
                    ret = savePath;
                }
                else
                {
                    ret = "";
                }
            }
            catch (Exception ex)
            {
                ret = "";
            }
            return ret;
        }
        /// 
        /// 将Base64字符串转换为图片并保存到服务器
        /// 
        /// 物理路径
        /// 图片名
        /// 
        /// 登记ID  作为目录
        /// 检查ID  作为目录
        /// 
        public static string Base64StrToImageInAbsolutePath(string AbsolutePath, string fileName, string base64Str, string PatientRegisterId, string RegisterCheckId)
        {
            var ret = "";
            try
            {
                base64Str = base64Str.Substring(base64Str.IndexOf(",") + 1);
                string savePath = "";
                string hostPath = "";
                var bitmap = Base64StrToImage(base64Str);
                if (bitmap != null)
                {
                    string ImageSuffix = "";
                    if (ImageFormat.Png.Guid == bitmap.RawFormat.Guid)
                    {
                        ImageSuffix = ".png";
                    }
                    else if (ImageFormat.Gif.Guid == bitmap.RawFormat.Guid)
                    {
                        ImageSuffix = ".gif";
                    }
                    else if (ImageFormat.Bmp.Guid == bitmap.RawFormat.Guid)
                    {
                        ImageSuffix = ".bmp";
                    }
                    else
                    {
                        ImageSuffix = ".jpg";
                    }
                    string savaDirectory = $"{AbsolutePath}\\pacs\\{DateTime.Now.Year}\\{DateTime.Now.Month}\\{DateTime.Now.Day}\\{PatientRegisterId}\\{RegisterCheckId}";
                    savePath = $"{savaDirectory}\\{fileName + ImageSuffix}";
                    hostPath = $"/CheckPictureImg/pacs/{DateTime.Now.Year}/{DateTime.Now.Month}/{DateTime.Now.Day}/{PatientRegisterId}/{RegisterCheckId}/{fileName + ImageSuffix}";
                    if (!Directory.Exists(savaDirectory))
                    {
                        Directory.CreateDirectory(savaDirectory);
                    }
                    //图片后缀格式
                    var suffix = savePath.Substring(savePath.LastIndexOf('.') + 1, savePath.Length - savePath.LastIndexOf('.') - 1).ToLower();
                    var suffixName = suffix == "png" ? ImageFormat.Png :
                        suffix == "jpg" || suffix == "jpeg" ? ImageFormat.Jpeg :
                        suffix == "bmp" ? ImageFormat.Bmp :
                        suffix == "gif" ? ImageFormat.Gif : ImageFormat.Jpeg;
                    //这里复制一份对图像进行保存,否则会出现“GDI+ 中发生一般性错误”的错误提示
                    var bmpNew = new Bitmap(bitmap);
                    //  bmpNew.Save(_hostingEnvironment.ContentRootPath + savePath, suffixName);
                    var s1 = Directory.GetCurrentDirectory();
                    string saveurl = Path.Combine(s1, savePath);
                    bmpNew.Save(saveurl, suffixName);
                    bmpNew.Dispose();
                    bitmap.Dispose();
                    ret = hostPath;
                }
                else
                {
                    ret = "";
                }
            }
            catch (Exception ex)
            {
                ret = "";
            }
            return ret;
        }
        public static string Base64ToImageUseAbsolutePath(string absolutePath, string fileName, string base64Str, string patientRegisterId, string registerCheckId)
        {
            var ret = "";
            if (string.IsNullOrWhiteSpace(absolutePath))
            {
                throw new UserFriendlyException("absolutePath不能为空");
            }
            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new UserFriendlyException("文件名不能为空");
            }
            if (string.IsNullOrWhiteSpace(base64Str))
            {
                throw new UserFriendlyException("base64Str不能为空");
            }
            if (string.IsNullOrWhiteSpace(patientRegisterId))
            {
                throw new UserFriendlyException("PatientRegisterId不能为空");
            }
            if (string.IsNullOrWhiteSpace(registerCheckId))
            {
                throw new UserFriendlyException("RegisterCheckId不能为空");
            }
            string savaDirectory = $"{absolutePath}\\pacs\\{DateTime.Now.Year}\\{DateTime.Now.Month}\\{DateTime.Now.Day}\\{patientRegisterId}\\{registerCheckId}";
            if (!Directory.Exists(savaDirectory))
            {
                Directory.CreateDirectory(savaDirectory);
            }
            var savePath = $"{savaDirectory}\\{fileName}";
            var fullFileName = Base64ToImage(base64Str, savePath);
            var ImageSuffix = Path.GetExtension(fullFileName);
            var hostPath = $"/CheckPictureImg/pacs/{DateTime.Now.Year}/{DateTime.Now.Month}/{DateTime.Now.Day}/{patientRegisterId}/{registerCheckId}/{fileName + ImageSuffix}";
            ret = hostPath;
            return ret;
        }
        /// 
        /// 将Base64字符串转换为图片并保存到服务器
        /// 
        /// 物理路径
        /// 
        /// 登记ID  作为目录
        /// 检查ID  作为目录
        /// 图片名
        /// 
        public static string Base64StrToImageInAbsolutePath2(string AbsolutePath, IFormFile file, string PatientRegisterId, string RegisterCheckId, string ImageName)
        {
            var ret = "";
            try
            {
                string savePath = "";
                string hostPath = "";
                if (file == null || file.Length == 0)
                {
                    throw new UserFriendlyException("图片数据有误");
                }
                var ImageSuffix = Path.GetExtension(file.FileName);
                if (ImageSuffix == null)
                {
                    throw new UserFriendlyException("图片数据有误");
                }
                string fileFilt = ".gif|.jpg|.jpeg|.png";
                if (fileFilt.IndexOf(ImageSuffix.ToLower(), StringComparison.Ordinal) <= -1)
                {
                    throw new UserFriendlyException("请上传jpg、png、gif格式的图片");
                }
                savePath = AbsolutePath + "\\" + PatientRegisterId + "\\" + RegisterCheckId + "\\" + ImageName + ImageSuffix;
                hostPath = "/CheckPictureImg/" + PatientRegisterId + "/" + RegisterCheckId + "/" + ImageName + ImageSuffix;
                if (!Directory.Exists(AbsolutePath + "\\" + PatientRegisterId))
                {
                    Directory.CreateDirectory(AbsolutePath + "\\" + PatientRegisterId);
                }
                if (!Directory.Exists(AbsolutePath + "\\" + PatientRegisterId + "\\" + RegisterCheckId))
                {
                    Directory.CreateDirectory(AbsolutePath + "\\" + PatientRegisterId + "\\" + RegisterCheckId);
                }
                //图片后缀格式
                var suffix = savePath.Substring(savePath.LastIndexOf('.') + 1, savePath.Length - savePath.LastIndexOf('.') - 1).ToLower();
                var suffixName = suffix == "png" ? ImageFormat.Png :
                    suffix == "jpg" || suffix == "jpeg" ? ImageFormat.Jpeg :
                    suffix == "bmp" ? ImageFormat.Bmp :
                    suffix == "gif" ? ImageFormat.Gif : ImageFormat.Jpeg;
                //这里复制一份对图像进行保存,否则会出现“GDI+ 中发生一般性错误”的错误提示
                // var bmpNew = new Bitmap(bitmap);
                //  bmpNew.Save(_hostingEnvironment.ContentRootPath + savePath, suffixName);
                using (FileStream fs = System.IO.File.Create(savePath))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                //var s1 = Directory.GetCurrentDirectory();
                //string saveurl = Path.Combine(s1, savePath);
                //bmpNew.Save(saveurl, suffixName);
                //bmpNew.Dispose();
                //bitmap.Dispose();
                ret = hostPath;
            }
            catch (Exception ex)
            {
                ret = "";
            }
            return ret;
        }
        /// 
        /// 将Base64字符串转换为Image对象
        /// 
        /// base64字符串
        /// 
        public static Bitmap Base64StrToImage(string base64Str)
        {
            Bitmap bitmap = null;
            byte[] arr = Convert.FromBase64String(base64Str);
            using (MemoryStream ms = new MemoryStream(arr))
            {
                Bitmap bmp = new Bitmap(ms);
                ms.Close();
                bitmap = bmp;
            }
            return bitmap;
        }
        public static string Base64ToImage(string base64String, string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new UserFriendlyException("文件名不能为空");
            }
            if (string.IsNullOrWhiteSpace(base64String))
            {
                throw new UserFriendlyException("base64Str不能为空");
            }
            byte[] imageBytes = Convert.FromBase64String(base64String);
            using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
            {
                // Convert byte[] to Image
                using (Image image = Image.FromStream(ms))
                {
                    // Save the image to file system
                    string ImageSuffix = "";
                    if (ImageFormat.Png.Guid == image.RawFormat.Guid)
                    {
                        ImageSuffix = ".png";
                    }
                    else if (ImageFormat.Gif.Guid == image.RawFormat.Guid)
                    {
                        ImageSuffix = ".gif";
                    }
                    else if (ImageFormat.Bmp.Guid == image.RawFormat.Guid)
                    {
                        ImageSuffix = ".bmp";
                    }
                    else
                    {
                        ImageSuffix = ".jpg";
                    }
                    image.Save(filePath + ImageSuffix);
                    return filePath + ImageSuffix;
                }
            }
        }
        ///// 
        ///// 图片转换为base64
        ///// 
        ///// 
        ///// 
        //public static string ImageToBase64Str(string imgurl)
        //{
        //    string result = "";
        //    try
        //    {
        //        using (FileStream fs = new FileStream(imgurl, FileMode.Open, FileAccess.Read))
        //        {
        //            byte[] byteArray = new byte[fs.Length];
        //            fs.Read(byteArray, 0, byteArray.Length);
        //            result = Convert.ToBase64String(byteArray);
        //        }
        //    }
        //    catch(Exception ex)
        //    {
        //        result = "";
        //    }
        //    return result; 
        //}
        ///// 
        ///// 获取图片的Base64字符串
        ///// 
        ///// imageUrl
        ///// 
        //public static async Task GetImageBase64StringAsync(string imageUrl)
        //{
        //    // 创建 HttpClient 实例
        //    using (var httpClient = new HttpClient())
        //    {
        //        // 下载图片
        //        var response = await httpClient.GetAsync(imageUrl);
        //        var contentStream = await response.Content.ReadAsStreamAsync();
        //        // 将图片转换为 Base64 格式的字符串
        //        using (var memoryStream = new MemoryStream())
        //        {
        //            await contentStream.CopyToAsync(memoryStream);
        //            string base64String = Convert.ToBase64String(memoryStream.ToArray());
        //            return base64String;
        //        }
        //    }
        //}
        /// 
        /// 获取图片的Base64字符串
        /// 
        /// imageUrl
        /// 
        public static string GetImageBase64StringAsync(string imageUrl)
        {
            string result = "";
            try
            {
                using (FileStream fs = new FileStream(imageUrl, FileMode.Open, FileAccess.Read))
                {
                    byte[] byteArray = new byte[fs.Length];
                    fs.Read(byteArray, 0, byteArray.Length);
                    result = Convert.ToBase64String(byteArray);
                }
            }
            catch
            {
                result = "";
            }
            if (!string.IsNullOrEmpty(result))
                result = "data:image/jpeg;base64," + result;
            return result;
        }
        public static string SavePacsFile(string absolutePath, string sourceFileFullName, string PatientRegisterId, string RegisterCheckId, string imageName)
        {
            var ret = "";
            string savePath = "";
            string hostPath = "";
            if (string.IsNullOrWhiteSpace(absolutePath))
            {
                throw new UserFriendlyException("absolutePath不能为空");
            }
            if (string.IsNullOrWhiteSpace(sourceFileFullName))
            {
                throw new UserFriendlyException("文件名不能为空");
            }
            if (!File.Exists(sourceFileFullName))
            {
                throw new UserFriendlyException("文件名不存在");
            }
            var ImageSuffix = Path.GetExtension(sourceFileFullName);
            if (string.IsNullOrWhiteSpace(imageName))
            {
                throw new UserFriendlyException("图片名不能为空");
            }
            if (string.IsNullOrWhiteSpace(ImageSuffix))
            {
                throw new UserFriendlyException("图片数据后缀名不能为空");
            }
            if (string.IsNullOrWhiteSpace(PatientRegisterId))
            {
                throw new UserFriendlyException("PatientRegisterId不能为空");
            }
            if (string.IsNullOrWhiteSpace(RegisterCheckId))
            {
                throw new UserFriendlyException("RegisterCheckId不能为空");
            }
            string fileFilt = ".gif|.jpg|.jpeg|.png";
            if (fileFilt.IndexOf(ImageSuffix.ToLower(), StringComparison.Ordinal) <= -1)
            {
                throw new UserFriendlyException("请上传jpg、png、gif格式的图片");
            }
            savePath = absolutePath + "\\" + PatientRegisterId + "\\" + RegisterCheckId + "\\" + imageName + ImageSuffix;
            hostPath = "/CheckPictureImg/" + PatientRegisterId + "/" + RegisterCheckId + "/" + imageName + ImageSuffix;
            if (!Directory.Exists(absolutePath + "\\" + PatientRegisterId))
            {
                Directory.CreateDirectory(absolutePath + "\\" + PatientRegisterId);
            }
            if (!Directory.Exists(absolutePath + "\\" + PatientRegisterId + "\\" + RegisterCheckId))
            {
                Directory.CreateDirectory(absolutePath + "\\" + PatientRegisterId + "\\" + RegisterCheckId);
            }
            File.Copy(sourceFileFullName, savePath, true);//true允许覆盖
            ret = hostPath;
            return ret;
        }
    }
}