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

namespace JuSNS.Web
{
    public partial class index : JuSNS.UI.Page.BasePage
    {
        protected string TishiStr = string.Empty;
        protected string province = string.Empty;
        protected string cityarray = string.Empty;
        protected string Pr = null;
        protected string MSG = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            string r = Request.QueryString["r"];
            string url = Request.QueryString["urls"];
            if (!string.IsNullOrEmpty(url))
            {
                if (url.IndexOf("/home%2findex.aspx") > -1 || url.IndexOf("/home/index.aspx") > -1)
                {
                    Response.Redirect("./");
                }
            }

            if (!string.IsNullOrEmpty(r))
            {
                string MSGStr = string.Empty;
                switch (r)
                {
                    case "out":
                        MSGStr = "你访问的页面需要登录后才能查看！";
                        break;
                    case "null":
                        MSGStr = "请填写用户名和密码！";
                        break;
                    case "error":
                        MSGStr = "用户名和密码错误！";
                        break;
                    case "lock":
                        MSGStr = "对不起，您的帐号已经被系统锁定，如有疑问，请与管理员联系！";
                        break;
                    case "email":
                        MSGStr = "帐号(" + Request.QueryString["email"] + ")未通过<a href=\"EmailActive.aspx\">电子邮件激活</a>";
                        break;
                    case "timeout":
                        MSGStr = "登录已经过期！";
                        break;
                    case "open":
                        MSGStr = "现在暂未开放用户注册功能！";
                        break;
                    case "login":
                        MSGStr = "";
                        break;
                    default:
                        MSGStr = "" + r + "";
                        break;
                }
                MSG = "<div class=\"font14 bold reshow nl\">发生了以下错误：</div><div class=\"nr\"><a href=\"javascript:void(0);\" onclick=\"cleardiv($('tishiErrSuDiv'));\"><img src=\"template/images/close_05.gif\" style=\"border:0px;\" /></a></div><div class=\"spline\"></div>" + MSGStr + "<div style=\"text-align:right;\"><a href=\"javascript:history.back();\">返回上一步</a> <a href=\"" + rooDir + "/\">返回登录</a></div><div class=\"spline\"></div>";
            }
            else
            {
                HttpCookie SNSToKenCookie = Context.Request.Cookies["SNSUserPassPort"];
                if (SNSToKenCookie != null && !string.IsNullOrEmpty(SNSToKenCookie["token"]))
                {
                    string userCookie = SNSToKenCookie["token"];
                    string desstr = DES.Decrypt(userCookie, SecretConfig.UserKey, SecretConfig.UserIV);
                    string[] userInfo = desstr.Split(SecretConfig.UserSeparator);
                    if (userInfo.Length == 3)
                    {
                        UserID = int.Parse(userInfo[0]);
                        string pass = userInfo[1];
                        string cookip = userInfo[2];
                        if (cookip != Public.GetClientIP())
                        {
                            return;
                        }
                        else
                        {
                            User us = new User();
                            EnumLoginState state = us.CheckLogin(UserID, pass);
                            if (state == EnumLoginState.Succeed)
                                Response.Redirect("" + rooDir + "/home");
                        }
                    }
                }
                if (string.IsNullOrEmpty(url))
                {
                    string showIndexPage = Public.GetXMLValue("showIndexPage");
                    if (showIndexPage == "1")
                    {
                        Response.Redirect(rooDir + "/default.aspx");
                    }
                }
            }
            loadPro();
            string tPath = "~/template/site/default.html";
            string TempletContent = JuSNS.Common.Public.GetTempleContent(tPath, false);
            TempletContent = GetReplaceContent(TempletContent);
            Response.Write(TempletContent);
            Response.End();
        }

