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.UI.Control;
using JuSNS.Common;
using System.Collections.Generic;

namespace JuSNS.Web.user.Group
{
    public partial class Group : JuSNS.UI.Page.BasePage
    {
        protected JuSNS.Model.UserGroupInfo usergroupinfo;
        protected string ruser = string.Empty;
        protected bool isGroupHead = true;
        JuSNS.Home.GroupMember groupmember = new JuSNS.Home.GroupMember();
        protected void Page_Load(object sender, EventArgs e)
        {
            ruser = GetUserID().ToString();
            string isHeadPic = this.GetHeadPath(this.GetUserID());
            if (string.IsNullOrEmpty(isHeadPic))
            {
                if (JuSNS.Config.UiConfig.isUpHeadPic == "1" && !JuSNS.Common.Public.GetHeadLimite(2))
                {
                    isGroupHead = false;
                }
            }
            CheckPublicity();
            Operate();
            getInfo();
            setGroupAlbum();
        }

        /// <summary>
        /// 检查是否允许被访问
        /// </summary>
        protected void CheckPublicity()
        {
            bool tf = false;
            string s_GroupID = Request.QueryString["GroupID"];
            if (!JuSNS.Common.Input.IsInteger(s_GroupID))
            {
                 PageError("参数传递错误！", "" + rooDir + "/home/group");
            }
            int GroupID = Convert.ToInt32(s_GroupID);
            Hid_GroupID.Value = s_GroupID;
            JuSNS.Home.UserGroup usergroup = new JuSNS.Home.UserGroup();
            usergroupinfo = usergroup.Info(GroupID);
            if (!this.PrivacyAvailable(EnumPrivacyType.Group, GetUserID(), usergroupinfo.UserID))
            {
                PageError("用户的隐私设置，你无法查看！", "javascript:history.back();");
            }
            tf = usergroup.CheckPublicity(GroupID, GetUserID(), false);
            if (!tf) { PageError("用户的隐私设置，你无法查看！", "" + rooDir + "/home/group"); }
        }

        /// <summary>
        /// 相关操作
        /// </summary>
        protected void Operate()
        {
            string s_Act = Request.QueryString["Action"];
            int n = 0;
            if (!string.IsNullOrEmpty(s_Act))
            {
                string s_gid = Request.QueryString["GroupID"];
                if (s_gid == null || s_gid == "")
                    PageError("参数传递错误!", ""+rooDir+"/home/group");
                int groupid = Convert.ToInt32(s_gid);
                switch (s_Act)
                {
                    case "Join":
                        JuSNS.Model.GroupMemberInfo gmemberinfo = new GroupMemberInfo();
                        gmemberinfo.ID = 0;
                        gmemberinfo.GroupID = groupid;
                        gmemberinfo.UserID = GetUserID();
                        gmemberinfo.Grade = EnumGroupGrade.Common;
                        gmemberinfo.JoinTime = DateTime.Now;
                        n = groupmember.Join(gmemberinfo);
                        if (n > 0)
                            Response.Redirect("group.aspx?GroupID=" + groupid.ToString());
                        else
                            PageError("加入群组失败!", "" + rooDir + "/home/group");
                        break;
                    case "Exit":
                        if (usergroupinfo.UserID == GetUserID() && usergroupinfo.Members == 1)
                        {
                            JuSNS.Home.UserGroup usergroup = new JuSNS.Home.UserGroup();
                            n = usergroup.Del(groupid, GetUserID());
                        }
                        else
                        {
                            n = groupmember.Out(GetUserID(), groupid);
                        }
                        if (n > 0)
                            Response.Cookies["OutGroup"].Value = "true";
                        Response.Redirect("my.aspx?r=" + GetUserID() + "&a=join");
                        break;
                }
            }
        }

