using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
using System.Net;

namespace RFrameGenerate.Common
{
    public class GraphicHelper
    {
        public GraphicHelper()
        {

        }

        public GraphicHelper(int obstructlinenum, int obstructdotnum, bool isBorder, string rgb, bool isfliter = false)
        {
            this.obstructlinenum = obstructlinenum;
            this.isBorder = isBorder;
            this.obstructdotnum = obstructdotnum;
            this.isfliter = isfliter;
            this.rgb = rgb;
        }

        private int obstructlinenum = 25;
        private int obstructdotnum = 100;
        private bool isBorder = true;
        private string rgb = string.Empty;
        private bool isfliter = false;

        /// <summary>
        /// 创建验证码的图片
        /// </summary>
        /// <param name="containsPage">要输出到的page对象</param>
        /// <param name="validateNum">验证码</param>
        public byte[] CreateGraphic(string validateCode)
        {
            Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);

                try
                {
                    if (!string.IsNullOrEmpty(rgb))
                    {
                        List<string> rgbarr = rgb.Split(',').ToList();
                        Color customColor = Color.FromArgb(Convert.ToInt32(rgbarr[0]), Convert.ToInt32(rgbarr[1]), Convert.ToInt32(rgbarr[2]));
                        g.Clear(customColor);
                    }
                }
                catch
                {

                }

                if (isfliter)
                {
                    g.Clear(Color.FromArgb(255, Color.White));
                }

                //画图片的干扰线
                for (int i = 0; i < obstructlinenum; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
                 Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 2);
                //画图片的前景干扰点
                for (int i = 0; i < obstructdotnum; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                if (isBorder)
                {
                    //画图片的边框线
                    g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                }


                //保存图片数据
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                //输出图片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }

        public byte[] ValidImg(int len)
        {
            return CreateGraphic(RadomCode.DigitalCode(len));
        }

        /// <summary>
        /// 截取图片方法
        /// </summary>
        /// <param name="url">图片地址</param>
        /// <param name="savePath">保存路径</param>
        public static void CutImage(string url, string savePath)
        {
            int getX = 0;//截取宽度
            int getY = 0;//截取长度
            int beginX = 0;//开始位置-X
            int beginY = 0;//开始位置-Y

            try
            {
                if (!string.IsNullOrEmpty(url))
                {
                    //Configure JPEG Compression Engine   
                    EncoderParameters encoderParams = new EncoderParameters();
                    long[] quality = new long[1];
                    quality[0] = 75;
                    EncoderParameter encoderParam = new EncoderParameter(Encoder.Quality, quality);
                    encoderParams.Param[0] = encoderParam;

                    ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo jpegICI = null;
                    for (int x = 0; x < arrayICI.Length; x++)
                    {
                        if (arrayICI[x].FormatDescription.Equals("JPEG"))
                        {
                            jpegICI = arrayICI[x];
                            break;
                        }
                    }

                    Bitmap bitmap = new Bitmap(url);//原图

                    var fileName = url.Substring(url.LastIndexOf('\\')).Replace("\\", "");//文件名称
                    var fileExt = fileName.Substring(fileName.LastIndexOf('.'));//后缀名
                    fileName = fileName.Remove(fileName.LastIndexOf("."));
                    if (bitmap.Width > bitmap.Height)
                    {
                        getX = bitmap.Height;
                        getY = bitmap.Height;
                        beginX = (bitmap.Width - bitmap.Height) / 2;
                        beginY = 0;
                    }
                    else
                    {
                        getX = bitmap.Width;
                        getY = bitmap.Width;
                        beginX = 0;
                        beginY = (bitmap.Height - bitmap.Width) / 2;
                    }

                    Bitmap destBitmap = new Bitmap(getX, getY);//目标图

                    Rectangle destRect = new Rectangle(0, 0, getX, getY);//矩形容器
                    Rectangle srcRect = new Rectangle(beginX, beginY, getX, getY);

                    Graphics g = Graphics.FromImage(destBitmap);
                    g.DrawImage(bitmap, destRect, srcRect, GraphicsUnit.Pixel);
                    destBitmap.Save(savePath + "//" + fileName + "_thumbnail.jpg", jpegICI, encoderParams);
                    //return savePath + "\\" + "*" + fileName.Split('.')[0] + "." + fileExt;
                    g.Dispose();

                }
            }
            catch
            {

            }

        }

        /// <summary>
        /// 图片压缩算法
        /// </summary>
        public static bool GetPicThumbnail(string sFile, string outPath, int flag)
        {

            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;
            //以下代码为保存图片时，设置压缩质量  
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100  
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.ToUpper().Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    iSource.Save(outPath, jpegICIinfo, ep);//dFile是压缩后的新路径  
                }
                else
                {
                    iSource.Save(outPath, tFormat);
                }
                return true;
            }
            catch (Exception ex)
            {
                //RFramework.Log.Write(System.Threading.Thread.CurrentThread.ManagedThreadId + " >>GraphicHelper.GetPicThumbnail File: " + sFile);
                //RFramework.Log.Write(System.Threading.Thread.CurrentThread.ManagedThreadId + " >>GraphicHelper.GetPicThumbnail Message: " + ex.Message);
                return false;
            }
            finally
            {
                iSource.Dispose();
            }
        }

