using System;
using System.Data;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Configuration;
using System.Collections.Generic;
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.Common;
using JuSNS.Home;
using JuSNS.Model;
using JuSNS.Config;
using JuSNS.UI.Control;

namespace JuSNS.Web.home.Album
{
    public partial class PhotoView : JuSNS.UI.Page.UserPage
    {
        protected string[] r ={ "", "" }; //r0照片id,r1corInfo[id
        protected string Whos = "我的"; //谁的corInfo[
        protected string WhosHeadImage = ""; //谁的头象
        protected UserInfo WhosUserInfo = new UserInfo(); //被访问的用户信息
        protected AlbumInfo AbInf = new AlbumInfo(); //被访问的corInfo[信息
        protected PhotoInfo Phi = new PhotoInfo(); //被访问的照片信息
        protected string photoPath = ""; //当前照片路径
        protected int nextPhotoID = 0; //下一张照片id
        protected int prePhotoID = 0; //上一张照片id
        protected int photoTheNumber = 1; //照片位于corInfo[中的哪一张
        protected string sucMSG = "";
        protected string photoQuanvalue = ""; //照片圈人信息
        protected string R = string.Empty; //用户ID仅在是头像corInfo[的时候用
        protected string LinkUrl = "Albumview.aspx";
        protected string orgPhotoPath = "";
        protected string PhotoTitle = "点击查看下一张";
        public static string phID = "";
        public static int num = 1;
        public static int photonum = 0;
        public int uID = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["r[0]"]))
            {
                r[0] = Request.QueryString["r[0]"];
            }
            else
            {
                this.PageError("缺少必要的参数", Request.RawUrl);
            }
            if (!string.IsNullOrEmpty(Request.QueryString["r[1]"]))
            {
                r[1] = Request.QueryString["r[1]"];
            }
            R = Request.QueryString["r"]; //此参数仅在头像corInfo[时用
            if (string.IsNullOrEmpty(R))
            {
                R = this.UserID.ToString();
            }


            #region 判断查看相片的权限
            string path = "";
            if (!IsPostBack)
            {
                path = this.GetHeadPath(this.UserID);//取得头像路径
                photonum = Convert.ToInt32(JuSNS.Common.Public.GetXMLValue("PhotoNum"));
            }

            if (string.IsNullOrEmpty(path))
            {
                if (r[1] != this.UserID.ToString())//判断是不是自己的相册
                {
                    if (phID == "")
                    {
                        phID += r[0];
                    }
                    string[] PD = phID.Split('|');
                    bool bl = false;
                    for (int i = 0; i < PD.Length; i++)
                    {
                        if (PD[i].ToString() == r[0])//判断这张相片自己看过没
                        {
                            bl = false;
                            break;
                        }
                        else
                        {
                            bl = true;
                        }
                    }

                    if (bl)
                    {
                        num += 1;
                        if (num != 1)
                        {
                            phID += "|" + r[0];
                        }
                    }

                    if (num > photonum)
                    {
                        phID = "";
                        num = 0;
                        Response.Write("<script>alert(\"对不起，你没有上传自己的头像，只能查看" + photonum + "张相片！\");window.location.href=\"/user/Space/UserHeadPhoto.aspx\";</script>");
                        Response.End();
                        return;
                    }
                }
            }
            #endregion

            sucMSG = Convert.ToString(Session["successMSG"]);
            Session.Remove("successMSG");
            setPhotoInfo();
            setAlbumInfo();
            fixPhoto();
            setWhos();
            setimghead();
            seth2title();
            setreturnaction();
            setPhotoLasso();
            setComments();

            if (photoTheNumber == 0)
            {
                photoTheNumber = AbInf.ImagesCount;
            }
            //if (WhosUserInfo.UserID != this.UserID)
            //{
            //    this.C_delPhoto.Visible = false;
            //    this.C_editPhoto.Visible = false;
            //}
            //隐私

            awrap.Visible = false;

            //如果是群组内的人
            UserGroup ug = new UserGroup();
            if (ug.IsMyGroup(AbInf.GroupID, this.UserID))
                return;

            if (!this.PrivacyAvailable(AbInf.Privacy, AbInf.UserID))
            {
                string returnText = string.Empty;
                string returnMsg = string.Empty;
                switch (AbInf.Privacy)
                {
                    case EnumPrivacy.ForFriends:
                        returnMsg = "加" + WhosUserInfo.Username + "为好友后可查看";
                        returnText = AddFriend(WhosUserInfo.UserID, WhosUserInfo.Username, WhosHeadImage);
                        //returnText = "<li id=\"li_req_" + WhosUserInfo.UserID + "\"><a href=\"javascript:AddFriend(" + WhosUserInfo.UserID + ",'" + WhosUserInfo.Username + "','" + WhosHeadImage + "','li_req_" + WhosUserInfo.UserID + "');\" class=\"complexlink friend-add\">加为好友</a></li>";
                        break;
                    case EnumPrivacy.ForNetWorkAndFriends:
                        returnMsg = "加" + WhosUserInfo.Username + "为好友后可查看";
                        returnText = AddFriend(WhosUserInfo.UserID, WhosUserInfo.Username, WhosHeadImage);
                        //returnText = "<li id=\"li_req_" + WhosUserInfo.UserID + "\"><a href=\"javascript:AddFriend(" + WhosUserInfo.UserID + ",'" + WhosUserInfo.Username + "','" + WhosHeadImage + "','li_req_" + WhosUserInfo.UserID + "');\" class=\"complexlink friend-add\">加为好友</a></li>";
                        break;
                    case EnumPrivacy.ForOwner:
                        returnMsg = "此人设置了照片仅为自己查看";
                        returnText = "";
                        break;
                    default:
                        break;
                }
                if (returnMsg != string.Empty)
                {
                    awrap.Visible = true;
                    toc.Visible = false;
                    awrap.InnerHtml = "<div class=\"msg-warn\"><div class=\"blod font14 pstr\">" + returnMsg + "</div><div>" + returnText + "</div><div class=\"spline\"></div></div>";
                    wrap.Visible = false;
                    photoabout.Visible = false;
                }
                //this.PageError("由于隐私的原因，此页不允许访问", "Photos.aspx");
            }
        }

        /// <summary>
        /// 设置被访问者信息
        /// </summary>
        protected void setWhos()
        {
            JuSNS.Home.User u = new JuSNS.Home.User();
            WhosUserInfo = u.GetUserInfo(AbInf.UserID);
            WhosHeadImage = this.GetHeadImage(AbInf.UserID);
            if (WhosUserInfo.UserID != this.UserID)
            {
                Whos = WhosUserInfo.Username + "的";
                uID = WhosUserInfo.UserID;
            }
        }

        /// <summary>
        /// 设置corInfo[信息
        /// </summary>
        protected void setAlbumInfo()
        {
            JuSNS.Home.Album alb = new JuSNS.Home.Album();
            AbInf = alb.Info(Convert.ToInt32(r[1]));
            Photo p = new Photo();
            if (r[1] == "0")
            {
                AbInf.AlbumID = 0;
                AbInf.Title = "头像相册";
                LinkUrl = "headalbum.aspx";
                AbInf.UserID = Convert.ToInt32(R);
                AbInf.ImagesCount = p.HeadCount(Convert.ToInt32(r[0]), Convert.ToInt32(R));
            }
        }

        /// <summary>
        /// 设置照片信息
        /// </summary>
        protected void setPhotoInfo()
        {
            JuSNS.Home.Photo ph = new JuSNS.Home.Photo();
            Phi = ph.Info(Convert.ToInt32(r[0]));
            if (Phi.PhotoType == 0)
            {
                r[1] = "0";
                R = Phi.UploadUser.ToString();
            }
            if (r[1] != "0")
            {
                nextPhotoID = ph.NextPhotoID(Phi.PhotoID);
                prePhotoID = ph.PrePhotoID(Phi.PhotoID);
                photoTheNumber = ph.TheNumber(Phi.PhotoID);
            }
            else
            {
                //头像相册
                nextPhotoID = ph.NextPhotoID(Phi.PhotoID, Convert.ToInt32(R));
                prePhotoID = ph.PrePhotoID(Phi.PhotoID, Convert.ToInt32(R));
                photoTheNumber = ph.TheNumber(Phi.PhotoID, Convert.ToInt32(R));
            }
            if (r[1] == "" || string.IsNullOrEmpty(r[1]))
            {
                r[1] = Phi.AlbumID.ToString();
            }
            //加浏览数
            ph.AddViews(Phi.PhotoID);
        }

        /// <summary>
        /// 设置正确的照片大小对应缩放路径
        /// </summary>
        protected void fixPhoto()
        {
            if (Phi.FilePath != "")
            {
                if (Convert.ToInt32(r[1]) == 0)
                {
                    //头像corInfo[
                    photoPath = "" + this.GetOrgHeadPic(Phi.FilePath);
                    orgPhotoPath = "" + this.GetOrgHeadPic(Phi.FilePath);
                }
                else
                {
                    //非头像corInfo[
                    photoPath = "" + this.GetOrgPic(Phi.FilePath);
                    orgPhotoPath = "" + this.GetOrgPic(Phi.FilePath);
                }
                try
                {
                    Bitmap bm = new Bitmap(Server.MapPath(photoPath));
                    if (bm.Width > 600)
                    {
                        PhotoTitle = "此照片已经过缩放处理，请点击上面“查看原始图像”查看原始照片";
                        if (Convert.ToInt32(r[1]) == 0)
                        {
                            //头像corInfo[
                            photoPath = Public.GetSmallHeadPic(Phi.FilePath, 3);
                        }
                        else
                        {
                            //非头像corInfo[
                            photoPath = this.GetSmallPic(Phi.FilePath, 6);
                        }
                    }
                    bm.Dispose();
                }
                catch
                {
                }
            }
            else
            {
                photoPath = "";
            }
        }

        /// <summary>
        /// 设置评论
        /// </summary>
        protected void setComments()
        {
            //PhotoComment comm=new PhotoComment();
            //List<PhotoCommentInfo> comments = comm.InfoList(Phi.PhotoID);
            //RptData.DataSource = comments;
            //RptData.DataBind();

            int ReCount, PgCount;
            int PageIndex = 1;
            if (Request.QueryString["Page"] != null)
                PageIndex = Convert.ToInt32(Request.QueryString["Page"]);
            DataTable dt = UtilPage.GetPage("PhotoCommentList", PageIndex, PAGESZ, out ReCount, out PgCount, new SqlConditionInfo("@PhotoID", Phi.PhotoID, TypeCode.Int32));
            string PageUrl = "PhotoView.aspx";
            this.RptData.DataSource = dt;
            dt.Columns.Add("availDel", typeof(string));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["userid"].ToString() == this.UserID.ToString() || this.IsAdmin())
                {
                    dt.Rows[i]["availdel"] = " class=\"delete\"";
                }
                else
                {
                    dt.Rows[i]["availdel"] = "style=\"display:none\"";
                }
                dt.Rows[i]["content"] = dt.Rows[i]["content"].ToString();
            }
            this.RptData.DataBind();
            PageUrl += "?r[0]=" + r[0] + "&r[1]=" + r[1];
            if (ReCount > PAGESZ)
            {
                this.DivPage.InnerHtml = PageNavigator.Pagination(PageIndex, PgCount, PageUrl);
            }
            else
            {
                this.DivPage.Visible = false;
            }
        }

        /// <summary>
        /// 取得用户名称
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        protected UserInfo getUser(object userid)
        {
            User u = new User();
            return u.GetUserInfo((int)userid);
        }

        /// <summary>
        /// 取得省份信息
        /// </summary>
        /// <param name="province">省份编号</param>
        /// <returns></returns>
        protected string getArea(object province)
        {
            Dict d = new Dict();
            return d.GetAreaName((int)province);
        }

        /// <summary>
        /// 取得省份信息
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <returns></returns>
        protected string getAreaByUserID(object userid)
        {
            return getArea((object)(getUser(userid).Province));
        }

        /// <summary>
        /// 设置照片圈人信息
        /// </summary>
        protected void setPhotoLasso()
        {
            PhotoLasso pl = new PhotoLasso();
            List<PhotoLassoInfo> infolist = pl.InfoList(Phi.PhotoID);
            StringBuilder sb = new StringBuilder();
            StringBuilder sb1 = new StringBuilder();
            if (infolist.Count > 0)
            {
                sb.Append("<div class=\"cpstr\">");
                sb.Append("<strong>照片中有：</strong>");
                for (int i = 0; i < infolist.Count; i++)
                {
                    PhotoLassoInfo pls = infolist[i];
                    User u = new User();
                    UserInfo ui = u.GetUserInfo(pls.FriendID);
                    string value = ui.UserID + "," + ui.Username + "," + pls.PosX + "," + pls.PosY + "," + pls.PosW + "," + pls.PosH;
                    string delstr = "";
                    if (pls.UserID == this.UserID)
                    {
                        delstr = "&nbsp;&nbsp;<a href=\"javascript:void(0);\" rev=\"plsodelete\" rel=\"../../inc/ajax/album/PhotoOperator.aspx?action=plsoDel&r=" + pls.ID + "\">删除</a>";
                    }
                    sb1.Append(value);
                    sb.Append("<span><a value=\"" + value + "\" rel=\"rel\" rev=\"quanquanview\" href=\"../../user/" + JuSNS.Common.Public.URLWrite("", "r", ui.UserID.ToString()) + "\">" + ui.Username + "</a>(<a href=\"quan.aspx?r=" + ui.UserID + "&uName=" + JuSNS.Common.Input.URLEncode(ui.Username) + "\">照片</a>" + delstr + ")");
                    if (i < infolist.Count - 1)
                    {
                        sb.Append("，");
                        sb1.Append("|");
                    }
                    sb.Append("</span>");
                }
                sb.Append("</div>");
            }
            this.quanview.InnerHtml = sb.ToString();
            photoQuanvalue = sb1.ToString();
        }

        protected string AddFriend(int uid, string unm, string upic)
        {
            JuSNS.Home.Friend frd = new Friend();
            string ret = string.Empty;
            int usid = uid;
            if (usid != UserID)
            {
                int n = frd.GetRelation(UserID, usid);
                if (n == 0)//无任何关系
                {
                    ret = "<li id=\"li_req_" + usid + "\"><a href=\"javascript:AddFriend(" + usid + ",'" + unm + "','" + upic + "','li_req_" + uid + "');\">加为好友</a></li>\r\n";
                }
                else if (n == 3)//已发出好友申请,等待确认好友申请
                {
                    ret = "<li>等待好友验证</li>";
                }
                else if (n == 4)//4被申请
                {
                    ret = "<li><a href=\"../friend/req.aspx\">处理好友请求</a></li>";
                }
            }
            return ret;
        }

        /// <summary>
        /// 设置头像，可能为群组相册
        /// </summary>
        protected void setimghead()
        {
            if (AbInf.GroupID == 0)
            {
                this.imghead.InnerHtml = "<a href=\"../../user/" + JuSNS.Common.Public.URLWrite("","r",uID.ToString())+ "\">"
                            + "<img src=\"" + WhosHeadImage + "\" alt=\"" + WhosUserInfo.Username + "\" style=\"width:48px;height:48px;\" /></a>";
            }
            else
            {
                UserGroup group = new UserGroup();
                UserGroupInfo info = group.Info(AbInf.GroupID);
                this.imghead.InnerHtml = "<a href=\"../group/group.aspx?GroupID=" + AbInf.GroupID + "\">"
                            + "<img src=\"" + this.GetGroupHead(info.Portrait) + "\" alt=\"" + info.GroupName + "\" style=\"width:48px;height:48px;\" /></a>";
            }
        }
        /// <summary>
        /// 设置h2title
        /// </summary>
        protected void seth2title()
        {
            if (AbInf.GroupID == 0)
            {
                this.h2title.InnerHtml = " " + Whos + ""
                        + "的相册<span class=\"pipe\">：</span>" + AbInf.Title + "";
            }
            else
            {
                UserGroup group = new UserGroup();
                UserGroupInfo info = group.Info(AbInf.GroupID);
                this.h2title.InnerHtml = "群组相册<span class=\"pipe\">：</span>" + info.GroupName + "";
            }
        }
        /// <summary>
        /// 设置返回
        /// </summary>
        protected void setreturnaction()
        {
            if (AbInf.GroupID == 0)
            {
                this.returnaction.InnerHtml = "<a href=\"../../user/" + JuSNS.Common.Public.URLWrite("", "r", uID.ToString()) + "\">返回" + Whos + "的空间</a>";
            }
            else
            {
                UserGroup group = new UserGroup();
                UserGroupInfo info = group.Info(AbInf.GroupID);
                this.returnaction.InnerHtml = "<a href=\"../group/group.aspx?GroupID=" + info.GroupID + "\">返回" + info.GroupName + "群</a>";
            }
        }
    }
}