        /// <summary>
        /// 加载页面初始信息
        /// </summary>
        protected void getInfo()
        {
            int GroupID = Convert.ToInt32(Hid_GroupID.Value);

            this.H2_GroupName.InnerHtml = usergroupinfo.GroupName;
            this.ptitle.InnerText = usergroupinfo.GroupName;
            this.P_Publicity.InnerHtml = JuSNS.Home.UserGroup.getPublicityName(usergroupinfo.Publicity);
            this.Div_sect.InnerHtml = JuSNS.Common.Input.HtmlEncode(usergroupinfo.Bulletin);
            this.Img_GroupHead.Src = this.GetGroupHead(usergroupinfo.Portrait);
            this.Img_GroupHead.Alt = usergroupinfo.GroupName;
            this.Span_UserCount.InnerHtml = usergroupinfo.Members.ToString();
            this.A_AllMember.HRef = "member.aspx?GroupID=" + Hid_GroupID.Value;

            DataTable dt_NewMember = groupmember.Top6GroupMemberList(GroupID);
            if (dt_NewMember != null)
            {
                Rpt_MemberList.DataSource = dt_NewMember;
                Rpt_MemberList.DataBind();
                dt_NewMember.Clear(); dt_NewMember.Dispose();
            }

            this.P_GroupType.InnerHtml = getGroupType(usergroupinfo.Publicity);

            DataTable dt_GroupAdmin = groupmember.GroupMemberGradeList(2, GroupID);
            if (dt_GroupAdmin != null)
            {
                Rpt_GroupAdminList.DataSource = dt_GroupAdmin;
                Rpt_GroupAdminList.DataBind();
                dt_GroupAdmin.Clear(); dt_GroupAdmin.Dispose();
            }

            string s_Op = "";
            bool supertf = false;
            bool admintf = false;
            if (usergroupinfo.UserID == GetUserID())
                supertf = true;
            if (groupmember.IsGroupAdmin(GetUserID(), GroupID))
                admintf = true;

            if (supertf || admintf)
            {
                this.A_Edit.InnerHtml = "修改";
                this.A_Edit.HRef = "Creat_base.aspx?GroupID=" + Hid_GroupID.Value;
                s_Op = "  <li class=\"reshow bold\"><a href=\"group.aspx?GroupID=" + GroupID + "#posttopic\">发表话题</a></li>";
                s_Op += "<li><a href=\"Group-m.aspx?GroupID=" + GroupID + "\">讨论区</a></li>";
                s_Op += "<li><a href=\"album.aspx?GroupID=" + GroupID + "\">群组相册</a></li>";
                s_Op += "<li><a href=\"Creat_base.aspx?GroupID=" + GroupID + "&m=1\">设置群组</a></li>";
                s_Op += "<li><a href=\"Creat_member.aspx?GroupID=" + GroupID + "&a=1\">管理成员</a></li>";
                s_Op += "<li><a href=\"member.aspx?GroupID=" + GroupID + "\" title=\"" + usergroupinfo.Members.ToString() + "个成员\">群组成员(" + usergroupinfo.Members.ToString() + ")</a></li>";
                s_Op += "<li><a href=\"Creat_member.aspx?GroupID=" + GroupID + "&a=1\">邀请好友加入</a></li>";
                if (this.GetUserID() != 0)
                {
                    if (this.GetUserID() == usergroupinfo.UserID)
                    {
                        s_Op += "<li><a href=\"javascript:void(0);\" onclick=\"javascript:Confirm(this,'<ul><li>您是本群群主，您确定退出吗？</li><li>退出后将解散此群所有信息。不可还原！</li></ul>','退出',function (){self.location='out.aspx?GroupID=" + GroupID.ToString() + "';})\">退出此群</a></li>";
                    }
                    else
                    {
                        s_Op += "<li><a href=\"javascript:void(0);\" onclick=\"javascript:Confirm(this,'<ul><li>确定要退出此群吗？</li></ul>','退出',function (){self.location='out.aspx?GroupID=" + GroupID.ToString() + "';})\">退出此群</a></li>";
                    }
                }
            }
            else
            {
                A_Edit.InnerHtml = string.Empty;
                s_Op = "<li><a href=\"Group-m.aspx?GroupID=" + GroupID + "\">讨论区</a></li>";
                s_Op += "<li><a href=\"album.aspx?GroupID=" + GroupID + "\">群组相册</a></li>";
                s_Op += "<li><a href=\"member.aspx?GroupID=" + GroupID + "\" title=\"" + usergroupinfo.Members.ToString() + "个成员\">群组成员(" + usergroupinfo.Members.ToString() + ")</a></li>";
                //判断是否是本群成员，如果不是则显示加入此群
                if (this.GetUserID() != 0)
                {
                    if (groupmember.IsGroupMember(GetUserID(), GroupID) == false)
                    {
                        this.isPost.InnerHtml = "<span class=\"reshow\">对不起，加入此群组才能发表帖子</span> &nbsp; <a href=\"javascript:void(0);\" onclick=\"javascript:Confirm(this,'<ul><li>确定加入此群吗？</li></ul>','加入',function (){self.location='?Action=Join&GroupID=" + GroupID + "';})\">加入此群</a>";
                        s_Op += "<li><a href=\"javascript:void(0);\" onclick=\"javascript:Confirm(this,'<ul><li>确定加入此群吗？</li></ul>','加入',function (){self.location='?Action=Join&GroupID=" + GroupID + "';})\">加入此群</a></li>";
                    }
                    else
                    {
                        s_Op += "<li><a href=\"javascript:void(0);\" onclick=\"javascript:Confirm(this,'<ul><li>确定要退出此群吗？</li></ul>','退出',function (){self.location='out.aspx?GroupID=" + GroupID.ToString() + "';})\">退出此群</a></li>";
                    }
                }
                else
                {
                    this.isPost.InnerHtml = "<span class=\"reshow\">请登录后发表帖子。</span> &nbsp; <a href=\"" + rooDir + "/?urls=" + Request.Url + "\">点这里登录</a>";
                }
            }
            Ul_GroupAdminOp.InnerHtml = s_Op;

            DivPage.Visible = false;
            int r, p, PageIndex = 0;
            PageIndex = Convert.ToInt32(Request.QueryString["Page"]);
            SqlConditionInfo st = new SqlConditionInfo("@GroupID", GroupID, TypeCode.Int32);

            DataTable dt_Discuss = JuSNS.Home.UtilPage.GetPage("GroupDiscuss_aspx", PageIndex, 20, out r, out p, st);
            if (dt_Discuss != null)
            {
                Rpt_DiscussList.DataSource = dt_Discuss;
                Rpt_DiscussList.DataBind();
                dt_Discuss.Clear();
                dt_Discuss.Dispose();
            }
            //判断是否调用分页
            if (r > 20)
            {
                DivPage.Visible = true;
                DivPage.InnerHtml = PageNavigator.Pagination(PageIndex, p, "Group-m.aspx");
            }
            span_DiscussCount.InnerHtml = r.ToString();
        }