        protected string GetReplaceContent(string sContent)
        {
            string listSTR = string.Empty;
            sContent = Public.ReplacePublic(sContent);
            sContent = sContent.Replace("{GetHtmlHead}", this.GetHtmlHead());
            sContent = sContent.Replace("{Email}", Request.QueryString["Email"]);
            sContent = sContent.Replace("{loginCode}", LoginCode());
            sContent = sContent.Replace("{URL}", Request.QueryString["urls"]);
            sContent = sContent.Replace("{MyAlbumList}", GetNewAlbum());
            sContent = sContent.Replace("{RecUser}", GetRecUser());
            sContent = sContent.Replace("{RecGroupList}", GetRecGroup());
            sContent = sContent.Replace("{province}", province);
            sContent = sContent.Replace("{cityarray}", cityarray);
            sContent = sContent.Replace("{BlogList}", GetRecBlog());
            sContent = sContent.Replace("{GetHtmlFoot}", this.GetHtmlFoot());
            sContent = sContent.Replace("{RegCount}",GetRegisterCount());
            if (MSG != string.Empty)
            {
                sContent = sContent.Replace("{LtrMsgRContent}", "<div class=\"divstyleMSG\" id=\"tishiErrSuDiv\" style=\"display:block;\">" + MSG + "</div>");
            }
            else
            {
                sContent = sContent.Replace("{LtrMsgRContent}", "");
            }
            listSTR = sContent;
            return listSTR;
        }


        protected string GetRegisterCount()
        {
            string listSTR = string.Empty;
            JUser ju = new JUser();
            int rCount = ju.GetUserCount();
            string tmpSTR = "<div>欢迎您！<a href=\"" + rooDir + "/register.aspx\">加入" + JuSNS.Config.UiConfig.SiteName + "</a>！建立您的人脉关系。</div>";
            string[] ShowRegCount = JuSNS.Common.Public.GetXMLValue("ShowRegCount").Split('|');
            if (ShowRegCount[0] == "1")
            {
                tmpSTR = "欢迎您！共有 <span><a href=\"" + rooDir + "/home/search\">" + (rCount + Convert.ToInt32(ShowRegCount[1])) + "</a></span> 个会员加入了" + JuSNS.Config.UiConfig.SiteName + "!";
            }
            return tmpSTR;
        }

        protected string LoginCode()
        {
            string lSTR = string.Empty;
            if (JuSNS.Common.Public.GetXMLValue("loginCode") == "1")
            {
                lSTR += "<div>请输入下面4位随机字符:</div>";
                lSTR += "<div><input type=\"text\" name=\"TxtLogCode\" id=\"TxtLogCode\" class=\"f-text s30\" maxlength=\"6\" />";
                lSTR += "<script type=\"text/javascript\" language=\"JavaScript\">var numkey = Math.random();numkey = Math.round(numkey*10000);document.write(\"<img src='inc/code/image.aspx?k='+ numkey +'' width='70' onClick='this.src+=Math.random()' alt='图片看不清？点击重新得到验证码' style='cursor:pointer;' height='23' hspace='4' align='absmiddle' />\");</script></div>";
            }
            return lSTR;
        }

        protected string GetNewAlbum()
        {
            string listSTR = string.Empty;
            int ReCount, PgCount;
            int PageIndex = 1;
            DataTable dt = UtilPage.GetPage("Friend_Album_List_All_Index", PageIndex, 6, out ReCount, out PgCount, null);
            Home.Album ab = new Home.Album();
            JuSNS.Home.User u = new JuSNS.Home.User();
            int gRowscount = dt.Rows.Count;
            for (int i = 0; i < gRowscount; i++)
            {
                listSTR+="<li><a href=\"home/album/AlbumView.aspx?r[0]=" + dt.Rows[i]["UserID"] + "&r[1]=" + dt.Rows[i]["AlbumID"] + "\">\n";
                listSTR+="<img alt=\"" + dt.Rows[i]["Title"] + ",有" + dt.Rows[i]["ImagesCount"] + "张照片\" src=\"" + this.GetSmallPic(ab.CoverPath((int)dt.Rows[i]["AlbumID"]), 1) + "\" align=\"absmiddle\" /></a>\n";
                listSTR+="<span><a href=\"home/albumAlbumview.aspx?r[0]=" + dt.Rows[i]["UserID"] + "&r[1]=" + dt.Rows[i]["AlbumID"] + "\">" + JuSNS.Common.Input.GetSubString(dt.Rows[i]["Title"].ToString(), 14) + "</a></span>\n";
                listSTR += "</li>\n";
            }
          return listSTR;
        }

