using System;
using System.Data;
using System.Configuration;
using System.Web;

using AVC.Passport;

public class LoginPageBase : PageBase
{
	private DataSet _UserRights = null;

	public LoginPageBase()
	{
       this.Load += new System.EventHandler(this.CheckLogin);
	}

	// 定义私有变量和常量
	protected string SubSystemID = System.Configuration.ConfigurationManager.AppSettings["SubSystemID"];
	protected string USERNAME = "UserName";
	protected string USERID = "UserID";
	private string LANGUAGEID = "LanguageID";
    
	/// <summary>
	/// 获取或设置语言编号
	/// </summary>
	protected	string LanguageID
	{
		get
		{
			return (string)ViewState[LANGUAGEID];
		}
		set
		{
			ViewState[LANGUAGEID] = value;
		}
	}

	/// <summary>
	/// 默认语言
	/// </summary>
	protected	string DefaultLanguageID
	{
		get
		{
			DataTable dtLanguages = Languages;
			DataRow[] drDefault = dtLanguages.Select("DefaultLanguage=1");
			if(drDefault.Length == 0)
			{
				return (string)dtLanguages.Rows[0]["LanguageID"];
			}
			else
			{
				return (string)drDefault[0]["LanguageID"];
			}
		}
	}

	/// <summary>
	/// 获取一个值，表示是否自动从简体中文转到繁体中文
	/// </summary>
	protected bool AutoSC2TCConvert
	{
		get
		{
			return true;
		}
	}

	/// <summary>
	/// 获取一个值，表示是否自动从繁体中文转到简体中文
	/// </summary>
	protected bool AutoTC2SCConvert
	{
		get
		{
			return true;
		}
	}