        /// <summary>
        /// 取得组的隐私介绍
        /// </summary>
        /// <param name="enumprivacy">类型</param>
        /// <returns></returns>
        protected string getGroupType(EnumGroupPrivacy enumprivacy)
        {
            string s_Type = "";
            switch (enumprivacy)
            {
                case EnumGroupPrivacy.ForWholeSite:
                    s_Type = "<strong>这是公开群</strong>：群组内容完全公开，随时可以加入。";
                    break;
                case EnumGroupPrivacy.ForSemiOvert:
                    s_Type = "<strong>这是半公开群</strong>：非成员可以浏览群组资料，不能查看讨论区，需要邀请才能加入。";
                    break;
                case EnumGroupPrivacy.ForGroupMember:
                    s_Type = "<strong>私密群</strong>：只有成员才能看到群组，非成员需要接受成员的邀请后才能加入。";
                    break;
            }
            return s_Type;
        }

       

        /// <summary>
        /// 判断是否群主
        /// </summary>
        /// <param name="Type">类型</param>
        /// <returns></returns>
        protected string getGradeName(object Type)
        {
            string s_Name = string.Empty;
            if (Type.ToString() == "0")
                s_Name = "<span class=\"reshow\">群主</span>";
            return s_Name;
        }

        /// <summary>
        /// 取得会员姓名
        /// </summary>
        /// <param name="UserID">会员编号</param>
        /// <returns></returns>
        protected string getUserName(object UserID)
        {
            string s_Name = "&nbsp;";
            if (UserID != DBNull.Value)
            {
                JuSNS.Home.User user = new JuSNS.Home.User();
                UserInfo userinfo = new UserInfo();
                userinfo = user.GetUserInfo(Convert.ToInt32(UserID));
                s_Name = "<a href=\""+rooDir+"/user/" + JuSNS.Common.Public.URLWrite("", "r", UserID.ToString()) + "\">" + userinfo.Username + "</a>";
            }
            return s_Name;
        }