        protected bool CreatImage(string content, string path)
        {
            Bitmap img = null;
            bool res = false;
            if (content != "")
            {
                img = new Bitmap((int)Math.Ceiling((content.Length * 18.0)), 30);
                Graphics g = Graphics.FromImage(img);
                try
                {
                    g.Clear(Color.White);
                    Font font = new Font("Arial", 15.5f, (FontStyle.Bold));
                    LinearGradientBrush brush =
                        new LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.Black, Color.DarkRed,
                            1.2f, true);
                    g.DrawString(content, font, brush, 2, 2);
                    g.DrawRectangle(new Pen(Color.Silver), 0, 0, img.Width - 1, img.Height - 1);
                    img.Save(path + ".jpg");
                    res = true;
                }
                catch (Exception ex)
                {
                    res = false;
                }
                finally
                {
                    g.Dispose();
                    img.Dispose();
                }
            }
            return res;

        }


        public static Metafile ToMetafile(Image image)
        {
            try
            {
                using (Bitmap bitmap = new Bitmap(image))
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        bitmap.Save(memoryStream, ImageFormat.Jpeg);
                        Metafile mf = new Metafile(memoryStream);
                        return mf;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static string MadeCode1(string storeLogoImage, string sistributionBackgroundImgae, string qrcodeImage, string username, string content, string savePath)
        {
            string url = "";
            ImageCodecInfo jpegICI = ImageCodecInfo.GetImageEncoders().Where(a => a.FormatDescription.Equals("JPEG")).FirstOrDefault();
            EncoderParameters encoderParams = new EncoderParameters();
            encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, new long[] { 500 }); ;


            if (string.IsNullOrEmpty(storeLogoImage)) return "";
            if (string.IsNullOrEmpty(sistributionBackgroundImgae)) return "";
            if (string.IsNullOrEmpty(qrcodeImage)) return "";
            if (string.IsNullOrEmpty(savePath)) return "";

            Bitmap baseImg = new Bitmap(500, 540);
            Bitmap StoreLogoImage = null;
            Bitmap DistributionBackgroundImgae = null;
            Bitmap QrcodeImage = null;
            //Bitmap PrintsImage = null;
            Image curStoreLogoImage = null;
            Image curDistributionBackgroundImgae = null;
            Image curQrcodeImage = null;
            //Image curPrintsImage = null;
            Graphics g = null;
            var brush = new SolidBrush(Color.FromArgb(102, 102, 102)); // new SolidBrush(ColorTranslator.FromHtml("#666"));
            var brushname = new SolidBrush(Color.Red);
            Font font = new Font("宋体", 12f, FontStyle.Regular);

            try
            {
                #region image
                if (storeLogoImage.ToLower().Contains("http://"))
                {
                    StoreLogoImage = DownloadPicture(storeLogoImage, -1);
                }
                else
                {
                    StoreLogoImage = new Bitmap(AppDomain.CurrentDomain.BaseDirectory + storeLogoImage);
                }

                if (sistributionBackgroundImgae.ToLower().Contains("http://"))
                {
                    DistributionBackgroundImgae = DownloadPicture(sistributionBackgroundImgae, -1);
                }
                else
                {
                    DistributionBackgroundImgae = new Bitmap(AppDomain.CurrentDomain.BaseDirectory + sistributionBackgroundImgae);
                }
                if (qrcodeImage.ToLower().Contains("http://"))
                {
                    QrcodeImage = DownloadPicture(qrcodeImage, -1);
                }
                else
                {
                    QrcodeImage = new Bitmap(AppDomain.CurrentDomain.BaseDirectory + qrcodeImage);
                }

                //if (printsImage.ToLower().Contains("http://"))
                //{
                //    PrintsImage = DownloadPicture(printsImage, -1);
                //}
                //else
                //{
                //    PrintsImage = new Bitmap(AppDomain.CurrentDomain.BaseDirectory + printsImage);
                //}
                #endregion

                //生成缩略图
                curStoreLogoImage = StoreLogoImage.GetThumbnailImage(90, 90, null, IntPtr.Zero);

                int curDistributionBackgroundImgaeHeight = (320 * DistributionBackgroundImgae.Height) / DistributionBackgroundImgae.Width;
                curDistributionBackgroundImgae = DistributionBackgroundImgae.GetThumbnailImage(320, curDistributionBackgroundImgaeHeight, null, IntPtr.Zero);
                curQrcodeImage = QrcodeImage.GetThumbnailImage(200, 200, null, IntPtr.Zero);
                //curPrintsImage = PrintsImage.GetThumbnailImage(150, 150, null, IntPtr.Zero);

                //生成矩形
                Rectangle srcRect = new Rectangle(16, 30, curStoreLogoImage.Width, curStoreLogoImage.Height);
                Rectangle disBackgroundRect = new Rectangle(0, 137, 500, 300);
                Rectangle qrcodeRect = new Rectangle(150, 200, 200, 200);
                //Rectangle printsRect = new Rectangle(275, 410, 150, 150);

                g = Graphics.FromImage(baseImg);
                SizeF sizeF;
                g.Clear(Color.White);
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.CompositingQuality = CompositingQuality.HighQuality;
                //消除锯齿 
                g.SmoothingMode = SmoothingMode.AntiAlias;
                //生成图片
                g.DrawImage(curStoreLogoImage, srcRect, new Rectangle(0, 0, curStoreLogoImage.Width, curStoreLogoImage.Height), GraphicsUnit.Pixel);
                g.DrawString("我是", font, brush, 112, 45);
                sizeF = g.MeasureString("我是", font);
                g.DrawString(username, font, brushname, 112 + sizeF.Width, 45);
                g.DrawString("我为", font, brush, 112, 70);
                g.DrawString(content, font, brushname, 112 + sizeF.Width, 70);
                sizeF = g.MeasureString("代言" + content, font);
                g.DrawString("代言", font, brush, 112 + sizeF.Width, 70);

                g.DrawImage(curDistributionBackgroundImgae, disBackgroundRect, new Rectangle(0, 0, curDistributionBackgroundImgae.Width, curDistributionBackgroundImgae.Height), GraphicsUnit.Pixel);
                g.DrawImage(curQrcodeImage, qrcodeRect, new Rectangle(0, 0, curQrcodeImage.Width, curQrcodeImage.Height), GraphicsUnit.Pixel);
                //g.DrawImage(curPrintsImage, printsRect, new Rectangle(0, 0, curPrintsImage.Width, curPrintsImage.Height), GraphicsUnit.Pixel);

                g.DrawString("长按指纹，识别图中二维码购买", font, brush, 150, disBackgroundRect.Height + disBackgroundRect.Y + 20);
                g.DrawString("关注我们加入有礼品", font, brush, 180, disBackgroundRect.Height + disBackgroundRect.Y + 50);
                savePath = AppDomain.CurrentDomain.BaseDirectory + savePath + "\\" + DateTime.Now.ToString("yyyy-MM-dd");
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                url = savePath + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + RadomCode.DigitalCode(3) + ".jpg";
                baseImg.Save(url, jpegICI, encoderParams);
                return url;
            }
            catch
            {
                return "";
            }
            finally
            {
                if (g != null) g.Dispose();
                if (baseImg != null) baseImg.Dispose();
                if (StoreLogoImage != null) StoreLogoImage.Dispose();
                if (DistributionBackgroundImgae != null) DistributionBackgroundImgae.Dispose();
                if (QrcodeImage != null) QrcodeImage.Dispose();
                //if (PrintsImage != null) PrintsImage.Dispose();
                if (curStoreLogoImage != null) curStoreLogoImage.Dispose();
                if (curDistributionBackgroundImgae != null) curDistributionBackgroundImgae.Dispose();
                if (curQrcodeImage != null) curQrcodeImage.Dispose();
                //if (curPrintsImage != null) curPrintsImage.Dispose();
                if (brush != null) brush.Dispose();
                if (brushname != null) brushname.Dispose();
                if (font != null) font.Dispose();

            }
        }

        public static bool MadeRQ(string logoImage, string backgroundImage, string qrcodeImage, string distname, string storeName, string savePath)
        {
            if (Directory.Exists(Path.GetDirectoryName(savePath)) != true)
                System.IO.Directory.CreateDirectory(Path.GetDirectoryName(savePath));

            Bitmap baseImg = new Bitmap(533, 800);
            Bitmap StoreLogoImage;
            Bitmap BackgroundImgae;
            Bitmap QrcodeImage;
            string imgerror = string.Empty;
            try
            {
                #region image
                if (logoImage.ToLower().Contains("http://"))
                {
                    StoreLogoImage = DownloadPicture(logoImage, -1);
                    imgerror += "Logo,";
                }
                else
                {
                    StoreLogoImage = new Bitmap(AppDomain.CurrentDomain.BaseDirectory + logoImage);
                    imgerror += "Logo,";
                }

                if (backgroundImage.ToLower().Contains("http://"))
                {
                    BackgroundImgae = DownloadPicture(backgroundImage, -1);
                    imgerror += "背景图片,";
                }
                else
                {
                    BackgroundImgae = new Bitmap(AppDomain.CurrentDomain.BaseDirectory + backgroundImage);
                    imgerror += "背景图片,";
                }
                if (qrcodeImage.ToLower().Contains("http://"))
                {
                    QrcodeImage = DownloadPicture(qrcodeImage, -1);
                    imgerror += "二维码,";
                }
                else
                {
                    QrcodeImage = new Bitmap(AppDomain.CurrentDomain.BaseDirectory + qrcodeImage);
                    imgerror += "二维码,";
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception("Message:" + ex.Message + ",错误信息:" + imgerror);
            }
            Graphics g = Graphics.FromImage(baseImg);
            var brush = new SolidBrush(Color.FromArgb(102, 102, 102));
            var redbursh = new SolidBrush(Color.Red);
            Font font = new Font("宋体", 12f, FontStyle.Regular);

            Image cutStoreLogoImage = StoreLogoImage.GetThumbnailImage(100, 100, null, IntPtr.Zero);
            Image cutBackgroundImgae = BackgroundImgae.GetThumbnailImage(baseImg.Width, baseImg.Height /*(baseImg.Width * BackgroundImgae.Height) / BackgroundImgae.Height*/, null, IntPtr.Zero);
            Image cutQrcodeImage = QrcodeImage.GetThumbnailImage(250, 250, null, IntPtr.Zero);

            var rectBackground = new Rectangle(0, 0, cutBackgroundImgae.Width, cutBackgroundImgae.Height);
            var rectLogo = new Rectangle(20, 20, cutStoreLogoImage.Width, cutStoreLogoImage.Height);
            var rectQR = new Rectangle(20, cutBackgroundImgae.Height - cutQrcodeImage.Height - 20, cutQrcodeImage.Width, cutQrcodeImage.Height);
            int mynameY = 10, mynameX = 10;
            SizeF size;
            try
            {
                g.DrawImage(cutBackgroundImgae, rectBackground);
                g.DrawString("我是", font, brush, rectLogo.Width + rectLogo.X + mynameX, rectLogo.Y + mynameY);
                size = g.MeasureString("我是", font);
                g.DrawString(distname, font, redbursh, rectLogo.Width + rectLogo.X + mynameX + size.Width, rectLogo.Y + mynameY);
                size = g.MeasureString("我是" + distname, font);
                g.DrawString("我为", font, brush, rectLogo.Width + rectLogo.X + mynameX, rectLogo.Y + mynameY * 4);
                size = g.MeasureString("我为", font);
                g.DrawString(storeName, font, redbursh, rectLogo.Width + rectLogo.X + mynameX + size.Width, rectLogo.Y + mynameY * 4);
                size = g.MeasureString("我为" + storeName, font);
                g.DrawString("代言", font, brush, rectLogo.Width + rectLogo.X + mynameX + size.Width, rectLogo.Y + mynameY * 4);
                g.DrawImage(cutStoreLogoImage, rectLogo);
                g.DrawImage(cutQrcodeImage, rectQR);
                g.DrawString("长按指纹，识别图中二维码购买", font, brush, rectQR.X + rectQR.Width + mynameX, rectQR.Y + rectQR.Width * 3 / 4);
                g.DrawString("关注我们加入有礼品", font, brush, rectQR.X + rectQR.Width + mynameX, rectQR.Y + mynameY * 3 + rectQR.Width * 3 / 4);
                if (File.Exists(savePath) == true)
                    File.Delete(savePath);
                baseImg.Save(savePath);
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (StoreLogoImage != null) StoreLogoImage.Dispose();
                if (BackgroundImgae != null) BackgroundImgae.Dispose();
                if (QrcodeImage != null) QrcodeImage.Dispose();
                if (cutStoreLogoImage != null) cutStoreLogoImage.Dispose();
                if (cutBackgroundImgae != null) cutBackgroundImgae.Dispose();
                if (cutQrcodeImage != null) cutQrcodeImage.Dispose();
                if (g != null) g.Dispose();
                if (brush != null) brush.Dispose();
                if (redbursh != null) redbursh.Dispose();
                if (font != null) font.Dispose();
            }
        }

        /// <summary>
        /// 获取文件流
        /// </summary>
        /// <param name="picUrl"></param>
        /// <param name="savePath"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static Bitmap DownloadPicture(string picUrl, int timeOut)
        {
            WebResponse response = null;
            Stream stream = null;
            Bitmap bit = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(picUrl);
                if (timeOut != -1) request.Timeout = timeOut;
                response = request.GetResponse();
                stream = response.GetResponseStream();
                bit = new Bitmap(stream);
            }
            finally
            {
                if (stream != null) response.Close();
                if (response != null) response.Close();
            }
            return bit;
        }
    }



}
