using System;
using System.Data;
using System.Configuration;
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 zj123.Model;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections;
namespace WebUI.html
{
    public class EasyHtml
    {
        public bool MakeHtml(string artid)
        {
           
            bool succ = false;
            int len = Convert.ToInt32(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["titlelength"]) ?? "20");
            //读取数据
            string sql = string.Format("select a.*,b.ClassName,b.Depth,b.OrderBy,b.isTop,b.isList,b.IsLinks,b.Links,b.PicURL,b.ParentID,b.TemplateoutId,b.TemplateinNeiId,b.TemplateinListId from article a,zone b  where a.classid=b.classid and a.Status=3 and a.articleid={0}", artid);
            DataTable dt = DbHelperOleDb.Query(sql).Tables[0];
            if(dt.Rows.Count>0)
            {
            //外模板
                string waitemp = "";
                DataTable waidt  =DbHelperOleDb.Query(string.Format("select * from template where TemplateID={0}",Convert.ToString(dt.Rows[0]["TemplateoutId"]).Trim())).Tables[0];
                if (waidt.Rows.Count > 0)
                {
                    waitemp = Convert.ToString(waidt.Rows[0]["TemplateContent"]);
                }
            //内模板
                string neitemp = "";
                DataTable neidt = DbHelperOleDb.Query(string.Format("select * from template where TemplateID={0}", Convert.ToString(dt.Rows[0]["TemplateinNeiId"]).Trim())).Tables[0];
                if (neidt.Rows.Count > 0)
                {
                    neitemp = Convert.ToString(neidt.Rows[0]["TemplateContent"]);
                }
                //替换模板
                waitemp = waitemp.Replace("$intemplate$", neitemp);
                //替换类型
                string tempclassname = classes.Common.GetP(Convert.ToString(dt.Rows[0]["classid"]));
                waitemp = waitemp.Replace("$ClassName$", tempclassname);
            #region "文章列表"
  
                //最新的文章
                System.Text.StringBuilder sbneartitle = new System.Text.StringBuilder("<div align=\"left\">");
                DataTable nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 order by updatetime desc").Tables[0];
                for (int i = 0; i < nearTitledt.Rows.Count; i++)
                {
                    sbneartitle.AppendFormat("<li><a href=\"{0}\">{1}</a></li>",Convert.ToString(nearTitledt.Rows[i]["HtmlPath"]),Convert.ToString(nearTitledt.Rows[i]["Title"]));
                }
                sbneartitle.Append("</ol></div>");
                waitemp = waitemp.Replace("$NearTitle$", sbneartitle.ToString());
                sbneartitle.Remove(0,sbneartitle.ToString().Length);
                if (waitemp.Contains("$OnTopTitle$"))
                {
                    sbneartitle.Append("<div align=\"left\">");

                    //固定
                    nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and OnTop=1 order by updatetime desc").Tables[0];
                    for (int i = 0; i < nearTitledt.Rows.Count; i++)
                    {
                    sbneartitle.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[i]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[i]["Title"]));
                    }
                    sbneartitle.Remove(0, sbneartitle.ToString().Length);
                    sbneartitle.Append("</ol></div>");
                    waitemp = waitemp.Replace("$OnTopTitle$", sbneartitle.ToString());
                    sbneartitle.Remove(0, sbneartitle.ToString().Length);
                }
             