        /// <summary>
        /// 取得时间
        /// </summary>
        /// <param name="time">时间</param>
        /// <returns></returns>
        protected string getTime(object time, object id)
        {
            string s_Time = "&nbsp;";
            if (time != DBNull.Value)
                s_Time = JuSNS.Common.Public.getTimeSpan(Convert.ToDateTime(time));
            return s_Time;
        }

        /// <summary>
        /// 显示是否置顶
        /// </summary>
        /// <param name="topnum"></param>
        /// <returns></returns>
        protected string getIsTop(object topnum)
        {
            string s_Top = "";
            if (topnum.ToString() == "1")
                s_Top = "<span class=\"reshow\">[置顶]</span>";
            return s_Top;
        }

        /// <summary>
        /// 执行添加过程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            GetIsNotEmail();
            if (this.GetUserID() == 0)
            {
                PageError("<span class=\"reshow\">请登录后发表帖子。</span> &nbsp; <a href=\"" + rooDir + "/?urls=" + Request.Url + "\">点这里登录</a>", rooDir + "/?urls=" + Request.Url, true);
            }
            bool tf = groupmember.IsGroupMember(GetUserID(), Convert.ToInt32(Hid_GroupID.Value));
            if (!tf)
                PageError("您没有访问权限！不能发表主题!", "javascript:history.back()");

            if (Page.IsValid)
            {
                if (Topic.Value.Trim() == "" || Content.Value.Trim() == "")
                {
                    ShowErr("标题和内容不能为空!", div_Error);
                    goto Finish;
                }

                #region 过滤关键字
                string res = JuSNS.Common.Public.CheckKey(this.Content.Value, true);
                if (res != "")
                {
                    this.Content.Value = this.Content.Value.Replace(res, "***");
                }
                #endregion
                JuSNS.Home.Group groupdis = new JuSNS.Home.Group();
                JuSNS.Model.GroupDiscussInfo groupdisinfo = new JuSNS.Model.GroupDiscussInfo();
                groupdisinfo.ID = 0;
                groupdisinfo.GroupID = Convert.ToInt32(Hid_GroupID.Value);
                groupdisinfo.UserID = GetUserID();
                groupdisinfo.Topic = Topic.Value;
                groupdisinfo.Content = JuSNS.Common.Input.HtmlEncode(Content.Value);
                groupdisinfo.DiscussType = 0;
                groupdisinfo.BelongTopic = 0;
                groupdisinfo.PostTime = DateTime.Now;
                groupdisinfo.PostIP = JuSNS.Common.Public.GetClientIP();
                groupdisinfo.LastPostTime = DateTime.Now;
                groupdisinfo.LastPostIP = JuSNS.Common.Public.GetClientIP();
                groupdisinfo.LastPoster = 0;
                groupdisinfo.Replys = 0;
                groupdisinfo.State = 0;
                groupdisinfo.LastModifyTime = DateTime.Now;
                groupdisinfo.LastModifyIP = JuSNS.Common.Public.GetClientIP();
                groupdisinfo.ReplyID = 0;
                groupdisinfo.ReplyTack = "";
                groupdisinfo.SeriesNum = 0;
                groupdisinfo.TopNum = 0;

                if (groupdis.Add(groupdisinfo) >0)
                {
                    Response.Cookies["AddGroupDisIsSuc"].Value = "true";
                    Response.Redirect("Group.aspx?GroupID=" + Hid_GroupID.Value);
                }
                else
                {
                    Topic.Value = "";
                    Content.Value = "";
                    ShowErr("发表失败!", div_Error);
                }
            Finish: ;
            }
        }
        /// <summary>
        /// 设置群组相册
        /// </summary>
        protected void setGroupAlbum()
        {
            Home.Photo photo = new Home.Photo();
            List<PhotoInfo> infolist = photo.GroupInfoList(usergroupinfo.GroupID);
            if (infolist.Count == 0)
            {
                this.gp_album.Visible = false;
            }
            this.groupalbum.DataSource = infolist;
            this.groupalbum.RepeatDirection = RepeatDirection.Vertical;
            this.groupalbum.CssClass = "groupalbum";
            this.groupalbum.RepeatColumns = 8;
            this.groupalbum.DataBind();
        }

    }
}