	/// <summary>
	/// 获取系统所支持的所有语言
	/// </summary>
	protected DataTable Languages
	{
		get
		{
			// 获取语言数据并绑定
			string strLanguagePath = Server.MapPath(@"\") + @"\Language.xml";

			DataSet dsLanguages = new DataSet();
			dsLanguages.ReadXml(strLanguagePath);
			DataTable dtLanguages = dsLanguages.Tables["Languages"];

			return dtLanguages;
		}
	}

	/// <summary>
	/// 在加载页面前检验用户是否登录。
	/// 如果未登录，则转向default.aspx页面。
	/// </summary>
	private void CheckLogin(object sender, System.EventArgs e)
	{
		// 如果用户未登录，则转向
		if(UserName == null || UserName == "")
		{
			Server.Transfer("~/Login.aspx");
		}

		ClientScript.GetPostBackEventReference(this,"");

		if(!IsPostBack)
		{
			// 获取来源地址
			string strSourceUrl = Request.UrlReferrer == null ? null : Request.UrlReferrer.Host;

			strSourceUrl = Request.ServerVariables["HTTP_REFERER"];
			ViewState["_SourceUrl"] = strSourceUrl;
			if(ViewState["_SourceUrl"] != null)
				ViewState["_SourceUrl"] = ((string)ViewState["_SourceUrl"]).Replace("&","[and]");
		}

        if (!ClientScript.IsStartupScriptRegistered(this.GetType(), "ClientScripts"))
		{
			string strScript = @"<script language=javascript>
// 在普通控件上，把回车变成tab。
function window_onkeypress(){
var test;
if(event.keyCode == 13){
	test=(event.srcElement.tagName=='TEXTAREA' || event.srcElement.type=='button' || event.srcElement.type=='reset' || event.srcElement.type=='submit')?true:false;
	if(!test)
		event.keyCode = 9;
}
if(event.keyCode==116 || (event.ctrlKey && event.keyCode==82)){
	event.keyCode=0;
	event.returnValue=false;
}
}
// 在提交的时候切换
function BeforeSubmit(ControlID){
if(typeof(Page_ClientValidate) == 'function'){
	if(!Page_ClientValidate()){
		document.forms[0].style.display='inline';
		__tblSubmitImage.style.display = 'none';
        return false;
	}
    else{
        document.forms[0].style.display='none';
        __tblSubmitImage.style.display = 'inline';
        return true;
    }
}
}
</script>";

			ClientScript.RegisterStartupScript(this.GetType(),"ClientScripts",strScript);
		}
	}

	/// <summary>
	/// 获取到此页的URL地址
	/// </summary>
	protected string SourceUrl
	{
		get
		{
			if(ViewState["_SourceUrl"] != null)
				return ((string)ViewState["_SourceUrl"]).Replace("[and]","&");
			else
				return "";
		}
	}

	override protected void OnInit(EventArgs e)
	{
		base.OnInit(e);
	}

	/// <summary>
	/// 验证用户是否具有某个子系统的某个权限
	/// </summary>
	/// <param name="strSubSystemID">子系统编号</param>
	/// <param name="strUserName">用户名</param>
	/// <param name="strRightName">权限名</param>
	/// <returns>true：有权；false：无权</returns>
	protected bool CheckRight(string strRightName)
	{
		if(_UserRights == null)
		{
			string strAppPath = Server.MapPath(@"~\CertifyPool\" + SubSystemID) + @"\";
			strAppPath = strAppPath.Replace("/",@"\").Replace(@"\\",@"\");
			string strPoolName = strAppPath + UserID.ToString() + ".cer";

//				Alogrim objAlogrim = new Alogrim(Alogrim.SymmProvEnum.DES);
//				objAlogrim.Key = KEY;
//				objAlogrim.IV = IV;
//
//				// 解密
//				FileStream fsEncrypt = new FileStream(strPoolName,FileMode.Open);
//				MemoryStream msSource = new MemoryStream();
//				objAlogrim.Decrypting(fsEncrypt,msSource);
//				fsEncrypt.Close();
//
//				// 加载到XML对象中
//				msSource.Position = 0;

			_UserRights = new DataSet();
			_UserRights.ReadXml(strPoolName);
//				msSource.Close();
		}
		if(_UserRights.Tables[SubSystemID] == null)
			return false;

		return (_UserRights.Tables[SubSystemID].Select("RightName='" + strRightName + "'").Length != 0);
	}

	/// <summary>
	/// 判断用户是否具有一组权限的所有权限
	/// </summary>
	/// <param name="arrRightName">权限组</param>
	/// <returns>true：用户具有所有权限，false，用户不具有所有权限</returns>
	protected bool CheckAllRights(string[] arrRightName)
	{
		bool Flag = true;
		for(int i=0;i<arrRightName.Length;i++)
		{
			if(!CheckRight(arrRightName[i]))
			{
				Flag = false;
				break;
			}
		}
		return Flag;
	}

	/// <summary>
	/// 判断用户是否具有一些权限中的某一个
	/// </summary>
	/// <param name="arrRightName">权限组</param>
	/// <returns>true：用户至少具有权限中的一个，false：用户不具有权限组中的任何权限</returns>
	protected bool CheckOneRight(string[] arrRightName)
	{
		bool Flag = false;
		for(int i=0;i<arrRightName.Length;i++)
		{
			if(CheckRight(arrRightName[i]))
			{
				Flag = true;
				break;
			}
		}
		return Flag;
	}

	/// <summary>
	/// 转向到警告页
	/// </summary>
	/// <param name="ReturnUrl">要返回的页面</param>
	protected void NoRightAlert()
	{
		Response.Redirect("../ShowMessagePage.aspx?Title=没有权限&Message=您没有权限进行此操作！&ReturnUrl=" + SourceUrl);
	}

	/// <summary>
	/// 显示服务器端信息，一般在操作成功或者失败时显示
	/// </summary>
	/// <param name="Title">显示标题</param>
	/// <param name="Message">信息内容</param>
	/// <param name="ReturnUrl">返回的页面</param>
	protected void ShowServerMessage(string Title,string Message,string ReturnUrl)
	{
		Response.Redirect("/ShowMessagePage.aspx?title=" + Title + "&message=" + Message + "&returnurl=" + ReturnUrl.Replace("&","[and]"),true);
	}

	/// <summary>
	/// 显示服务器端信息，一般在操作成功或者失败时显示。此方法返回的地址是这个页面的来源地址
	/// </summary>
	/// <param name="Message">信息内容</param>
	protected void ShowServerMessage(string Message)
	{
		Response.Redirect("/ShowMessagePage.aspx?title=操作成功&message=" + Message + "&returnurl=" + SourceUrl,true);
	}

	/// <summary>
	/// 当前用户名
	/// </summary>
	protected string UserName
	{
		get
		{
			//return (string)Session[USERNAME];
			return UserTicket.UserName;
		}
	}

	/// <summary>
	/// 当前用户ID
	/// </summary>
	protected int UserID
	{
		get
		{
			return UserTicket.UserID;
			//return (int)Session[USERID];
		}
	}
}