using log4net;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace VIZ.Package.Module
{
    public class ThumbnailHelper
    {
        /// <summary>
        /// 日志
        /// </summary>
        private static readonly ILog log = LogManager.GetLogger(typeof(ThumbnailHelper));

        /// <summary>
        /// 生成高清缩略图片方法
        /// </summary>
        /// <param name="image"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public static Image GetThumbnail(Image image, int width, int height)
        {
            Bitmap bmp = new Bitmap(width, height);
            //从Bitmap创建一个System.Drawing.Graphics
            System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
            //设置 
            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //下面这个也设成高质量
            gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            //下面这个设成High
            gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            //把原始图像绘制成上面所设置宽高的缩小图
            System.Drawing.Rectangle rectDestination = new Rectangle(0, 0, width, height);

            gr.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
            return bmp;
        }

        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="path"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public static Image GetImage(string path, int width, int height)
        {
            try
            {
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                Image result = Image.FromStream(fs);
                fs.Close();
                result = GetThumbnail(result, result.Width/2, result.Height / 2);
                return result;
            }
            catch (Exception e)
            {
                return null;
            }
        }

        #region ---图片文件检测

        public static Boolean IsImage(string path)
        {
            try
            {
                if (IsImageByName(path))
                {
                    System.Drawing.Image img = System.Drawing.Image.FromFile(path);
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        /// <summary>
        /// 根据名称判断是否为图片
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static Boolean IsImageByName(string name)
        {
            try
            {
                if (name == null) return false;

                int pos = name.LastIndexOf(".");
                if (name.Length - pos - 1 < 3)
                    return false;

                string ext = name.Substring(pos + 1, name.Length - pos - 1);
                string[] imge = { "jpg", "jpeg", "png", "gif", "bmp", "TIFF", "tif" };

                return IsInIgnoreCase(ext, imge);
            }
            catch (Exception e)
            {
                return false;
            }

        }

        /// <summary>
        /// 不区分大小写进行判断
        /// </summary>
        /// <param name="source"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        private static bool IsInIgnoreCase(string source, params string[] list)
        {
            if (null == source) return false;

            IEnumerable<string> en = list.Where(i => string.Compare(i, source, StringComparison.OrdinalIgnoreCase) == 0);
            return en.Count() == 0 ? false : true;
        }
        /// <summary>
        /// 读取图片文件
        /// </summary>
        /// <param name="path">图片文件路径</param>
        /// <returns>图片文件</returns>
        private Bitmap ReadImageFile(String path)
        {
            Bitmap bitmap = null;
            try
            {
                FileStream fileStream = File.OpenRead(path);
                Int32 filelength = 0;
                filelength = (int)fileStream.Length;
                Byte[] image = new Byte[filelength];
                fileStream.Read(image, 0, filelength);
                System.Drawing.Image result = System.Drawing.Image.FromStream(fileStream);
                fileStream.Close();
                bitmap = new Bitmap(result);
            }
            catch (Exception ex)
            {
                //  异常输出
            }
            return bitmap;
        }

        /// <summary>
        /// 是否是视频
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool IsVideo(string filePath)
        {
            bool isVideo = false;
            string fileName = filePath;
            IList<string> formateList = new List<string> {
               "avi","flv","mpg","mpeg","mpe","m1v","m2v","mpv2","mp2v","dat","ts","tp","tpr","pva","pss","mp4","m4v",
                "m4p","m4b","3gp","3gpp","3g2","3gp2","ogg","mov","qt","amr","rm","ram","rmvb","rpm"};

            string[] Namesuffix = fileName.Split('.');

            if (Namesuffix.Length > 1)
            {
                if (formateList.Contains(Namesuffix[1]))
                {
                    isVideo = true;
                }
            }

            return isVideo;
        }


        /// <summary>
        /// 判断是否为视频流
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static bool IsVideo(Stream stream)
        {
            try
            {
                Image img = Image.FromStream(stream);
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 从完整路径中查找文件或文件夹名称
        /// </summary>
        /// <param name="path">完整路径</param>
        /// <returns></returns>
        public static string GetFileFolderName(string path)
        {
            // 如果没有路径，则返回空
            if (string.IsNullOrEmpty(path))
                return string.Empty;

            // 使所有斜杠成反斜杠
            var normalizedPath = path.Replace('/', '\\');

            // 找到最后一个反斜杠就是路径
            var lastIndex = normalizedPath.LastIndexOf('\\');

            // 如果找不到反斜线，则返回路径本身
            if (lastIndex <= 0)
                return path;

            // 最后一个反斜杠后返回名称
            return path.Substring(lastIndex + 1);
        }


        /// <summary>
        /// byte数组转换
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public static byte[] BitmapToGrayByte(Bitmap bitmap)
        {
            //// 申请目标位图的变量，并将其内存区域锁定
            //BitmapData bitmapDat = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
            //// 获取bmpData的内存起始位置
            //IntPtr intPtr = bitmapDat.Scan0;
            //byte[] image = new byte[bitmap.Width * bitmap.Height];//原始数据
            //                                                      // 将数据复制到byte数组中，
            //Marshal.Copy(intPtr, image, 0, bitmap.Width * bitmap.Height);
            ////解锁内存区域  
            //bitmap.UnlockBits(bitmapDat);
            //return image;

            // 1.先将BitMap转成内存流
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            // 2.再将内存流转成byte[]并返回
            byte[] bytes = new byte[ms.Length];
            ms.Read(bytes, 0, bytes.Length);
            ms.Dispose();
            return bytes;
        }

        #endregion
    }
}
