using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Drawing;
using System.IO;
using System.Net;

/// <summary>
/// Common 的摘要说明
/// </summary>
public class Common
{
    public Common()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
    /// <summary>
    /// 获取文本编辑器的数据，并自动上传远程图片
    /// </summary>
    /// <param name="uc">文本编辑器数据</param>
    /// <returns></returns>
    public string GetText(string str)
    {
        string mycontext = Regex.Replace(str.Replace("http://"+ System.Web.HttpContext.Current.Request.ServerVariables["HTTP_HOST"],""), @"src[^>]*[^/].(?:jpg|bmp|gif|png|jpeg|JPG|BMP|GIF|JPEG)(?:\""|\')", new MatchEvaluator(SaveYuanFile));
        
        return mycontext;
    }

   

    private string SaveYuanFile(Match m)
    {
        string imgurl = "";
        string matchstr = m.Value;//str[i].ToString();
        string tempimgurl = "";
        tempimgurl = matchstr.Substring(5);
        tempimgurl = tempimgurl.Substring(0, tempimgurl.IndexOf("\""));

        Regex re = new Regex(@"^http://*");
        if (re.Match(tempimgurl).Success)
        {
            matchstr = matchstr.Substring(5);
            matchstr = matchstr.Substring(0, matchstr.IndexOf("\""));

            //Response.Write(matchstr + "<br>");

            //远程文件保存路径
            string Folders = "~/uploadfiles/";
            string fullname = matchstr;

            string huozui = fullname.Substring(fullname.LastIndexOf("."));
            string filename = Common.GetFileName();
            string path = Folders + filename + huozui;
            //Folders+fullname.Substring(fullname.LastIndexOf("\\") + 1);

            if (System.IO.File.Exists(System.Web.HttpContext.Current.Request.MapPath(path)))
                System.IO.File.Delete(System.Web.HttpContext.Current.Request.MapPath(path));
            GetHttpFile(matchstr, System.Web.HttpContext.Current.Request.MapPath(path));
            imgurl = "src=\"" + path.Replace("~/", "/") + "\"";
        }
        else
        {
            imgurl = matchstr;
        }


        return imgurl;
    }


    string sException = null;
    private bool GetHttpFile(string sUrl, string sSavePath)
    {
        bool bRslt = false;
        WebResponse oWebRps = null;
        WebRequest oWebRqst = WebRequest.Create(sUrl);
        oWebRqst.Timeout = 100000;
        try
        {
            oWebRps = oWebRqst.GetResponse();
        }
        catch (WebException e)
        {
            sException = e.Message.ToString();
        }
        catch (Exception e)
        {
            sException = e.ToString();
        }
        finally
        {
            if (oWebRps != null)
            {
                BinaryReader oBnyRd = new BinaryReader(oWebRps.GetResponseStream(), System.Text.Encoding.GetEncoding("GB2312"));
                int iLen = Convert.ToInt32(oWebRps.ContentLength);
                FileStream oFileStream;
                try
                {
                    if (File.Exists(System.Web.HttpContext.Current.Request.MapPath("RecievedData.tmp")))
                    {
                        oFileStream = File.OpenWrite(sSavePath);
                    }
                    else
                    {
                        oFileStream = File.Create(sSavePath);
                    }
                    oFileStream.SetLength((Int64)iLen);
                    oFileStream.Write(oBnyRd.ReadBytes(iLen), 0, iLen);
                    oFileStream.Close();
                }
                catch (Exception ex)
                {
                    //bRslt= false;
                }
                finally
                {
                    oBnyRd.Close();
                    oWebRps.Close();

                }
                bRslt = true;

            }
        }
        return bRslt;

    }

    /// <summary>
    /// 文件上传
    /// </summary>
    /// <param name="fileupload">文件上传实例</param>
    /// <returns>保存的文件名称</returns>
    public static string UpLoadFile(FileUpload fileupload, string Folders, string w, string h)
    {
        //string Folders = "~/admin/eWebEditor/UpLoadFile/";
        string fullname = fileupload.PostedFile.FileName;
        if ((fullname == null) || (fullname.Equals("")))
            return "";
        string huozui = fullname.Substring(fullname.LastIndexOf("."));
        string filename = GetFileName();
        string p1 = Folders + filename + huozui;
        //Folders + fullname.Substring(fullname.LastIndexOf("\\") + 1); 
        string path = System.Web.HttpContext.Current.Server.MapPath(p1);

        if (System.IO.File.Exists(path))
            System.IO.File.Delete(path);
			
		if( w == "" || h == "" )
        	fileupload.PostedFile.SaveAs(path);
		else
		{
			if( Convert.ToInt32(w) == 0 || Convert.ToInt32(h) == 0 )
				fileupload.PostedFile.SaveAs(path);
			else
				Common.Upload( fileupload.PostedFile, "/uploadfiles", filename + huozui, Convert.ToInt32(w), Convert.ToInt32(h) );
		}

        return p1;
    }

        public static bool Upload(System.Web.HttpPostedFile file, string dirPath, string filepath, int width, int height)
        {
            bool Upload = true;

                System.Drawing.Image originalImage = System.Drawing.Image.FromStream(file.InputStream);

                int towidth = width;
                int toheight = height;

                int x = 0;
                int y = 0;
                int ow = originalImage.Width;
                int oh = originalImage.Height;

                string mode = "CUT";
                switch (mode)
                {
                    case "HW"://指定高宽缩放（可能变形）                
                        break;
                    case "W"://指定宽，高按比例                    
                        toheight = originalImage.Height * width / originalImage.Width;
                        break;
                    case "H"://指定高，宽按比例
                        towidth = originalImage.Width * height / originalImage.Height;
                        break;
                    case "AUTO"://指定高宽填充（不变形)
                        if (originalImage.Width / originalImage.Height >= width / height)
                        {
                            if (originalImage.Width > width)
                            {
                                towidth = width;
                                toheight = (originalImage.Height * width) / originalImage.Width;
                            }
                            else
                            {
                                towidth = originalImage.Width;
                                toheight = originalImage.Height;
                            }
                        }
                        else
                        {
                            if (originalImage.Height > height)
                            {
                                toheight = height;
                                towidth = (originalImage.Width * height) / originalImage.Height;
                            }
                            else
                            {
                                towidth = originalImage.Width;
                                toheight = originalImage.Height;
                            }
                        }
                        break;
                    case "CUT"://指定高宽裁减（不变形）                
                        if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                        {
                            oh = originalImage.Height;
                            ow = originalImage.Height * towidth / toheight;
                            y = 0;
                            x = (originalImage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = originalImage.Width;
                            oh = originalImage.Width * height / towidth;
                            x = 0;
                            y = (originalImage.Height - oh) / 2;
                        }
                        break;
                    default:
                        break;
                }

                System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);		//新建一个bmp图片

                Graphics g = System.Drawing.Graphics.FromImage(bitmap);							//新建一个画板

                g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;				//设置高质量插值法
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;				//设置高质量,低速度呈现平滑程度

                g.Clear(Color.Transparent);														//清空画布并以透明背景色填充

                g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);	//在指定位置并且按指定大小绘制原图片的指定部分

                //加水印
                //Font f = new System.Drawing.Font("宋体", 14F);

                //g.DrawString( "www.tian001.com", f, new SolidBrush( Color.Gray ), 4, 4 ); 
                //g.DrawString( "www.tian001.com", f, new SolidBrush( Color.FromArgb( 224, 224, 224 ) ), 3, 3 ); 

                try
                {
                    bitmap.Save(System.Web.HttpContext.Current.Server.MapPath(dirPath + "/" + filepath), System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                catch (System.Exception e)
                {
                    throw e;
                }
                finally
                {
                    originalImage.Dispose();
                    bitmap.Dispose();
                    g.Dispose();
                }

            return Upload;
        }

    public static string GetFileName()
    {
        System.Threading.Thread.Sleep(1000);
        string str1 = System.DateTime.Now.Year.ToString() + "-";

        if ((System.DateTime.Now.Month).ToString().Length < 2)
        {
            str1 += "0" + System.DateTime.Now.Month.ToString() + "-";
        }
        else
        {
            str1 += System.DateTime.Now.Month.ToString() + "-";
        }

        if ((System.DateTime.Now.Day).ToString().Length < 2)
        {
            str1 += "0" + System.DateTime.Now.Day.ToString() + "-";
        }
        else
        {
            str1 += System.DateTime.Now.Day.ToString() + "-";
        }

        if ((System.DateTime.Now.Hour).ToString().Length < 2)
        {
            str1 += "0" + System.DateTime.Now.Hour.ToString() + "-";
        }
        else
        {
            str1 += System.DateTime.Now.Hour.ToString() + "-";
        }

        if ((System.DateTime.Now.Minute).ToString().Length < 2)
        {
            str1 += "0" + System.DateTime.Now.Minute.ToString() + "-";
        }
        else
        {
            str1 += System.DateTime.Now.Minute.ToString() + "-";
        }

        if ((System.DateTime.Now.Second).ToString().Length < 2)
        {
            str1 += "0" + System.DateTime.Now.Second.ToString();
        }
        else
        {
            str1 += System.DateTime.Now.Second.ToString();
        }

        return str1;
    }
     
}
