using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using JuSNS.Home;
using JuSNS.Model;
using JuSNS.Common;
using JuSNS.Config;

namespace JuSNS.Web
{
    public partial class InviteReg : JuSNS.UI.Page.BasePage
    {
        protected string province = string.Empty;
        protected string cityarray = string.Empty;
        protected bool succeed = false;
        protected string error = string.Empty;
        protected string email = string.Empty;
        protected InviteInfo info;
        protected Dictionary<string, string> frnd;
        protected string code;
        protected int invitemode = (int)EnumFriendInviteMode.Email;
        protected string isRegMobile = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!isTimeOut())
                {
                    Response.Redirect(rooDir + "/home");
                }
                string RegSwitch = Public.GetXMLValue("OpenReg");
                if (RegSwitch == "0")
                {
                    PageError("管理员禁止注册！", Public.GetXMLValue("Url") + rooDir, true);
                }
                if (JuSNS.Common.Public.GetXMLValue("isRegMobile") == "1")
                {
                    isRegMobile = "或手机";
                }

                if (Request.Form["Register"] == "Submit")
                {
                    DoRegister();
                }
                if (!string.IsNullOrEmpty(Request["r"]))
                {
                    try
                    {
                        code = Request["r"].Trim();
                        EnumFriendInviteMode mode = EnumFriendInviteMode.Email;
                        JuSNS.Home.User us = new User();
                        if (Request.QueryString["a"] == "url")
                        {
                            #region url邀请
                            string _code = DES.Decrypt(Input.URLDecode(code), SecretConfig.InviteKey, SecretConfig.InviteIV);
                            string[] arrcode = _code.Split(SecretConfig.InviteSeparator);
                            if (arrcode.Length == 2)
                            {
                                code = arrcode[0];
                                mode = EnumFriendInviteMode.URL;
                                invitemode = (int)mode;
                            }
                            else
                            {
                                PageError("参数无效(length)，请与系统管理员联系！", "InviteReg.aspx");
                            }
                            #endregion
                        }
                        info = us.GetInviteInfo(code, mode, out frnd);
                        if (!string.IsNullOrEmpty(info.Invitee))
                        {
                            this.TxtEmail.Disabled = true;
                        } 
                        if (mode == EnumFriendInviteMode.URL)
                        {
                            info.Postscript = JuSNS.Common.Public.GetXMLValue("inviteReg").Replace("{siteName}", UiConfig.SiteName);
                        }
                    }
                    catch (Exception ex)
                    {
                        PageError(ex.Message, "");
                    }
                }
                else
                {
                    PageError("参数不完整", "InviteReg.aspx");
                }
                if (!succeed)
                {
                    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();
            }
        }

        /// <summary>
        /// 注册
        /// </summary>
        protected void DoRegister()
        {
            UserInfo ui = new UserInfo();
            ui.Username = Request["TxtName"];
            ui.Password = Request["TxtPassword"];
            ui.Province = Convert.ToInt32(Request["SlctProvince"]);
            ui.City = Convert.ToInt32(Request["SlctCity"]);
            EnumFriendInviteMode mode = EnumFriendInviteMode.Email;
            if (Convert.ToInt32(Request["mode"]) == (int)EnumFriendInviteMode.URL)
            {
                mode = EnumFriendInviteMode.URL;
                ui.Email = email = Request["TxtEmail"];
            }
            else
            {
                ui.Email = Request["TxtEmails"];
            }
            JuSNS.Home.User user = new User();
            int userId;
            UserBasicInfo bi = new UserBasicInfo();
            bool isFull = false;
            bi.Sex = Convert.ToInt32(Request["Slctgender"]);
            if (string.IsNullOrEmpty(Request["Slctgender"])) 
            { isFull = true; }
            if (isFull) { error = "所有项目必须填写！"; }

            EnumRegister ret = user.InviterRegister(ui, bi, mode, Request["r"], out userId);
            if (ret == EnumRegister.Succeed || ret == EnumRegister.EmailMayNotSend)
            {
                if (mode == EnumFriendInviteMode.Email)
                {
                    JuSNS.UI.Page.UserPage.SetCookie(userId, ui.Username, Input.MD5(ui.Password, false), "", false);
                    Response.Redirect("" + rooDir + "/home/space/edit.aspx?f=1");
                }
                else
                {
                        string RegVert = JuSNS.Common.Public.GetXMLValue("RegVer");
                        if (RegVert == "0")
                        {
                            JuSNS.UI.Page.UserPage.SetCookie(userId, ui.Username, Input.MD5(ui.Password, false), "", false);
                            Response.Redirect("" + rooDir + "/home/space/edit.aspx?f=1");
                        }
                        else
                        {
                            if (ret == EnumRegister.EmailMayNotSend)
                            {
                                error = "Email(" + ui.Email + ")未发送成功。请重新<a href=\"EmailActive.aspx?email=" + ui.Email + "\">发送邮件</a>。";
                            }
                            else
                            {
                                DisSucc(ui.Email);
                            }
                        }
                }
            }
            else if (ret == EnumRegister.EmailRepeat)
            {
                error = "该Email("+ui.Email+")地址已注册过帐户";
            }
            else if (ret == EnumRegister.InvalidCode)
            {
                error = "该邀请验证码无效";
            }
            else if (ret == EnumRegister.RegInviteCode)
            {
                error = "该邀请邮箱(" + ui.Email + ")已经注册";
            }
            else
            {
                error = "系统错误,请稍后再试";
            }
            Response.Redirect(rooDir + "/?r=" + error + "");
        }
        /// <summary>
        /// 显示成功
        /// </summary>
        private void DisSucc(string email)
        {
            Response.Redirect(rooDir + "/EURegisterResult.aspx?email=" + JuSNS.Common.Input.URLEncode(email));
        }
    }
}

