namespace SK.MemberWeb.Templates.Default
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;
	using System.Text.RegularExpressions;
	using SK.MemberBLL;
	using System.Web.Security;

	/// <summary>
	///		cu_Reg 的摘要说明。
	/// </summary>
	public class cu_Reg : BaseControl
	{
		protected SK.MemberWeb.Controls.ControlHolder ControlHolder5;
		protected System.Web.UI.WebControls.TextBox txtMemberName;
		protected System.Web.UI.WebControls.TextBox txtPassword;
		protected System.Web.UI.WebControls.TextBox txtRePassword;
		protected System.Web.UI.WebControls.TextBox txtEmail;
		protected System.Web.UI.WebControls.Button btnSave;
		protected SK.MemberWeb.Controls.ControlHolder ControlHolder1;
		protected System.Web.UI.WebControls.RadioButton rbtnCompany;
		protected System.Web.UI.WebControls.RadioButton rbtnMember;
		protected System.Web.UI.WebControls.TextBox txtTrueName;
		protected System.Web.UI.WebControls.DropDownList lstCompany;
		MemberSystem member = new MemberSystem();

		private void Page_Load(object sender, System.EventArgs e)
		{
			// 在此处放置用户代码以初始化页面
			btnSave.Attributes["onclick"] = "return cu_Reg_CheckInput();";
			rbtnCompany.Attributes["onclick"] = "changeCompany();";
			rbtnMember.Attributes["onclick"] = "changeCompany();";

			if(!IsPostBack)
				BindData();

		}

		#region Web 窗体设计器生成的代码
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		设计器支持所需的方法 - 不要使用代码编辑器
		///		修改此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{
			this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void BindData()
		{
			lstCompany.DataSource = member.MemberList_Company();
			lstCompany.DataTextField = "TrueName";
			lstCompany.DataValueField = "MemberID";
			lstCompany.DataBind();

		}

		private void btnSave_Click(object sender, System.EventArgs e)
		{
			/*if(Session["verifycode"]==null)
			{
				this.DisplayAlert("超时，验证码丢失，请刷新登录页");
				return;
			}
			if(txtVerifyCode.Text!=Session["verifycode"].ToString())
			{
				this.DisplayAlert("验证码错误");
				return;
			}*/
			if(!Regex.IsMatch(txtMemberName.Text,Main.GetValue("Regex_MemberName").ToString()))
			{
				this.DisplayAlert("所使用的用户名不符合规则");
				return;
				//this.AlertAndRedir("所使用的用户名不符号规则!","Reg.aspx");
			}
			if(!Regex.IsMatch(txtEmail.Text,@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
			{
				this.DisplayAlert("输入的Email不符合规则");
				return;
				//this.AlertAndRedir("所使用的用户名不符号规则!","Reg.aspx");
			}
			if(member.Exists_MemberName(txtMemberName.Text)!=null)
			{
				this.DisplayAlert("此用户名已经注册过，不能重复注册");
				this.GiveFocus(txtMemberName);
				return;
			}
			if(member.Exists_Email(txtEmail.Text))
			{
				this.DisplayAlert("此Email已经注册过，不能重复注册");
				this.GiveFocus(txtEmail);
				return;
			}
			BasePape des = new BasePape();
			des.EncryptKey = "sorkednc";
			des.InputString = txtPassword.Text;
			des.DesEncrypt();
			string EncryptString = des.OutString;

			//member.Add("",txtMemberName.Text,txtTrueName.Text,EncryptString,dpSex.SelectedValue,txtEmail.Text,txtEmail2.Text,dpQuestion.SelectedValue,txtAnswer.Text,cpBirthDay.Value,txtZip.Text,dpCountry.SelectedValue,dpProvince.Value,txtCity.Text,0,Utils.CreateRndStr(20));
			member.Add("",txtMemberName.Text,txtTrueName.Text,EncryptString,"1",txtEmail.Text,"",null,"",DateTime.Now.AddYears(-30),"",null,null,null,0,Utils.CreateRndStr(20));
			if(rbtnMember.Checked)
			{
				member.UpdateCompanyID(txtMemberName.Text,lstCompany.SelectedValue);
			}
			

			//Forum_MemberWS.Member forummember = new Forum_MemberWS.Member();
			//forummember.Rigister(txtMemberName.Text,txtPassword.Text,txtEmail.Text,null,null);
			bool NeedValidEmail = Convert.ToBoolean(Convert.ToInt16(Main.GetValue("NeedValidEmail")));
			if(NeedValidEmail)
			{
				try
				{
					DataRow drMember = member.Info_Name(txtMemberName.Text);
					string body = Main.GetValue("ActiveEmailBody").ToString();
					body = body.Replace("[[MemberID]]",drMember["MemberID"].ToString());
					body = body.Replace("[[MemberName]]",drMember["MemberName"].ToString());
					body = body.Replace("[[Password]]",txtPassword.Text);
					body = body.Replace("[[Email]]",drMember["Email"].ToString());
					body = body.Replace("[[EmailValidCode]]",drMember["EmailValidCode"].ToString());

					string subject = Main.GetValue("ActiveEmailSubject").ToString();
					subject = subject.Replace("[[MemberID]]",drMember["MemberID"].ToString());
					subject = subject.Replace("[[MemberName]]",drMember["MemberName"].ToString());
					subject = subject.Replace("[[Password]]",txtPassword.Text);
					subject = subject.Replace("[[Email]]",drMember["Email"].ToString());
					subject = subject.Replace("[[EmailValidCode]]",drMember["EmailValidCode"].ToString());

					bool inhtml = Convert.ToBoolean(Convert.ToInt16(Main.GetValue("ActiveEmailInHtml")));
					Utils.SendMail(txtEmail.Text,txtMemberName.Text,subject,body,inhtml?PatNorSoft.Mail.Message.Build.BodyPartFormat.HTML:PatNorSoft.Mail.Message.Build.BodyPartFormat.Plain);

					this.AlertAndRedir("注册成功","reg_ok.aspx?i=1&n="+txtMemberName.Text);
				}
				catch(Exception ex)
				{
					member.Delete_MemberName(txtMemberName.Text);
					this.DisplayAlert("向您填写的Email地址发送邮件时失败，请重新填写正确的Email或换一个Email");
					return;
				}
			}
			else
			{
				object MemberID    = member.Login(txtMemberName.Text,EncryptString);
				if(MemberID != DBNull.Value)
				{
					DataRow dr = member.Info(MemberID);
					member.UpdateCompany(MemberID,rbtnCompany.Checked);
					FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
						MemberID+";"+txtMemberName.Text,
						DateTime.Now,
						DateTime.Now.AddMinutes(30),
						true,
						dr["Roles"].ToString(),
						FormsAuthentication.FormsCookiePath);
					string hash = FormsAuthentication.Encrypt(ticket);
					HttpCookie cookie = new HttpCookie(
						FormsAuthentication.FormsCookieName, 
						hash); 
					cookie.Domain = this.Domain;

					if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

					Response.Cookies.Add(cookie);
				}
				Response.Redirect("reg_ok.aspx?n="+txtMemberName.Text);
			}
		}
	}
}
