using System;
using System.Data;
using System.Text;
using System.Configuration;
using System.Collections;
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.user.Album
{
    public partial class AlbumView : JuSNS.UI.Page.BasePage
    {
        protected string[] r ={ "", "" };
        protected string errmsg = "";
        protected string AlbumContent;   //相册内容
        protected int PhotoCount=0;  //相册中照片数量
        protected string Whos = "我";   //谁的相册
        protected string WhosHeadImage = "";
        protected AlbumInfo AbInf = new AlbumInfo();
        protected string Quan = string.Empty;
        protected bool isGroupMember = false; 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["r[0]"]))
            {
                r[0] = Request.QueryString["r[0]"];
            }
            if (!string.IsNullOrEmpty(Request.QueryString["r[1]"]))
            {
                r[1] = Request.QueryString["r[1]"];
            }
            if (string.IsNullOrEmpty(r[1]))
                Response.Redirect("index.aspx");
            JuSNS.Home.Album ab = new JuSNS.Home.Album();

            AbInf = ab.Info(Convert.ToInt32(r[1]));
            if (string.IsNullOrEmpty(r[0]))
                r[0] = AbInf.UserID.ToString();

            if (Convert.ToInt32(r[0]) == this.GetUserID())
            {
                this.toc.Visible = true;
            }
            else
            {
                this.toc.Visible = false;
            }
            this.SuccessMSG.Visible = false;
            if (Session["SuccessMSG"] != null)
            {
                this.SuccessMSG.InnerText = Session["SuccessMSG"].ToString();
                this.SuccessMSG.Visible = true;
                Session.Remove("SuccessMSG");
            }
            albumContent();
            setWhos();
            setQuan();
            setimghead();
            seth2title();
            setreturnaction();
            setToc();
            //隐私
            awrap.Visible = false;
            //如果是群组内的人
            UserGroup ug = new UserGroup();
            if (ug.IsMyGroup(AbInf.GroupID, this.GetUserID()))
            {
                this.toc.Visible = true;
                this.isGroupMember = true;
                return;
            }
            if(r[0]!=GetUserID().ToString())
            {
                if (!this.PrivacyAvailable(AbInf.Privacy, AbInf.UserID))
                {
                    string returnText = string.Empty;
                    string returnMsg = string.Empty;
                    switch (AbInf.Privacy)
                    {
                        case EnumPrivacy.ForFriends:
                            returnMsg = "" + Whos + "设置为好友才可见！";
                            returnText = AddFriend(AbInf.UserID, Whos, WhosHeadImage);
                            break;
                        case EnumPrivacy.ForNetWorkAndFriends:
                            returnMsg = "加" + Whos + "为好友后可查看";
                            returnText = AddFriend(AbInf.UserID, Whos, WhosHeadImage);
                            break;
                        case EnumPrivacy.ForOwner:
                            returnMsg = "相册主人设置了照片仅为自己查看";
                            returnText = string.Empty; ;
                            break;
                        default:
                            break;
                    }
                    if (!string.IsNullOrEmpty(returnMsg))
                    {
                        PageError(returnMsg + "<br />" + returnText, "javascript:history.back();");
                    }
                }
            }
        }

        /// <summary>
        /// 设置头像，可能为群组相册
        /// </summary>
        protected void setimghead()
        {
            if (AbInf.GroupID == 0)
            {
                
                this.imghead.InnerHtml = "<a href=\"../../user/" + JuSNS.Common.Public.URLWrite("", "r", r[0]) + "\">"
                            + "<img src=\"" + WhosHeadImage + "\" alt=\"" + Whos + "\" style=\"width:48px;height:48px;\" /></a>";
            }
            else
            {
                UserGroup group = new UserGroup();
                UserGroupInfo info = group.Info(AbInf.GroupID);
                this.imghead.InnerHtml = "<a href=\"../../home/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 + "";
                        this.ptitle.InnerText = AbInf.Title+"浏览";
            }
            else
            {
                UserGroup group = new UserGroup();
                UserGroupInfo info = group.Info(AbInf.GroupID);
                this.h2title.InnerHtml = "群组相册：" + info.GroupName;
                this.ptitle.InnerText = info.GroupName + "的相册浏览";
            }
        }
        /// <summary>
        /// 设置返回
        /// </summary>
        protected void setreturnaction()
        {
            if (AbInf.GroupID == 0)
            {
                this.returnaction.InnerHtml = "<a href=\"../../user/" + JuSNS.Common.Public.URLWrite("", "r", r[0]) + "\">返回" + 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>";
            }
        }
        /// <summary>
        /// 设置toc区域
        /// </summary>
        protected void setToc()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<p class=\"bar\">");
            if (PhotoCount > 0)
            {
                sb.Append(PhotoCount);
                sb.Append("张照片");
            }
            else
            {
                sb.Append("没有照片");
            }
            if (AbInf.UserID == this.GetUserID())
            {
                sb.Append("<span class=\"pipe\">|</span><a href=\"AlbumEdit.aspx?r=");
                sb.Append(r[1]);
                sb.Append("\">编辑相册</a>");
            }
            sb.Append("<span class=\"pipe\">|</span>");
            sb.Append("<a href=\"PhotoAdd.aspx?r=");
            sb.Append(r[1]);
            sb.Append("&u=");
            sb.Append(this.GetUserID());
            sb.Append("\">上传");
            if (PhotoCount > 0)
            {
                sb.Append("更多");
            }
            string s = "index.aspx?r[0]=" + r[0];
            if (AbInf.GroupID != 0)
            {
                s = "../group/album.aspx?GroupID=" + AbInf.GroupID;
            }
            sb.Append("照片</a><span class=\"pipe\">|</span><a href=\"");
            sb.Append(s);
            sb.Append("\">");
            if (AbInf.GroupID == 0)
            {
                sb.Append("返回我的所有相册");
            }
            else
            {
                sb.Append("返回群组所有相册");
            }
            sb.Append("</a></p>");
        }

        /// <summary>
        /// 设置内容和照片数量
        /// </summary>
        /// <returns></returns>
        protected void albumContent()
        {
            

            int ReCount, PgCount;
            int PageIndex = 1;
            if (Request.QueryString["Page"] != null)
                PageIndex = Convert.ToInt32(Request.QueryString["Page"]);
            DataTable dt1 = UtilPage.GetPage("Album_View", PageIndex, PAGESZ, out ReCount, out PgCount, new SqlConditionInfo("@UserID", Convert.ToInt32(r[0]), TypeCode.Int32), new SqlConditionInfo("@AlbumID", Convert.ToInt32(r[1]), TypeCode.Int32));
            string PageUrl = "AlbumView.aspx";
            DataTable dt = new DataTable();
            dt.Columns.Add("d1", typeof(string));
            PhotoCount = ReCount;
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                DataRow dr=dt.NewRow();
                StringBuilder sb = new StringBuilder();
                sb.Append("                <a onclick=\"return postblog()\" href=\"PhotoView.aspx?r[0]=" + dt1.Rows[i]["PhotoID"] + "&r[1]=" + dt1.Rows[i]["AlbumID"] + "\">\n");
                sb.Append("                    <img src=\"" + this.GetSmallPic(dt1.Rows[i]["FilePath"].ToString(), 2) + "\" alt=\"" + dt1.Rows[i]["Description"] + "\" /></a>");
                dr["d1"] = sb.ToString();
                dt.Rows.Add(dr);
            }
            this.albumviewer.RepeatColumns = 4;
            this.albumviewer.RepeatDirection = RepeatDirection.Vertical;
            this.albumviewer.DataSource = dt;
            this.albumviewer.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;
            }
            dt.Dispose();
            dt1.Dispose();
        }

        /// <summary>
        /// 设置是谁的相册
        /// </summary>
        protected void setWhos()
        {
            User u = new User();
            UserInfo UI = u.GetUserInfo(Convert.ToInt32(r[0]));
            JuSNS.Home.Photo ph = new JuSNS.Home.Photo();
            Whos = UI.Username;
            WhosHeadImage = this.GetHeadImage(UI.UserID);           
        }

        /// <summary>
        /// 设置圈人信息
        /// </summary>
        protected void setQuan()
        {
            PhotoLasso plo = new PhotoLasso();
            List<PhotoLassoInfo> infolist = plo.AlbumLasso(AbInf.AlbumID);
            infolist = deleteRe(infolist);
            StringBuilder sb = new StringBuilder();
            if (infolist.Count > 0)
            {
                sb.Append("<div class=\"pstr\">");
                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 delstr = "";
                    sb.Append("<span><a 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("，");
                    }
                    sb.Append("</span>");
                }
                sb.Append("</div>");
            }
            Quan = sb.ToString();
        }
        /// <summary>
        /// 去除有重复用户的项
        /// </summary>
        /// <param name="infolist">圈人信息表</param>
        /// <returns></returns>
        protected List<PhotoLassoInfo> deleteRe(List<PhotoLassoInfo> infolist)
        {
            List<PhotoLassoInfo> tempList = new List<PhotoLassoInfo>();
            for (int i = 0; i < infolist.Count; i++)
            {
                if (existUserIDinList(tempList, infolist[i].UserID))
                {
                    continue;
                }
                tempList.Add(infolist[i]);
            }
            return tempList;
        }
        /// <summary>
        /// 圈人信息表中存在userid
        /// </summary>
        /// <param name="infolist">圈人信息表</param>
        /// <param name="userid">userid</param>
        /// <returns>true|false</returns>
        protected bool existUserIDinList(List<PhotoLassoInfo> infolist, int userid)
        {
            for (int i = 0; i < infolist.Count; i++)
            {
                if (userid == infolist[i].UserID)
                {
                    return true;
                }
            }
            return false;
        }

        protected string AddFriend(int uid, string unm, string upic)
        {
            JuSNS.Home.Friend frd = new Friend();
            string ret = string.Empty;
            int usid = uid;
            if (usid != GetUserID())
            {
                int n = frd.GetRelation(GetUserID(), 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;
        }
    }
}