        protected string GetRecUser()
        {
            string listSTR = string.Empty;
            int ReCount, PgCount;
            int PageIndex = 1;
            DataTable dt = UtilPage.GetPage("Friend_Index_Rec_aspx", PageIndex, 12, out ReCount, out PgCount, null);
            Home.Album ab = new Home.Album();
            JuSNS.Home.User u = new JuSNS.Home.User();
            int gRowscount = dt.Rows.Count;
            for (int i = 0; i < gRowscount; i++)
            {
                listSTR += "<li><a href=\"user/" + JuSNS.Common.Public.URLWrite(string.Empty, "r", dt.Rows[i]["UserID"].ToString()) + "\">\n";
                listSTR += "<img alt=\"" + dt.Rows[i]["UserName"] + "\" src=\"" + this.GetHeadImage(Convert.ToInt32(dt.Rows[i]["UserID"].ToString()), 1) + "\"  align=\"absmiddle\" />\n";
                listSTR += "<span>" + JuSNS.Common.Input.GetSubString(dt.Rows[i]["UserName"].ToString(), 8) + "</span></a>\n";
                listSTR += "</li>\n";
            }
            return listSTR;
        }

        protected string GetRecBlog()
        {
            string listSTR = string.Empty;
            int ReCount, PgCount;
            int PageIndex = 1;
            DataTable dt = UtilPage.GetPage("BlogList_Index_Rec_aspx", PageIndex, 10, out ReCount, out PgCount, null);
            Home.Album ab = new Home.Album();
            JuSNS.Home.User u = new JuSNS.Home.User();
            int gRowscount = dt.Rows.Count;
            for (int i = 0; i < gRowscount; i++)
            {
                listSTR += "<li><a href=\""+rooDir+"/blog/b" + dt.Rows[i]["ID"].ToString() + ".aspx\">" + JuSNS.Common.Input.GetSubString(dt.Rows[i]["Title"].ToString(), 32) + "</a>\n";
                listSTR += "</li>\n";
            }
            return listSTR;
        }

        protected string GetRecGroup()
        {
            string listSTR = string.Empty;
            int ReCount, PgCount;
            int PageIndex = 1;
            DataTable dt = UtilPage.GetPage("Group_Index_Rec_aspx", PageIndex, 3, out ReCount, out PgCount, null);
            int gRowscount = dt.Rows.Count;
            for (int i = 0; i < gRowscount; i++)
            {
                listSTR += "<li><div class=\"nl\"><a href=\"home/group/group.aspx?GroupID=" + dt.Rows[i]["GroupID"].ToString() + "\"  target=\"_blank\">\n";
                listSTR += "<img alt=\"" + dt.Rows[i]["GroupName"] + "\" src=\"" + this.GetGroupHead(dt.Rows[i]["Portrait"].ToString()) + "\"  align=\"absmiddle\" /></a></div>\n";
                listSTR += "<div class=\"nl padding10\"><div class=\"bold\"><a target=\"_blank\" href=\"home/group/group.aspx?GroupID=" + dt.Rows[i]["GroupID"].ToString() + "\">" + dt.Rows[i]["GroupName"].ToString() + "</a></div>\n";
                listSTR += "<div class=\"gmg\">\n";
                UserGroup ug = new UserGroup();
                DataTable dp = ug.GetUserGroupDis(Convert.ToInt32(dt.Rows[i]["GroupID"].ToString()), 3);
                if (dp != null && dp.Rows.Count > 0)
                {
                    for (int j = 0; j < dp.Rows.Count; j++)
                    {
                        listSTR += "<div>· <a href=\"home/group/topic.aspx?disID=" + dp.Rows[j]["ID"].ToString() + "\" target=\"_blank\">" + dp.Rows[j]["Topic"].ToString() + "</a></div>\n";
                    }
                }
                else
                {
                    listSTR += "" + dt.Rows[i]["Bulletin"].ToString() + "\n";
                }
                listSTR += "</div></div></li>\n";
                dp.Clear(); dp.Dispose();
            }
            return listSTR;
        }

        protected void loadPro()
        {
            Dict dict = new Dict();
            IList<DictAreaInfo> list = dict.GetArea();
            foreach (DictAreaInfo info in list)
            {
                if (info.ParentID.Equals(0))
                {
                    province += "<option value=\"" + info.ID + "\">" + info.Name + "</option>";
                }
                else
                {
                    if (!cityarray.Equals(string.Empty))
                        cityarray += ",";
                    cityarray += "new Array('" + info.ParentID + "','" + info.ID + "','" + info.Name + "')";
                }
            } DataBind();
        }
    }
}
