using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Net;

using System.IO;
using System.Drawing;
using System.Web.SessionState;
using System.Data;
using System.Data.SqlClient;
using DotNet.FrameWork.Data;
using GetCommand;
using DotNet.FrameWork.Common.Images;

namespace HteamDd.Web.ashx
{
    /// <summary>
    /// Dd_picture 的摘要说明
    /// </summary>
    public class Dd_picture : IHttpHandler,IRequiresSessionState
    {
        HaTeam.Dd.Model.Dd_Picture model = new HaTeam.Dd.Model.Dd_Picture();
        HaTeam.Dd.BLL.Dd_Picture bll = new HaTeam.Dd.BLL.Dd_Picture();
        HaTeam.Dd.BLL.Dd_Reprint reprint_bll = new HaTeam.Dd.BLL.Dd_Reprint();
        HaTeam.Dd.Model.Dd_Reprint reprint_model = new HaTeam.Dd.Model.Dd_Reprint();

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request["type"] == "Upimages" && context.Request["type"] != "reship_picture")
                {
                    SaveImage("/UpLoadImage/UploadPictures/", context);//图片的处理，传入图片的路径
                }
               else if (context.Request["type"] == "sumbitImages")
                {
                    if (context.Session["image_ID"] == null)
                    {
                        SaveImageToSql(context);//将图片保存到数据库
                    }
                    else
                    {
                        string update = "update Dd_Picture set Picture_Address=@address ,Picture_Discription=@discription,Picture_Tag=@tag where Picture_ID=@ID";
                        SqlParameter[] parmerters = { 
                                                    new SqlParameter("@ID",SqlDbType.Int),
                                                    new SqlParameter("@address",SqlDbType.NVarChar,1000),
                                                    new SqlParameter("@discription",SqlDbType.NVarChar,1000),
                                                    new SqlParameter("@tag",SqlDbType.VarChar,100)
                                                    };
                        parmerters[0].Value = context.Session["image_ID"].ToString();
                        string [] url_data=context.Session["update"].ToString().Split('$');
                        parmerters[1].Value =url_data[0]+"|"+url_data[1];
                        parmerters[2].Value = context.Request.Params["content"].ToString();
                        parmerters[3].Value = context.Request.Params["lable"].ToString();
                        if (DbHelperSQL.ExecuteSql(update, parmerters) != 0)
                        {
                            context.Response.Write("1");
                            context.Session.Remove("update");
                        }
                        else
                        {
                            context.Response.Write("-1");
                        }
                    }
                    
                }
            else if (context.Request["type"] == "reship_picture")//转载
            {
                reprint_model.Reprint_ArticleID = Convert.ToInt32(context.Request["ArticleID"]);
                reprint_model.Reprint_CopyFrom = Convert.ToInt32(context.Request["CopyFrom"]);
                reprint_model.Reprint_Count = 0;
                reprint_model.Reprint_Datetime = System.DateTime.Now;
                reprint_model.Reprint_Delete = 0;
                reprint_model.Reprint_Guid = Guid.NewGuid().ToString();
                reprint_model.Reprint_Lock = 0;
                reprint_model.Reprint_Order = Convert.ToInt32(context.Request["Order"]);
                reprint_model.Reprint_OriginID = Convert.ToInt32(context.Request["originID"]);
                reprint_model.Reprint_Remark = null;
                reprint_model.Reprint_State = 0;
                reprint_model.Reprint_type = 1;
                reprint_model.Reprint_UpDatetime = System.DateTime.Now;
                reprint_model.Reprint_UserID = Convert.ToInt32(context.Request["userID"]);
                reprint_model.Reprint_Verify = 0;
                int num = 0;
                try
                {
                    num = reprint_bll.Add(reprint_model);
                    if (num!=0)
                    {
                        num = 1;
                        SaveImageToSql(context);
                    } 
                }
                catch
                {
                    num = 0;
                }
                context.Response.Write(num);
            }
               else if (context.Request["type"] == "imge_url")//提交之前对图片路径的处理
                {
                    Image_Url_Proc(context);
                                        
                }
                else if (context.Request["type"] == "image_del")//编辑的时候删除图片
                {
                    string image_id = context.Request["image_del_id"].ToString();
                    string[] image_url = context.Session["update"].ToString().Split('$');
                    string[] path = image_url[0].Split('/');
                    string[] image_del_url = image_url[1].Split('|');
                    for (int i = 0; i < image_del_url.Length - 1; i++)
                    {
                        string image_name = image_del_url[i].Split('.')[0];
                        if (image_id == image_name)
                        {
                            DeleImage.image_server_del(image_url[0], image_del_url[i]);//删除服务器上的缩略图
                            DeleImage.image_server_del("/" + path[1] + "/UploadPictures/"+path[3]+"/"+path[4], image_del_url[i]);//删除服务器上的原图
                            image_del_url[i] = "";
                            break;
                        }
                    }
                    for (int i = 0; i < image_del_url.Length; i++)
                    {

                        if (image_del_url[i] != "")
                        {
                            context.Session["pic_del_addres"] += image_del_url[i] + "|";
                        }
                    }
                    if (context.Session["pic_del_addres"] != null)//图片没有删除完毕，还存在图片
                    {
                        context.Session["update"] = image_url[0] + "$" + context.Session["pic_del_addres"].ToString();
                        context.Session.Remove("pic_del_addres");//临时的session要清空
                    }
                    else//图片删除完毕，没有图片的情况
                    {
                        context.Session["update"] = image_url[0] + "$" + "";
                    }
                }
        }

        
        /// <summary>
        /// 对图片路径的处理进行方法提取
        /// </summary>
        /// <param name="context"></param>
        private static void Image_Url_Proc(HttpContext context)
        {
            if (context.Session["update"] == null)//此时是用户添加图片，不含编辑的情况
            {
                if (context.Session["ThumbnailPictures"] != null)
                {
                    context.Session["update"] = context.Session["ThumbnailPictures"].ToString() + "$" + context.Session["image_url"].ToString();
                    context.Response.Write(context.Session["ThumbnailPictures"].ToString() + ":" + context.Session["image_url"]);
                    context.Session.Remove("image_url");
                }
                else
                {
                    context.Response.Write("");
                }
            }
            else
            {
                string[] url_edit = context.Session["update"].ToString().Split('$');              
                if (context.Session["image_url"] != null)//在编辑的时候用户又新增上传图片
                {
                    //使用上传控件上传图片的路径+编辑传值过来的图片路径
                    context.Response.Write(url_edit[0] + ":" + context.Session["image_url"].ToString() + url_edit[1]);
                    context.Session["update"] = url_edit[0] +"$"+ context.Session["image_url"].ToString() + url_edit[1];
                    context.Session.Remove("image_url");//清除用户使用控件上传的图片路径，以备用户再次上传
                    
                }
                else//用户并没用使用上传控件上传图片的情况
                {
                    context.Response.Write(url_edit[0] + ":" + url_edit[1]);
                }
            }
        }

        /// <summary>
        /// 保存图片到服务器
        /// </summary>
        /// 2011-10-10
        /// <param name="url">图片的路径</param>
        /// 时间:2011-10-26 17:41
        protected void SaveImage(string url, HttpContext context)
        {
            //'遍历File表单元素
            HttpFileCollection files = HttpContext.Current.Request.Files;

            //'检查文件扩展名字
            //HttpPostedFile postedFile = files[iFile];
            HttpPostedFile postedFile = context.Request.Files["Filedata"]; //得到要上传文件
            string fileName, fileExtension, filesize;
            fileName = System.IO.Path.GetFileName(postedFile.FileName.ToString()); //得到文件名
            filesize = System.IO.Path.GetFileName(postedFile.ContentLength.ToString()); //得到文件大小
            if (fileName != "")
            {    
                fileExtension = System.IO.Path.GetExtension(fileName);//'获取扩展名
                string url_name = GetFileName();//生成的图片名
                string name_And_extension = url_name + fileExtension;//图片名加扩展名

                if (context.Session["update"] != null)
                {
                    string[] image_is_create = context.Session["update"].ToString().Split('$');
                    if (image_is_create[1] == "")//要创建新的文件夹
                    {
                        Image_is_createLoad(context, postedFile, name_And_extension);
                    }
                    else//保证用户编辑后的图片保存在源图片文件下，而不是存放在新的文件
                    {
                        string orig_virural_path = image_is_create[0] + "/" + name_And_extension;
                        string Thumbnail_path = HttpContext.Current.Server.MapPath("/") + "/"+orig_virural_path;                      
                        string[] arry_orig = image_is_create[0].Split('/');
                        string UploadPictures_path = HttpContext.Current.Server.MapPath("/") + "/" + arry_orig[1] + "/UploadPictures/" + arry_orig[3] + "/" + arry_orig[4];
                        
                        postedFile.SaveAs(UploadPictures_path + "/" + name_And_extension);
                        ImageThumbnail.ReducedImage(0.5, UploadPictures_path + "/" + name_And_extension);
                        MakeThumbnail(UploadPictures_path+ "/" + name_And_extension, Thumbnail_path, 150, 150, "Cut");//传入图片的缩略图路径
                    }
                }
                Image_is_createLoad(context, postedFile, name_And_extension);//用户直接发布而没进行编辑
                string pic = "";
                pic += name_And_extension + "|";
                pic += context.Session["image_url"];
                context.Session["image_url"] = pic; 
            }
            context.Response.Write(fileName + "上传成功");
        }

        /// <summary>
        /// 判断图片的路径是否进行创建新的路径
        /// </summary>
        /// <param name="context"></param>
        /// <param name="postedFile"></param>
        /// <param name="name_And_extension"></param>
        private static void Image_is_createLoad(HttpContext context, HttpPostedFile postedFile, string name_And_extension)
        {
            string origion_path = "";
            string[] virtual_UploadPictures = SavePic.virtual_path("/UpLoadImage/UploadPictures/").Split('#');
            string pic_document = SavePic.SavePicToDocument(virtual_UploadPictures[0], virtual_UploadPictures[1]);//在存放图片的物理路径下生成存放图片的指定文件夹
            if (pic_document != "")
            {
                origion_path = pic_document + "/" + name_And_extension;//源图片的物理路径
               
                postedFile.SaveAs(origion_path);
                ImageThumbnail.ReducedImage(0.5, origion_path);
                context.Session["UploadPictures"] = virtual_UploadPictures[1];
            }
            string[] virtual_Thumbnail = SavePic.virtual_path("/UpLoadImage/ThumbnailPictures/").Split('#');
            string Thumbnail_path = SavePic.SavePicToDocument(virtual_Thumbnail[0], virtual_Thumbnail[1]);
            if (Thumbnail_path != "")
            {
                MakeThumbnail(origion_path, Thumbnail_path + "/" + name_And_extension, 150, 150, "Cut");//传入图片的缩略图路径
                context.Session["ThumbnailPictures"] = virtual_Thumbnail[1];
            }
        }

        /// <summary>
        /// 保存图片数据到数据库
        /// </summary>
        /// <param name="imageName">图片名</param>
        /// <param name="imageAddress">图片地址</param>
        /// <param name="imageType">图片类型</param>
        /// 时间:2011-10-26 17:40
        protected void SaveImageToSql(HttpContext context)
        {
            
            string content = context.Request.Params["content"].ToString();
            string lable = context.Request.Params["lable"].ToString();
            string checkbox = context.Request.Params["check"].ToString();
            string url = context.Request.Params["address_url"].ToString();


            model.User_ID = Convert.ToInt32(context.Request.Params["userID"].ToString());
            model.Picture_Address = url;
            model.Picture_Discription = content;
            model.Picture_Tag = lable;
            model.Picture_PublishMode = 1;
            model.Picture_PutTop = Convert.ToBoolean(checkbox);
            model.Picture_Fever = 0;
            model.Picture_OriginId = model.User_ID;
            model.Picture_Guid = Convert.ToString(Guid.NewGuid());
            model.Picture_Datetime = DateTime.Now;
            model.Picture_UpDatetime = DateTime.Now;
            model.Picture_Verify = 0;
            model.Picture_Lock = 0;
            model.Picture_State = 0;
            model.Picture_Delete = 0;
            model.Picture_Count = 0;
            model.Picture_Order = 1;
            int _num = 0;
            try
            {
                _num = bll.Add(model);
                if (_num != 0)
                {
                    context.Session.Remove("update");//在添加成功的时候，清除本次会话
                    _num = 1;
                }
            }
            catch
            {
                _num = -1;
            }

            context.Response.Write(_num);
        }

        /// <summary>
        /// 得到随机图片名
        /// </summary>
        /// <returns></returns>
        public static string GetFileName()
        {
            Random rd = new Random();
            StringBuilder serial = new StringBuilder();
            serial.Append(DateTime.Now.ToString("yyMMddHHmmssff"));
            serial.Append(rd.Next(0, 9999).ToString());
            return serial.ToString();
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>    
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
            int towidth = width;
            int toheight = height;

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

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / 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;
            }
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}