using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using MySql.Data.MySqlClient;
using System.Text.RegularExpressions; 


using Security;
namespace Security
{
    public partial class ArticleAdd : PageBase
    {
		DataTable dt = null;
		string className = null;
		
		///定义树节点的结构体
		struct ClassTreeNode{
			public string ID;
			public string Name;
			public string OutLinkHref;
			public int Level;
		}
		
		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
            {
				MysqlHelp mh = new MysqlHelp();
				dt = mh.GetDatabysql("Select * From Class4DeepSoon Order By Id");
				///显示ID=?的节点+孩子节点，并设定层级初值level
				ClassTreeNode nd;
				nd.ID="0";               ///节点ID
				nd.Name="请选择所属栏目";        ///节点Name
				nd.OutLinkHref = "";     ///节点外链OutLinkHref
				nd.Level=0;              ///节点Level
				///添加栏目下拉菜单
				ListItem li=new ListItem(nd.Name,"Enable"+nd.ID);
				li.Attributes.Add("style","color:#1081BC;");
				this.dropListClassName.Items.Add(li);
				showNodes(nd);
				
				string classID = Request.QueryString["classID"];
				className = Request.QueryString["className"];
				if(classID != null && className != null){			
					///初始化表单数据
					ListItem item=this.dropListClassName.Items.FindByValue(classID);
					if(item != null)
					{
						item.Selected = true;
					}
					this.labelAdminTitle.Text = className+"/添加";
					this.labelAddInfor.Text = "<a href='deepSoonArticleAdmin.aspx?classID="+classID+"&className="+className+"'>文章管理</a> | <a href='DeepSoonArticleTree.aspx'>返回文章树</a>";
					this.txtAuthor.Text = base.strUser;
				}
				else{
					this.labelAdminTitle.Text = "发布文章";
					this.txtAuthor.Text = base.strUser;
				}
			}
			
			this.btnAdd.Attributes.Add("onClick", "hiddFieldArticle.value = document.getElementById('contentBox').contentWindow.document.body.innerHTML;var textBriefInfor = document.getElementById('contentBox').contentWindow.document.body.innerText;if(textBriefInfor.length > 120)textBriefInfor = textBriefInfor.substring(0,119);hiddFieldBriefInfor.value = textBriefInfor;"); 
			
        }
		
		protected void btnAdd_Click(object sender, EventArgs e)
		{
			string title = this.txtTitle.Text.Replace("'", "").Replace("select", "").Replace("delete", "").Replace("update", "").Replace("insert", "");
			string source = this.txtSource.Text.Replace("'", "").Replace("select", "").Replace("delete", "").Replace("update", "").Replace("insert", "");
			string author = this.txtAuthor.Text.Replace("'", "").Replace("select", "").Replace("delete", "").Replace("update", "").Replace("insert", "");
			string classId = this.dropListClassName.SelectedItem.Value;
			string article = this.hiddFieldArticle.Value.Replace("'","").Replace("<div>","<p>").Replace("<DIV>","<p>").Replace("</div>","</p>").Replace("</DIV>","</p>").Replace("<DIV","<p ").Replace("<div","<p ");
			string briefInfor = this.hiddFieldBriefInfor.Value; 
			if(briefInfor.Length>120)briefInfor = briefInfor.Substring(0,120);
			briefInfor = Regex.Replace(briefInfor, @"\s*|\t|\r|\n", "", RegexOptions.IgnoreCase);
			briefInfor = Regex.Replace(briefInfor, "（", "(", RegexOptions.IgnoreCase);
			briefInfor = Regex.Replace(briefInfor, "）", ")", RegexOptions.IgnoreCase);		
			string thumbnailImage = getImageUrl(this.hiddFieldArticle.Value);
			bool classIdEnable = classId.Contains("Enable");
			
			if(classIdEnable){
				labelAddInfor.Text = "选择的所属栏目不合法，不允许外部栏目！";
			}
			else{
				if(title != "" && source != "" && author != "" && !classIdEnable && article != "" && briefInfor != ""){
					string Values = "'"+title+"','"+source+"','"+author+"','"+classId+"','"+article+"','"+briefInfor+"','"+thumbnailImage+"',True";
					///创建数据连接对象：
					MysqlHelp mh = new MysqlHelp();
					mh.Runsql("Insert Into Article4DeepSoon(Title,Source,Author,ClassID,Article,BriefInfor,thumbnailImage,isPass) Values ("+Values+")");
					labelAddInfor.Text = "文章已添加！"+briefInfor;
					Response.Redirect("DeepSoonArticleAdmin.aspx?ClassID="+classId+"&ClassName="+className);
				}
				else {
					labelAddInfor.Text = "文章信息没有填写完整！";
				}
			}
		}
		
		/// 获取文中图片地址
		public static string getImageUrl(string content)
		{ 
			string imgSrcValue = "";
			MatchCollection mc = Regex.Matches(content, @"<img(?:(?!src).)*src=(['""]?)(?<path>.*?)/(?<name>[^/\s'""]*)\1", RegexOptions.IgnoreCase);
			if( mc.Count > 0){
				Match m = mc[0];
				imgSrcValue += m.Groups["path"].Value + "/";
				imgSrcValue += m.Groups["name"].Value;
			}
			return imgSrcValue;
		} 
		
		///显示节点+孩子节点
		private void showNodes(ClassTreeNode node)
        {
			this.showNodesFunction(node);
			///this.myLabel.Text = treeStr;
			
		}
		///显示节点递归函数
		private void showNodesFunction(ClassTreeNode node)
        {			
			DataRow [] rows = dt.Select("fatherId = '"+node.ID+"'");///筛选node的孩子节点 
			string spaceStr = "";
			foreach(DataRow dr in rows)///循环孩子节点
            {
				ClassTreeNode childNd;
				childNd.ID = dr["id"].ToString();                    ///孩子节点ID
                childNd.Name = dr["name"].ToString();                ///孩子节点Name
				childNd.OutLinkHref = dr["outLinkHref"].ToString();  ///孩子节点外链OutLinkHref
				childNd.Level = node.Level+1; 
				spaceStr = "";
				///孩子节点Level
				for(int i=0;i<childNd.Level;i++){
					spaceStr += "--";
				}
				///添加栏目下拉菜单
				///判断当前节点是否有孩子节点
				bool isFather = dr["childID"].ToString().Contains(",");
				if(isFather){
					ListItem li=new ListItem(spaceStr+"|*"+childNd.Name+"*|","Enable"+childNd.ID);
					li.Attributes.Add("style","color:#1081BC;");
					this.dropListClassName.Items.Add(li);
				}
				else{
					ListItem li=new ListItem(spaceStr+"|"+childNd.Name+"|",childNd.ID);
					this.dropListClassName.Items.Add(li);
				}
				this.showNodesFunction(childNd);//递归调用自身  
            }
		}

	}//end class
}//end nameSpace