using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Drawing;
using System.Web.SessionState;
using System.Data.SqlClient;
using System.Data;
using DotNet.FrameWork.Data;
using GetCommand;

namespace HteamDd.Web.ashx
{
    /// <summary>
    /// Dd_person_image 的摘要说明
    /// </summary>
    public class Dd_person_image : IHttpHandler,IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (context.Request["type"] == "Upimages")
            {
                SaveImage("/UpLoadImage/HeadImg/Origin_pictures/", context);//图片的处理，传入图片的路径
            }
            else if (context.Request["type"] == "imge_personal")
            {
                if (context.Session["image_pernal"] != null)
                {
                    string head_image = Del_personal_img(context.Request["userID"].ToString());//删除用户已有的图片
                    if (head_image != "")
                    {
                        //DeleImage.image_server_del(head_image[1] +"/"+head_image[2]+"/"+ head_image[3], head_image[4]);
                        string[] Origin = head_image.Split('/');
                        DeleImage.personal_image_del(head_image);//保存成功的同时，删除用户已有的缩略图像
                        DeleImage.personal_image_del("/" + Origin[1] + "/" + Origin[2] + "/Origin_pictures/" + Origin[4] + "/" + Origin[5] + "/" + Origin[6]);//删除用户已有的源图像
                    }
                    context.Response.Write(context.Session["image_pernal"]);
                }
                else
                {
                    context.Response.Write("");
                }
                
            }
            else if (context.Request["type"] == "submit")
            {                          
                string sql = "update Dd_User set User_BlogName=@blogName,User_Remark=@introduce,User_HeadPhoto=@image_url where User_ID=@ID";
                SqlParameter [] parmeters={
                                          new SqlParameter("@ID",SqlDbType.Int),
                                          new SqlParameter("@blogName",SqlDbType.NVarChar,50),
                                          new SqlParameter("@introduce",SqlDbType.NText),
                                          new SqlParameter("@image_url",SqlDbType.NVarChar,100)};
                parmeters[0].Value = context.Request["user_ID"].ToString();
                parmeters[1].Value = context.Request["user_call"].ToString();
                parmeters[2].Value = context.Request["uer_disprict"].ToString();
                if (context.Session["image_pernal"] ==null)//首先判断用户是否对自己的图片进行修改，session为空，说明没更改
                {
                    string orign=Del_personal_img(parmeters[0].Value.ToString());
                    if (orign != "")
                    {
                        parmeters[3].Value = orign;//如果用户对图片未做更改,只保存修改过的信息，并保存源图片路径                      
                    }
                    else
                    {
                        parmeters[3].Value = "NULL";//说明用户以前也没上传过图片
                    }
                    if (DbHelperSQL.ExecuteSql(sql, parmeters) != 0)
                    {
                        Get_UserMess(context, parmeters[0].Value.ToString());
                        context.Response.Write("11");
                    }
                    else
                    {
                        context.Response.Write("00");
                    }
                    context.Response.End();
                }
                else 
                {
                    string[] url_iamge = context.Session["image_pernal"].ToString().Split(':');    
                    if (url_iamge[1] == "")
                    {
                        parmeters[3].Value = "";
                    }
                    else
                    {
                        parmeters[3].Value = url_iamge[0] + url_iamge[1];
                        if (DbHelperSQL.ExecuteSql(sql, parmeters) != 0)
                        {
                            Get_UserMess(context, parmeters[0].Value.ToString());
                            context.Session.Remove("image_pernal");//对session进行清除，清除本次会话
                            context.Response.Write("11");                           
                        }
                        else
                        {
                            context.Response.Write("00");
                        }
                    }                    
                }
                
            }
        }

        /// <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_path = GetFileName();//生成的图片名
                //string image_url = context.Server.MapPath(url) + url_path + fileExtension;
                string img_NameAndExtentsion = url_path + fileExtension;
                string[] virtual_Head_Origin= SavePic.virtual_path(url).Split('#');
                string creat_Origin_document = SavePic.SavePicToDocument(virtual_Head_Origin[0], virtual_Head_Origin[1]);
                string origion_path = string.Empty;
                if (creat_Origin_document != "")
                {
                    origion_path = creat_Origin_document + "/" + img_NameAndExtentsion;
                    postedFile.SaveAs(origion_path);
                }
                string[] virtual_Head_Thumbnail = SavePic.virtual_path("/UpLoadImage/HeadImg/Thumbnail_pics/").Split('#');
                string creat_Thumbnai_document = SavePic.SavePicToDocument(virtual_Head_Thumbnail[0],virtual_Head_Thumbnail[1]);
                if (creat_Thumbnai_document != "")
                {
                    MakeThumbnail(origion_path, creat_Thumbnai_document+"/"+img_NameAndExtentsion, 64, 64, "Cut");//传入图片的缩略图路径
                }
                context.Session["image_pernal"] = virtual_Head_Thumbnail[1]+ "/" + ":" + img_NameAndExtentsion;             

            }
            context.Response.Write(fileName + "上传成功");
           
        }

        /// <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();
            }
        }


        private string Del_personal_img(string user_ID)
        {
            string user_image = "select User_HeadPhoto from Dd_User where User_ID=@ID";
            SqlParameter parm_image = new SqlParameter("@ID", SqlDbType.Int);
            string url = "";
            parm_image.Value = user_ID;
            if (DbHelperSQL.GetSingle(user_image, parm_image) != null)
            {
                url = DbHelperSQL.GetSingle(user_image, parm_image).ToString();
            }
            else
            {
                url = "";
            }
            return url;
        }

        /// <summary>
        /// 用户修改信息的同时把修改的信息写入cookie
        /// </summary>
        /// <param name="context"></param>
        /// <param name="ID"></param>
        public void Get_UserMess(HttpContext context ,string ID)
        {
            string usersql = "select User_BlogName,User_Email from Dd_User where User_ID=@ID ";
            SqlParameter Mess = new SqlParameter("@ID", SqlDbType.Int);
            Mess.Value = Convert.ToInt32(ID);
            SqlDataReader sdr = DbHelperSQL.ExecuteReader(usersql, Mess);
            sdr.Read();
            string user_Mes_Name=sdr["User_BlogName"].ToString();
            string user_email=sdr["User_Email"].ToString();
            HttpCookie hck = context.Request.Cookies["login"];
            hck.Value = null;
            context.Response.Cookies.Add(hck);

            HttpCookie hc = context.Request.Cookies["login"];
            hc.Values.Add("user_ID", ID);
            hc.Values.Add("user_blogName",user_Mes_Name);
            hc.Values.Add("user_email",user_email);
            hc.Expires = DateTime.Now.AddDays(7);
            context.Response.Cookies.Add(hc);
            context.Session["user_Message"] = ID + "," + user_Mes_Name + "," + user_email;

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