                if (waitemp.Contains("$HitsTitle$"))
                {
                    sbneartitle.Append("<div align=\"left\">");
                    //热门
                    nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and Hits>1000 order by Hits desc,updatetime desc").Tables[0];
                    for (int i = 0; i < nearTitledt.Rows.Count; i++)
                    {
                    sbneartitle.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[i]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[i]["Title"]));
                    }
                    sbneartitle.Append("</ol></div>");


                    waitemp = waitemp.Replace("$HitsTitle$", sbneartitle.ToString());
                    sbneartitle.Remove(0, sbneartitle.ToString().Length);
                }
        
                if (waitemp.Contains("$Elite$"))
                {
                    sbneartitle.Append("<div align=\"left\">");
                    //推荐Elite
                    nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and Elite=1 order by updatetime desc").Tables[0];
                    for (int i = 0; i < nearTitledt.Rows.Count; i++)
                    {
                    sbneartitle.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[i]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[i]["Title"]));
                    }

                    sbneartitle.Append("</ol></div>");
                    waitemp = waitemp.Replace("$Elite$", sbneartitle.ToString());

                    sbneartitle.Remove(0, sbneartitle.ToString().Length);
                }

            
           
                //相关Classid
                if (waitemp.Contains("$ClassTitle$"))
                {
                    sbneartitle.Append("<div align=\"left\">");
                    nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and classid=" + Convert.ToString(dt.Rows[0]["classid"]) + " order by updatetime desc").Tables[0];
                    for (int curr = 0; curr < nearTitledt.Rows.Count; curr++)
                    {
                        sbneartitle.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[curr]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[curr]["Title"]));
                    }

                    sbneartitle.Append("</ol></div>");
                    waitemp = waitemp.Replace("$ClassTitle$", sbneartitle.ToString());
                    sbneartitle.Remove(0, sbneartitle.ToString().Length);
                }

                //相关Classid
                if (waitemp.Contains("$LikeTitle$"))
                {
                    sbneartitle.Append("<div align='left'>");
                    DataTable dtlike = zj123.Model.Article.GetLike(artid);
                    for (int likei = 0; likei < dtlike.Rows.Count; likei++)
                    {
                        sbneartitle.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", Convert.ToString(dtlike.Rows[likei]["HtmlPath"]), Convert.ToString(dtlike.Rows[likei]["Title"]));
                    }
                    sbneartitle.Append("</ol></div>");
                    waitemp = waitemp.Replace("$LikeTitle$", sbneartitle.ToString());
                    sbneartitle.Remove(0, sbneartitle.ToString().Length);
                }

                    /////////////////////////////////////////////////////////////////////////////////////////////
            #endregion
                    //替换最新的数据
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (dt.Columns[j].ColumnName.Trim() == "Title")
                        {
                            string temp1 = "";
                            string temp2 = "";
                            string typefont = Convert.ToString(dt.Rows[0]["TitleFontType"]);
                            if (typefont == "0")
                            {
                                temp1 = "<strong>";
                                temp2 = "</strong>";
                            }
                            else if (typefont == "1")
                            {
                                temp1 = "<em>";
                                temp2 = "</em>";
                            }
                            else if (typefont == "2")
                            {
                                temp1 = "<strong><em>";
                                temp2 = "</strong></em>";
                            }
                            else
                            {

                            }
                            //System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex();
                            //Match match = Regex.Matches();
                            //reg.Replace(waitemp, Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]), 1, waitemp.IndexOf("$Title$"));
                            string temp11 = waitemp.Substring(0, waitemp.IndexOf("$Title$") + 8);
                            string temp22 = waitemp.Substring(waitemp.IndexOf("$Title$") + 8);
                            temp11 = temp11.Replace("$Title$", Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()])+"---"+Regex.Replace(Regex.Replace(tempclassname,"<[^>]*>",""),"[>|<]*",""));
                            temp22 = temp22.Replace("$Title$", "<font color='" + Convert.ToString(dt.Rows[0]["TitleFontColor"]) + "'>" + temp1 + Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]) + temp2 + "</font>");
                            waitemp = temp11 + temp22;
                            temp11 = null;
                            temp22 = null;
                            //waitemp = waitemp.Replace("$" + dt.Columns[j].ColumnName.Trim() + "$", "<font color='" + Convert.ToString(dt.Rows[0]["TitleFontColor"]) + "'>" +temp1+ Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]) +temp2+ "</font>");
                        }
                        else if (dt.Columns[j].ColumnName.Trim().ToLower() == "hits")
                        {
                            waitemp = waitemp.Replace("$" + dt.Columns[j].ColumnName.Trim() + "$", Convert.ToInt16(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]) > 1000 ? ("热门") : (""));
                        }
                        else if (dt.Columns[j].ColumnName.Trim().ToLower() == "ontop")
                        {
                            waitemp = waitemp.Replace("$" + dt.Columns[j].ColumnName.Trim() + "$", Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]).ToLower() == "true" ? ("置顶") : (""));
                        }
                        else if (dt.Columns[j].ColumnName.Trim().ToLower() == "elite")
                        {
                            waitemp = waitemp.Replace("$" + dt.Columns[j].ColumnName.Trim() + "$", Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]).ToLower().ToString() == "true" ? ("推荐") : (""));
                        }
                        else
                        {
                            waitemp = waitemp.Replace("$" + dt.Columns[j].ColumnName.Trim() + "$", Convert.ToString(dt.Rows[0][dt.Columns[j].ColumnName.Trim()]));
                        }

                    }
                //替换链表信息
                //$typejs$
                waitemp = waitemp.Replace("$typejs$", Convert.ToString(dt.Rows[0]["ClassID"]));
                //$numjs$
                waitemp = waitemp.Replace("$numjs$", "10");
                //$setjs$
                waitemp = waitemp.Replace("$setjs$","");
               
                ///js脚本信息


               //根据路径生成页面
                //路径 检查
                string path = System.Web.HttpContext.Current.Request.PhysicalApplicationPath.Trim()  + Convert.ToString(dt.Rows[0]["Links"]) + "\\" + Convert.ToDateTime(dt.Rows[0]["CreateTime"]).ToString("yyyy-MM");
                if(!Directory.Exists(path))
                  Directory.CreateDirectory(path);
              string filename = "\\"+ Convert.ToString(dt.Rows[0]["ArticleID"]) + ".html";
                using(StreamWriter sw = new StreamWriter(path+"\\"+filename,false,System.Text.Encoding.GetEncoding("gb2312")))
                {
                    sw.Write(waitemp);
                    sw.Flush();
                    sw.Close();
                }
                //修改文章转台
                try
                {
                    if (artid == null)
                        return false;
                    int j = int.Parse(artid);
                }
                catch
                {
                    return false;
                }

                string sql1 = string.Format("update article set iscreate=1,htmlpath='{0}' where articleid={1}", "/" + Convert.ToString(dt.Rows[0]["Links"]).Replace("\\\\", "/") + "/" + Convert.ToDateTime(dt.Rows[0]["CreateTime"]).ToString("yyyy-MM") + filename, artid);
                DbHelperOleDb.ExecuteSql(sql1);
               
            }
            else
            {
                return false;
            }
      

            return succ;
        }
        /// <summary>
        /// 生成列表页
        /// </summary>
        /// <param name="classid"></param>
        /// <returns></returns>
        public bool MakeList(string classid)
        {
            int len = Convert.ToInt32(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["titlelength"]) ?? "20");
            bool succ = false;
            try
         {        
          int i = int.Parse(classid);

         }
         catch
         {
          
       return false;
         }
            DataTable dt = DbHelperOleDb.Query(string.Format("select a.*,b.ClassName,b.Depth,b.OrderBy,b.isTop,b.isList,b.IsLinks,b.Links,b.PicURL,b.ParentID,b.TemplateoutlistId,b.TemplateoutId,b.TemplateinNeiId,b.TemplateinListId,b.keywords,b.[description] from article a,zone b  where a.classid=b.classid and  iscreate=1 and a.Status=3 and a.classid={0} order by a.UpdateTime desc,OnTop desc,Elite desc,Hits desc", classid)).Tables[0];
            if (dt.Rows.Count > 0)
            {
                string classpath = HttpContext.Current.Request.PhysicalApplicationPath + @"\" + Convert.ToString(dt.Rows[0]["Links"]).Trim();
                //读取外模板信息
                string templatewai = "";
                DataTable templatewaidt = DbHelperOleDb.Query(string.Format("select * from template where TemplateID={0}", Convert.ToString(dt.Rows[0]["TemplateoutlistId"]))).Tables[0];
                if (templatewaidt.Rows.Count > 0)
                {
                    templatewai = Convert.ToString(templatewaidt.Rows[0]["TemplateContent"]);
                }
                //根据类型替换标题
                string tempclassname = classes.Common.GetP(classid);
                templatewai = templatewai.Replace("$Title$", Convert.ToString(dt.Rows[0]["ClassName"]).Trim() +"--"+Regex.Replace(Regex.Replace(tempclassname,"<[^>]*>",""),"[<|>]*",""));
                templatewai = templatewai.Replace("$ClassTitleTop$", Convert.ToString(dt.Rows[0]["ClassName"]).Trim());
                templatewai = templatewai.Replace("$ClassName$", tempclassname);
                templatewai = templatewai.Replace("$Keyword$", Convert.ToString(dt.Rows[0]["Keywords"]).Trim());
                templatewai = templatewai.Replace("$Description$", Convert.ToString(dt.Rows[0]["Description"]).Trim());

                int zong = dt.Rows.Count;
                int size = 10;
                try
                {
                    size = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["pagesize"]);
                }
                catch
                {

                    size = 10;
                }
                int pagecount = zong % size == 0 ? (zong / 10) : (zong / 10 + 1);
                string listcontent = "";
                DataTable dtlist = DbHelperOleDb.Query(string.Format("select * from template where TemplateID={0}", Convert.ToString(dt.Rows[0]["TemplateinListId"]))).Tables[0];
                if (dtlist.Rows.Count > 0)
                {
                    listcontent = Convert.ToString(dtlist.Rows[0]["TemplateContent"]);
                }
                //// Match mat = Regex.Match(this.rtbconten.Text.Trim(), "<tablehead>(?<content>.*)<tableheadend><tablebody></tablebodyend><tablepage></tablepage><tablebottom></tablebottomend>", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                //// MessageBox.Show(mat.Groups["content"].Value);
                ////<tablehead>(?<content>.*)<tableheadend><tablebody></tablebodyend><tablepage></tablepage><tablebottom></tablebottomend>
                ////
                Match mat = Regex.Match(listcontent, "<tablehead>(?<head>.*)<tableheadend><tablebody>(?<body>.*)</tablebodyend><tablepage>(?<page>.*)</tablepage><tablebottom>(?<bottom>.*)</tablebottomend>",RegexOptions.IgnoreCase|RegexOptions.Multiline);
                string head = Convert.ToString(mat.Groups["head"]);
                string body = Convert.ToString(mat.Groups["body"]);
                string page = Convert.ToString(mat.Groups["page"]);
                string bottom = Convert.ToString(mat.Groups["bottom"]);
                //循环生成分页
                for (int i = 0; i < pagecount; i++)
                {
                    //System.Text.StringBuilder sbneilist = new System.Text.StringBuilder("<TABLE cellSpacing=0 cellPadding=0 width=760 border=0><TBODY>");
                    System.Text.StringBuilder sbneilist = new System.Text.StringBuilder(head);


                    int l = 0;
                    for (int j = (i * size < zong) ? (i * size) : (zong); j < ((i + 1) * size < zong ? ((i + 1) * size) : (zong)); j++)
                    {
                        //sbneilist.Append(" <TR><TD vAlign=top align=center bgColor=#f7f7f7 >");
                        //string temp = listcontent;
                        string temp = body;
                        for (int k = 0; k < dt.Columns.Count; k++)
                        {
                          
                            temp = temp.Replace("$" + dt.Columns[k].ColumnName.Trim() + "$", Convert.ToString(dt.Rows[j][dt.Columns[k].ColumnName.Trim()]));
                        }
                        if ((++l) % 5 == 0)
                        {
                            sbneilist.Append(temp).Append("<dd class=\"l\"></dd>");
                        }
                        else
                        {
                            sbneilist.Append(temp);
                        }
                      
                        //sbneilist.Append("</td></tr>");

                    }

                    //sbneilist.Append("<TR><TD height=36>").Append(classes.Common.GetPage(i + 1, size, zong)).Append("</td></tr>");
                    sbneilist.Append(page.Replace("¥pages¥", classes.Common.GetPage(i + 1, size, zong)));
                    // sbneilist.Append("</tbody></table>");
                    sbneilist.Append(bottom);

                    #region "文章列表"

                    //最新的文章
                    System.Text.StringBuilder sbneartitle = new System.Text.StringBuilder("");
                    DataTable nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 order by updatetime desc").Tables[0];
                    for (int curr = 0; curr < nearTitledt.Rows.Count; curr++)
                    {
                        sbneartitle.AppendFormat("<li>·<a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[curr]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[curr]["Title"]));
                    }
                    sbneartitle.Append("");
                    templatewai = templatewai.Replace("$NearTitle$", sbneartitle.ToString());
                    sbneartitle.Remove(0, sbneartitle.ToString().Length);
                    sbneartitle.Append("");

                    //固定
                    nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and OnTop=1 order by updatetime desc").Tables[0];
                    for (int curr = 0; curr < nearTitledt.Rows.Count; curr++)
                    {
                        sbneartitle.AppendFormat("<li>·<a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[curr]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[curr]["Title"]));
                    }
                    sbneartitle.Remove(0, sbneartitle.ToString().Length);
                    sbneartitle.Append("");
                    templatewai = templatewai.Replace("$OnTopTitle$", sbneartitle.ToString());
                    sbneartitle.Remove(0, sbneartitle.ToString().Length);
                    sbneartitle.Append("");
                    //热门
                    nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and Hits>1000 order by Hits desc,updatetime desc").Tables[0];
                    for (int curr = 0; curr < nearTitledt.Rows.Count; curr++)
                    {
                        sbneartitle.AppendFormat("<li>·<a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[curr]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[curr]["Title"]));
                    }
                    sbneartitle.Append("");


                    templatewai = templatewai.Replace("$HitsTitle$", sbneartitle.ToString());
                    sbneartitle.Remove(0, sbneartitle.ToString().Length);
                    sbneartitle.Append("");
                    //推荐Elite
                    nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and Elite=1 order by updatetime desc").Tables[0];
                    for (int curr = 0; curr < nearTitledt.Rows.Count; curr++)
                    {
                        sbneartitle.AppendFormat("<li>·<a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[curr]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[curr]["Title"]));
                    }
                    sbneartitle.Remove(0, sbneartitle.ToString().Length);
                    sbneartitle.Append("");
                    templatewai = templatewai.Replace("$Elite$", sbneartitle.ToString());
                    sbneartitle.Append("");
                    //相关Classid
                    nearTitledt = DbHelperOleDb.Query("select top 10 case when len(title)>" + len + " then substring(title,1," + len + ") else title end as Title,HtmlPath from article where iscreate=1 and classid=" + classid + " order by updatetime desc").Tables[0];
                    for (int curr = 0; curr < nearTitledt.Rows.Count; curr++)
                    {
                        sbneartitle.AppendFormat("<li>·<a href=\"{0}\">{1}</a></li>", Convert.ToString(nearTitledt.Rows[curr]["HtmlPath"]), Convert.ToString(nearTitledt.Rows[curr]["Title"]));
                    }

                    sbneartitle.Append("");
                    templatewai = templatewai.Replace("$ClassTitle$", sbneartitle.ToString());
                    sbneartitle.Remove(0, sbneartitle.ToString().Length);
                    //sbneartitle.Append("<div align='left'>");
                    //DataTable dtlike = zj123.Model.Article.GetLike(artid);
                    //for (int likei = 0; likei < dtlike.Rows.Count; likei++)
                    //{
                    //    sbneartitle.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", Convert.ToString(dtlike.Rows[likei]["HtmlPath"]), Convert.ToString(dtlike.Rows[likei]["Title"]));
                    //}
                    //sbneartitle.Append("</ol></div>");
                    //waitemp = waitemp.Replace("$LikeTitle$", sbneartitle.ToString());
                    //sbneartitle.Remove(0, sbneartitle.ToString().Length);
                    /////////////////////////////////////////////////////////////////////////////////////////////
                    #endregion
                    //替换链表信息
                    //$typejs$
                    templatewai = templatewai.Replace("$typejs$", classid);
                    //$numjs$
                    templatewai = templatewai.Replace("$numjs$", "10");
                    //$setjs$
                    templatewai = templatewai.Replace("$setjs$", "");
                    string tempzong = templatewai.Replace("$intemplate$", sbneilist.ToString());
                    string indexshow = (i + 1).ToString() == "1" ? ("") : ((i + 1).ToString());
                    if (!Directory.Exists(classpath))
                    {
                        Directory.CreateDirectory(classpath);
                    }

                    using (StreamWriter sw = new StreamWriter(classpath + @"\index" + indexshow + ".html", false, System.Text.Encoding.GetEncoding("gb2312")))
                    {
                        sw.Write(tempzong);
                        sw.Flush();
                        sw.Close();
                    };
                }
            }
            return succ;
 
        }
        public bool MakeIndex(string classid)
        {
            Match m = null;
            string temp="";
            ArrayList altemp = new ArrayList();
            bool succ = false;
            if (classid.Length < 1)
                return false;
            string templatewai = Convert.ToString(DbHelperOleDb.GetSingle("select TemplateContent from Template where TemplateID in(select TempIndexId from zone where classid=" + classid+")")??"");
            DataTable dtwaitemp = DbHelperOleDb.Query("select * from zone where classid=" + classid).Tables[0];
            string path = "";
            if(dtwaitemp.Rows.Count>0)
            {
            #region "编辑"
            templatewai = templatewai.Replace("$Title$",Convert.ToString(dtwaitemp.Rows[0]["ClassName"]));
            templatewai = templatewai.Replace("$Description$",Convert.ToString(dtwaitemp.Rows[0]["Description"]));
            templatewai = templatewai.Replace("$KeyWord$",Convert.ToString(dtwaitemp.Rows[0]["Keywords"]));
            path= Convert.ToString(dtwaitemp.Rows[0]["links"]);
            #endregion
           //Convert.ToString(DbHelperOleDb.GetSingle("select links from zone where classid=" + classid))??"";
            }

            classes.Common.al.Clear();
            classes.Common.GetChilds(classid);
            System.Collections.ArrayList al = classes.Common.al;
            System.Text.StringBuilder sb = new StringBuilder();
            for (int i = 0; i < al.Count; i++)
            {
                sb.Append(al[i]).Append(",");
            }
            MatchCollection mats = Regex.Matches(templatewai, @"<asp:title [^>]*>", RegexOptions.IgnoreCase);
          //  int i = 0;
            foreach (Match mat in mats)
            {
                //temp = mat.Value;
                m = Regex.Match(mat.Value.Trim(), "<asp:title\\s*classid=\"(?<classid>\\d*)\"\\s*size=\"(?<size>\\d*)\"\\s*count=\"(?<count>\\d*)\"\\s*date=\"(?<date>\\d*)\"\\s*dateformat=\"(?<dateformat>[^\\s]*)\"\\s*target=\"(?<target>[^\\s]*)\"\\s*img=\"(?<img>[^\\s]*)\"/>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                TemplateModel tm = new TemplateModel();
                if (m.Success)
                {
                  
                    tm.Classid = m.Groups["classid"].Value;
                    tm.Size = m.Groups["size"].Value;
                    tm.Count = m.Groups["count"].Value;
                    tm.Date = m.Groups["date"].Value;
                    tm.Dateformat = m.Groups["dateformat"].Value;
                    tm.Target = m.Groups["target"].Value;
                    tm.Img = m.Groups["img"].Value;
                    tm.Body = m.Value;
                    tm.Atitle ="<asp:title classid=\""+tm.Classid +"\">";
                 
                }
         
                   altemp.Add(tm);
        
            }
            #region "替换注释"

            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);
                string sql = "select * from zone where ClassID in(" + sb.ToString() + ") order by orderby";
                DataTable dt = DbHelperOleDb.Query(sql).Tables[0];
                DataTable dttemp = null;

                if (dt.Rows.Count > 0)
                {
                    ///循环所有的子类
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        //循环模板里面的符合项
                        for (int l = 0; l < altemp.Count; l++)
                        {
                            TemplateModel tempTm = (TemplateModel)altemp[l];
                            if ((i + 1).ToString() == tempTm.Classid)
                            {
                              
                               //列表生成工具
                                System.Text.StringBuilder tempsb = new StringBuilder();
                                ///图片新闻
                                if (tempTm.Img == "1")
                                {
                                    dttemp = DbHelperOleDb.Query("select top " + tempTm.Count + " case when len(Title)>" + tempTm.Size + " then substring(title,0," + tempTm.Size + ") else title end as title,htmlPath,updatetime,DefaultPicUrl,Intro,TitleIntact from article where deleted=1 and isCreate=1 and classid=" + Convert.ToString(dt.Rows[i]["ClassID"] ?? "0") + " order by DefaultPicUrl desc,Hits desc,updatetime desc").Tables[0];
                                    //无日期
                                    for (int j = 0; j < dttemp.Rows.Count; j++)
                                    {
                                       // tempsb.Append("<span class='fontpl20'>").Append("<a href='").Append(Convert.ToString(dttemp.Rows[j]["htmlPath"])).Append("'>·").Append(Convert.ToString(dttemp.Rows[j]["Title"])).Append("</a>").Append("</span><br>");
                                        ///<TR>
                                        ///<TD><IMG src="/template/newzs/img/7785047.jpg"  width=67 height=67 border=0 class=img_bd></TD>
                                        //<TD class=lh22><STRONG>劳动法偏袒员工</STRONG><BR>中国女首富称劳动法偏袒员工 旗下公司员工罢工……[详细]</TD>
                                        ////</TR>
                                        ///
                                        string linktemp = Convert.ToString(dttemp.Rows[j]["htmlPath"]) ?? "";
                                        string targettemp = tempTm.Target;
                                        string ttitletemp = Convert.ToString(dttemp.Rows[j]["TitleIntact"]) ?? "";
                                        ttitletemp = ttitletemp.Length > Convert.ToInt32(tempTm.Size) ? (ttitletemp.Substring(0, Convert.ToInt32(tempTm.Size))) : (ttitletemp);
                                        string introtemp = Convert.ToString(dttemp.Rows[j]["Intro"]) ?? "";
                                        introtemp = ttitletemp.Length > Convert.ToInt32(tempTm.Size) * 2 ? (ttitletemp.Substring(0, Convert.ToInt32(tempTm.Size) * 2)) : (ttitletemp);
                                        string imgtemp = Convert.ToString(dttemp.Rows[j]["DefaultPicUrl"]) ?? "";

                                        tempsb.Append("<TR>");
                                        tempsb.Append("<TD><a href='").Append(linktemp).Append("' target='").Append(targettemp).Append("'><IMG src=\"").Append(imgtemp).Append("\"  width=67 height=67 border=0 class=img_bd></a></TD>");
                                        tempsb.Append("<TD class=lh22><STRONG><a href='").Append(linktemp).Append("'  target='").Append(targettemp).Append("'>").Append(ttitletemp).Append("</a></STRONG><BR><a href='").Append(linktemp).Append("'  target='").Append(targettemp).Append("'>").Append(introtemp).Append("……[详细]</a></TD>");
                                        tempsb.Append("</TR>");
                                    }
                                }
                                else
                                {
                                    dttemp = DbHelperOleDb.Query("select top " + tempTm.Count + " case when len(Title)>" + tempTm.Size + " then substring(title,0," + tempTm.Size + ") else title end as title,htmlPath,updatetime from article where deleted=1 and isCreate=1 and classid=" + Convert.ToString(dt.Rows[i]["ClassID"] ?? "0") + " order by Hits desc,updatetime desc").Tables[0];
                                    if (tempTm.Date == "1")
                                    {
                                        //有日期
                                        for (int j = 0; j < dttemp.Rows.Count; j++)
                                        {
                                            tempsb.Append("<span class='fontpl20'>").Append("<a href='").Append(Convert.ToString(dttemp.Rows[j]["htmlPath"])).Append("' target=\"").Append(tempTm.Target).Append("(\">·").Append(Convert.ToString(dttemp.Rows[j]["Title"])).Append("</a>").Append("</span>").Append("&nbsp;&nbsp;&nbsp;").Append((Convert.ToDateTime(dttemp.Rows[j]["updatetime"]) == null ? (DateTime.Now) : (Convert.ToDateTime(dttemp.Rows[j]["updatetime"]))).ToString(tempTm.Dateformat)).Append("<span><br>");

                                        }
                                    }
                                    else
                                    {
                                        //无日期
                                        for (int j = 0; j < dttemp.Rows.Count; j++)
                                        {
                                            tempsb.Append("<span class='fontpl20'>").Append("<a href='").Append(Convert.ToString(dttemp.Rows[j]["htmlPath"])).Append("'>·").Append(Convert.ToString(dttemp.Rows[j]["Title"])).Append("</a>").Append("</span><br>");

                                        }
                                    }
                                }
                          
                                //end 列表生成
                                templatewai = Regex.Replace(templatewai, tempTm.Atitle, new System.Text.StringBuilder("<a href='/").Append(Convert.ToString(dt.Rows[i]["Links"] ?? " ")).Append("\\index.html").Append("'>").Append(Convert.ToString(dt.Rows[i]["ClassName"] ?? "0")).Append("</a>").ToString());
                                templatewai = Regex.Replace(templatewai, tempTm.Body, tempsb.ToString());
                           
                            }
                        }
                        #region MyRegion

                        //if (i < 3)
                        //{//$CLASSNAMEA1
                        //    templatewai = templatewai.Replace("$CLASSNAMEA" + (i + 1).ToString() + "$", "<a href='\\" + Convert.ToString(dt.Rows[i]["links"]).Trim() + "\\index.html'>" + Convert.ToString(dt.Rows[i]["ClassName"]) + "</a>");
                        //    // templatewai.Replace("$CLASSNAMEA1$", Convert.ToString(dt.Rows[i]["ClassName"]));
                        //    dttemp = DbHelperOleDb.Query("select top 12 Title,htmlPath from article where deleted=1 and isCreate=1 and classid=" + Convert.ToString(dt.Rows[i]["ClassID"] ?? "0") + " order by Hits desc,updatetime desc").Tables[0];
                        //    System.Text.StringBuilder tempsb = new StringBuilder();
                        //    for (int j = 0; j < dttemp.Rows.Count; j++)
                        //    {
                        //        tempsb.Append("<span class='fontpl20'>").Append("<a href='").Append(Convert.ToString(dttemp.Rows[j]["htmlPath"])).Append("'>·").Append(Convert.ToString(dttemp.Rows[j]["Title"])).Append("</a>").Append("</span><br>");

                        //    }
                        //    templatewai = templatewai.Replace("$CLASSNAMEA" + (i + 1).ToString() + "CONTENT$", tempsb.ToString());

                        //}
                        //else if (i >= 3 && i <= 5)
                        //{
                        //    templatewai = templatewai.Replace("$CLASSNAMEB" + (i - 2).ToString() + "$", "<a href='\\" + Convert.ToString(dt.Rows[i]["links"]).Trim() + "\\index.html'>" + Convert.ToString(dt.Rows[i]["ClassName"]) + "</a>");
                        //    dttemp = DbHelperOleDb.Query("select top 12 Title,htmlPath from article where deleted=1 and isCreate=1 and classid=" + Convert.ToString(dt.Rows[i]["ClassID"] ?? "0") + " order by Hits desc,updatetime desc").Tables[0];
                        //    System.Text.StringBuilder tempsb = new StringBuilder();
                        //    for (int j = 0; j < dttemp.Rows.Count; j++)
                        //    {
                        //        tempsb.Append("<span class='fontpl20'>").Append("<a href='").Append(Convert.ToString(dttemp.Rows[j]["htmlPath"])).Append("'>·").Append(Convert.ToString(dttemp.Rows[j]["Title"])).Append("</a>").Append("</span><br>");

                        //    }
                        //    templatewai = templatewai.Replace("$CLASSNAMEB" + (i - 2).ToString() + "CONTENT$", tempsb.ToString());
                        //}
                        //else if (i >= 5 && i <= 6)
                        //{
                        //    templatewai = templatewai.Replace("$CLASSNAMEC1$", "<a href='\\" + Convert.ToString(dt.Rows[i]["links"]).Trim() + "\\index.html'>" + Convert.ToString(dt.Rows[i]["ClassName"]) + "</a>");
                        //    dttemp = DbHelperOleDb.Query("select top 12 Title,htmlPath from article where deleted=1 and isCreate=1 and classid=" + Convert.ToString(dt.Rows[i]["ClassID"] ?? "0") + " order by Hits desc,updatetime desc").Tables[0];
                        //    System.Text.StringBuilder tempsb = new StringBuilder();
                        //    for (int j = 0; j < dttemp.Rows.Count; j++)
                        //    {
                        //        tempsb.Append("<span class='fontpl20'>").Append("<a href='").Append(Convert.ToString(dttemp.Rows[j]["htmlPath"])).Append("'>·").Append(Convert.ToString(dttemp.Rows[j]["Title"])).Append("</a>").Append("</span><br>");

                        //    }
                        //    templatewai = templatewai.Replace("$CLASSNAMEC1CONTENT$", tempsb.ToString());
                        //}
                        //else if (i > 6 && i <= 12)
                        //{
                        //    templatewai = templatewai.Replace("$CLASSNAMED" + (i - 6).ToString() + "$", "<a href='\\" + Convert.ToString(dt.Rows[i]["links"]).Trim() + "\\index.html'>" + Convert.ToString(dt.Rows[i]["ClassName"]) + "</a>");
                        //    dttemp = DbHelperOleDb.Query("select top 12 Title,htmlPath from article where deleted=1 and isCreate=1 and classid=" + Convert.ToString(dt.Rows[i]["ClassID"] ?? "0") + " order by Hits desc,updatetime desc").Tables[0];
                        //    System.Text.StringBuilder tempsb = new StringBuilder();
                        //    for (int j = 0; j < dttemp.Rows.Count; j++)
                        //    {
                        //        tempsb.Append("<span class='fontpl20'>").Append("<a href='").Append(Convert.ToString(dttemp.Rows[j]["htmlPath"])).Append("'>·").Append(Convert.ToString(dttemp.Rows[j]["Title"])).Append("</a>").Append("</span><br>");

                        //    }
                        //    templatewai = templatewai.Replace("$CLASSNAMED" + (i - 6).ToString() + "CONTENT$", tempsb.ToString());
                        //}
                        //else
                        //{

                        //}
                        #endregion
                    }
                    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    string filepath = HttpContext.Current.Request.PhysicalApplicationPath.ToString() + path;
                    if (!Directory.Exists(filepath))
                        Directory.CreateDirectory(filepath);
                    filepath += "\\Default.html";

                    using (StreamWriter sw = new StreamWriter(filepath, false, System.Text.Encoding.GetEncoding("GB2312")))
                    {
                        sw.Write(templatewai);
                        sw.Flush();
                        sw.Close();
                    
                    };
                    succ = true;
                }
            }
            else
            {

            }
           
            #endregion
            return succ;
        }
        #region ""
        public bool MakeIndexLink(string classid)
        {
            Match m = null;
            string temp = null;
            ArrayList altemp = new ArrayList();
            bool succ = false;
            if (classid.Length < 1)
                return false;
            string templatewai = Convert.ToString(DbHelperOleDb.GetSingle("select TemplateContent from Template where TemplateID in(select TempIndexId from zone where classid=" + classid + ")") ?? "");
            DataTable dtwaitemp = DbHelperOleDb.Query("select * from zone where classid=" + classid).Tables[0];
            string path = "";
            if (dtwaitemp.Rows.Count > 0)
            {
                #region "编辑"
                templatewai = templatewai.Replace("$Title$", Convert.ToString(dtwaitemp.Rows[0]["ClassName"]));
                templatewai = templatewai.Replace("$Description$", Convert.ToString(dtwaitemp.Rows[0]["Description"]));
                templatewai = templatewai.Replace("$KeyWord$", Convert.ToString(dtwaitemp.Rows[0]["Keywords"]));
                path = Convert.ToString(dtwaitemp.Rows[0]["links"]);
                #endregion
               
            }

      
            MatchCollection mats = Regex.Matches(templatewai, @"<asp:title [^>]*>", RegexOptions.IgnoreCase);
            DataTable dttemp = null;
            System.Text.StringBuilder tempsb = new StringBuilder();
            foreach (Match mat in mats)
            {
                 temp = mat.Value;
                m = Regex.Match(temp, "<asp:title classid=\"(?<classid>\\d*)\" size=\"(?<size>\\d*)\" count=\"(?<count>\\d*)\" date=\"(?<date>\\d*)\" dateformat=\"(?<dateformat>\\w*)\"/>");
                TemplateModel tm = new TemplateModel();
                tm.Classid = m.Groups["classid"].Value;
                tm.Size = m.Groups["size"].Value;
                tm.Count = m.Groups["count"].Value;
                tm.Date = m.Groups["date"].Value;
                tm.Dateformat = m.Groups["dateformat"].Value;
                tm.Body = m.Value;
                altemp.Add(tm);

               // dttemp = DbHelperOleDb.Query("select ").Tables[0];
                dttemp = DbHelperOleDb.Query("select top " + tm.Count + " case when len(Title)>" + tm.Size + " then substring(title,0," + tm.Size + ") else title end as title,htmlPath from article where deleted=1 and isCreate=1 and classid=" + Convert.ToString(tm.Classid ?? "0") + " order by Hits desc,updatetime desc").Tables[0];
                //列表生成工具
                tempsb.Remove(0,tempsb.Length);
                if (tm.Date == "1")
                {
                    //有日期
                    for (int j = 0; j < dttemp.Rows.Count; j++)
                    {
                        tempsb.Append("<span class='fontpl20'>").Append("<a href='").Append(Convert.ToString(dttemp.Rows[j]["htmlPath"])).Append("'>·").Append(Convert.ToString(dttemp.Rows[j]["Title"])).Append("</a>").Append("</span>").Append((Convert.ToDateTime(dttemp.Rows[j]["Title"]) == null ? (DateTime.Now) : (Convert.ToDateTime(dttemp.Rows[j]["Title"]))).ToString(tm.Dateformat)).Append("<span><br>");

                    }
                }
                else
                {
                    //无日期
                    for (int j = 0; j < dttemp.Rows.Count; j++)
                    {
                        tempsb.Append("<span class='fontpl20'>").Append("<a href='").Append(Convert.ToString(dttemp.Rows[j]["htmlPath"])).Append("'>·").Append(Convert.ToString(dttemp.Rows[j]["Title"])).Append("</a>").Append("</span><br>");

                    }
                }
                //end 列表生成
                templatewai = Regex.Replace(templatewai, tm.Body, tempsb.ToString());
           
            }
         
            string filepath = HttpContext.Current.Request.PhysicalApplicationPath.ToString() + path;
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);
            filepath += "\\Default.html";

            using (StreamWriter sw = new StreamWriter(filepath, false, System.Text.Encoding.GetEncoding("GB2312")))
            {
                sw.Write(templatewai);
                sw.Flush();
                sw.Close();
            };
            succ = true;

            return succ;

        }
        #endregion
    }
    public class TemplateModel
    {

        private Regex reg = new Regex("^\\d+$");
        private string _classid;
        private string _size;
        private string _count;
        private string _date;
        private string _dateformat;
        private string _body;
        private string _atitle;
        private string _target;
        private string _img;
        public string Classid
        {
            set
            {
                if (reg.IsMatch(value))
                {
                    this._classid = value;
                }
                else
                {
                    this._classid = "0";
                }
            }
            get { return this._classid; }
        }
        public string Size
        {
            set
            {
                if (reg.IsMatch(value))
                {
                    this._size = value;
                }
                else
                {
                    this._size = "10";
                }
            }
            get { return this._size; }
        }
        public string Count
        {
            set
            {
                if (reg.IsMatch(value))
                {
                    this._count = value;
                }
                else
                {
                    this._count = "10";
                }
            }
            get { return this._count; }
        }
        public string Date
        {
            set
            {
                if (reg.IsMatch(value))
                {
                    this._date = value;
                }
                else
                {
                    this._date = "0";
                }
            }
            get { return this._date; }
        }
        public string Dateformat
        {
            set
            {

                this._dateformat = value;

            }
            get { return this._dateformat; }
        }
        public string Body
        {
            set
            {

                this._body = value;

            }
            get { return this._body; }
        }
      public string Atitle
        {
            set
            {

                this._atitle = value;

            }
            get { return this._atitle; }
        }
        public string Target
        {
            set
            {
                if (value.Length < 1)
                {
                    this._target = "_self";
                }
                else
                {
                    this._target = value;
                }
               

            }
            get { return this._target; }
        }
        public string Img
        {
            set
            {
                if (value.Length < 1)
                {
                    this._img = "0";
                }
                else
                {
                    this._img = value;
                }


            }
            get { return this._img; }
        }

    }
 
}

posted on 2009-01-08 18:54 sanmao 阅读(415) 评论(1)  编辑  收藏

FeedBack:
# re: C#生成静态页类代码|支持列表生成代码
2015-03-20 21:38 | myhero
正在学习,能否把classes.Common.也贴一下,非常感谢。L.ni@163.com  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 

常用链接

留言簿(5)

随笔分类

随笔档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