using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 JuSNS.Model;
using JuSNS.Common.PicUpload;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing;
using JuSNS.Common;
using JuSNS.Config;
using System.Collections.Generic;

namespace JuSNS.Web.home.Group
{
    public partial class Creat_Pic : JuSNS.UI.Page.UserPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataBind();
            Response.CacheControl = "no-cache";
            Check();
            if (!Page.IsPostBack)
            {
                getInfo();
                IsSuc();
            }
        }

        /// <summary>
        /// 检测有无权限设置
        /// </summary>
        protected void Check()
        {
            string GroupID = Request.QueryString["GroupID"];
            if (GroupID != null && GroupID != "")
            {
                JuSNS.Home.UserGroup usergroup = new JuSNS.Home.UserGroup();
                JuSNS.Home.GroupMember groupmember = new JuSNS.Home.GroupMember();
                bool admintf = false;
                bool supertf = false;
                if (usergroup.IsMyGroup(Convert.ToInt32(GroupID), UserID))
                    supertf = true;
                if (groupmember.IsGroupAdmin(UserID, Convert.ToInt32(GroupID)))
                    admintf = true;

                if (!(admintf || supertf))
                {
                    PageError("参数错误!", "Creat_base.aspx");
                }
            }
        }

        /// <summary>
        /// 检查是否添加成功
        /// </summary>
        protected void IsSuc()
        {
            try
            {
                if (Request.Cookies["AddGroupIsScu"].Value == "true")
                {
                    ShowSuc("创建群组成功！为群组创建一个图片。", div_Suc);
                }
                Response.Cookies["AddGroupIsScu"].Value = "";
            }
            catch (Exception e) { }
            try
            {
                if (Request.Cookies["EditGroupIsScu"].Value == "true")
                    ShowSuc("修改群组成功!", div_Suc);
                Response.Cookies["EditGroupIsScu"].Value = "";
            }
            catch (Exception e) { }
        }

        /// <summary>
        /// 加载页面初始信息
        /// </summary>
        protected void getInfo()
        {
            Div_Result.Visible = false;
            string GroupID = Request.QueryString["GroupID"];
            if (GroupID != null && GroupID != string.Empty)
            {
                JuSNS.Home.UserGroup usergroup = new JuSNS.Home.UserGroup();
                UserGroupInfo usergroupinfo = new UserGroupInfo();
                usergroupinfo = usergroup.Info(Convert.ToInt32(GroupID));

                this.Em_GroupName.InnerHtml = usergroupinfo.GroupName;
                this.IMG.Src = this.GetGroupHead(usergroupinfo.Portrait);
                this.Hid_GroupID.Value = GroupID;           
            }
        }

        /// <summary>
        /// 执行上传头像过程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void submit1_ServerClick(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                bool tf = true;
                div_Suc.Visible = false;
                Div_Result.Visible = false;
                if (picture.Value == null || picture.Value == "")
                {
                    tf = false;
                    ShowErr("图片目的文件错误", div_Error);
                    goto Finish;
                }
                if (tf)
                {
                    //上传图片
                    PicUpload picup = new GroupUpload(picture.PostedFile);
                    picup.Start();

                    JuSNS.Home.UserGroup usergroup = new JuSNS.Home.UserGroup();
                    UserGroupInfo usergroupinfo = new UserGroupInfo();
                    
                    usergroupinfo.GroupID = Convert.ToInt32(Hid_GroupID.Value);
                    usergroupinfo.GroupName = "";
                    usergroupinfo.UserID = UserID;
                    usergroupinfo.Members = 0;
                    usergroupinfo.Bulletin = "";
                    usergroupinfo.NetWork = 0;
                    usergroupinfo.Publicity = EnumGroupPrivacy.ForWholeSite;
                    if (picup.SuccessNum > 0)
                    {
                        usergroupinfo.Portrait = picup.OutFileName;
                    }
                    usergroupinfo.State = 0;
                    usergroupinfo.PostTime = DateTime.Now;
                    usergroupinfo.PostIP = string.Empty;

                    if (usergroup.EditHead(usergroupinfo) == 1)
                    {
                        Div_UpPic.Visible = false;
                        Div_Result.Visible = true;
                        ShowSuc("上传成功!", div_Suc);
                        IMG.Src = this.GetGroupHead(picup.OutFileName);
                        Div_Result.InnerHtml = "<div style=\"font-size:18px;margin:3em 0 2em;text-align:center;\"><input type=\"button\" class=\"f-button\" value=\"成功，进行下一步\" onclick=\"window.location='Creat_Member.aspx?GroupID=" + Hid_GroupID.Value + "&a=1&m="+Request.QueryString["m"]+"'\" /></div><div>对刚刚上传的头像不太满意？可以<a href=\"Creat_Pic.aspx?GroupID=" + Hid_GroupID.Value + "&a=1\">重新上传头像</a>。</div>";
                    }
                }
            Finish: ;
            }
        }
        /// <summary>
        /// 生成剪切头像图片
        /// </summary>
        /// <param name="im"></param>
        /// <param name="filename"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        protected void makeRectImage(string filename, int x, int y, int w, int h)
        {
            Dictionary<string, PicConfigInfo> pci;
            pci = PicConfig.GroupHead;
            string filepath = this.GetGroupHead(filename, 6);
            string smallPath = this.GetGroupHead(filename, 4);
            if (string.IsNullOrEmpty(PicConfig.GroupServer) || PicConfig.GroupServer != "~")
            {
                //剪切for远程
            }
            else
            {
                //本地剪切
                Bitmap bmp = new Bitmap(Server.MapPath(filepath));
                MemoryStream ms = new MemoryStream();
                ImageCodecInfo myImageCodecInfo;
                System.Drawing.Imaging.Encoder myEncoder;
                EncoderParameter myEncoderParameter;
                EncoderParameters myEncoderParameters;
                myImageCodecInfo = ImageCodecInfo.GetImageEncoders()[0];
                myEncoder = System.Drawing.Imaging.Encoder.Quality;
                myEncoderParameters = new EncoderParameters(1);
                myEncoderParameter = new EncoderParameter(myEncoder, 100L);
                myEncoderParameters.Param[0] = myEncoderParameter;
                bmp.Save(ms, myImageCodecInfo, myEncoderParameters);
                bmp.Dispose();
                byte[] data1;
                PicUpload.makeRectImage(ms.ToArray(), out data1, x, y, w, h);
                System.Drawing.Image image = Bitmap.FromStream(new MemoryStream(data1));
                Thumbnail thb = new Thumbnail(image);
                thb.NewPath = Server.MapPath(smallPath);
                thb.Width = pci["1"].X;
                thb.Height = pci["1"].Y;
                thb.Make();
                image.Dispose();
                ms.Dispose();
            }
        }
    }
}
