/**********************************************************************************
 * ClassName:       ListTags
 * Description:     Loop标签和分页标签处理类处理类
 * MemberVariable:
 * Functions:       
 * Modify information:     
 * 2009-11-12     New          Ayong     Create Class
 * 
 * ********************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Data;
using System.Configuration;
using Fm.Bussiness;
using Fm.DataAccess;
using System.Web;
using System.Collections;

namespace Fm.Tags
{
    public class ListTags
    {
        //获取参数属性列表  
        GlobalTags gb = new GlobalTags();
        /// <summary>
        /// 分页标签解析
        /// </summary>
        /// <param name="content">解析内容</param>
        /// <param name="cid">栏目ID</param>
        /// <param name="pid">page页</param>
        /// <returns></returns>
        public string Analysis_Page(string content,int pid,int cid,int htmcount)
        {
            //实例化分页数据操作类
            Formpage page = new Formpage();
            //获取查询条件
            string where = "cl_id=" + cid;
            //查询该栏目的信息
            public_select ps=new public_select();
            DataView column = ps.Getps("Fm_column","*",where);
            //正则获取标签信息
            Regex r = new Regex(@"(\{fm:page\s+(?<attributes>[^\]]*?)\}(?<text>[\s\S]*?)\{/fm:page\})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            //标签解析开始---

            string Attributes = "";//存储属性
            string Text = "";//存储标签Text
            string AllText = "";
            foreach (Match m in r.Matches(content))
            {
                //获取正则相关属性
                Attributes = m.Groups["attributes"].ToString();
                Text = m.Groups["text"].ToString();
                AllText = m.Groups[0].Value.ToString();

               
                string count = null;
                count = gb.TagVal(Attributes,"count");
                if (count == null)
                {
                    count = "10";
                }
                
                /*分页Start*************************/
                //查询记录总数
                DataView total = page.PageRow("Fm_model_article_view", "docid", int.Parse(count), 1, "colid=" + cid + "") as DataView;

                int rownum = int.Parse(total[0]["total"].ToString());
                int pagesize = int.Parse(count);
                int rowcount = 0;
                //判断总页码
                if (rownum % pagesize == 0)
                {
                    rowcount = rownum / pagesize;
                }
                else
                {
                    rowcount = rownum / pagesize + 1;
                }
                if (rowcount == 0)
                {
                    rowcount = 1;
                }
                //判断是否按照静态页生成设置来显示最大页数
                if (htmcount != 0 && htmcount <= rowcount)
                {
                    rowcount = htmcount;
                }
                //标签替换
                string txt = Text;
                txt = txt.Replace("{field.total}",rownum.ToString());
                txt = txt.Replace("{field.current}", pid.ToString());//当前页
                txt = txt.Replace("{field.amount}", rowcount.ToString());//总页数
                //获取URL 地址
                StringBuilder url = new StringBuilder();
                if (column[0]["cl_options"].ToString() == "2")
                {
                    url.Append("/list.aspx?cid=");
                    url.Append(cid);
                    url.Append("&page={page}");
                }
                else
                {
                    url.Append("/");
                    url.Append(column[0]["cl_path"].ToString());
                    url.Append(column[0]["cl_list"].ToString().Replace("{cid}", cid.ToString()));
                   
                }
                string newurl = url.ToString();
                //根据栏目选项属性替换首页链接
                if (column[0]["cl_options"].ToString() == "0")
                {
                    txt = txt.Replace("{field.index}", "/" + column[0]["cl_path"].ToString() + column[0]["cl_default"].ToString());
                }
                else if (column[0]["cl_options"].ToString() == "1")
                {
                    txt = txt.Replace("{field.index}", newurl.Replace("{page}", "1"));
                }
                else
                {
                    txt = txt.Replace("{field.index}", newurl.Replace("{page}", "1"));
                }
           
                //最后一页
                txt = txt.Replace("{field.last}", newurl.Replace("{page}", rowcount.ToString()));
              
                int front = 1;
                int next = 1;
                if (pid > 1)
                {
                    front = pid - 1;
                   
                }
                if (pid == rowcount)
                {
                    next = pid;
                }
                else
                {
                    next = pid + 1;
                }
                txt = txt.Replace("{field.front}",newurl.Replace("{page}",front.ToString()));//上一页
                txt = txt.Replace("{field.next}",newurl.Replace("{page}",next.ToString()));//下一页
                //处理数字页标签
                //正则获取标签信息
                //实例化正则对象
                Regex reg = new Regex(@"(\{fm:number\}(?<text>[\s\S]*?)\{/fm:number\})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                //存储新的内容
                StringBuilder str = new StringBuilder();
                str.Append(" ");
                string NewText = "";
                string NewAllText = "";
                foreach (Match ma in reg.Matches(txt))
                {
                    StringBuilder src = new StringBuilder();
                    //存储新的内容
                     NewText = ma.Groups["text"].ToString();
                     NewAllText = ma.Groups[0].Value.ToString();
                    //根据栏目选项属性替换首页链接
                    if (column[0]["cl_options"].ToString() == "0")
                    {
                        src.Append("/");
                        src.Append(column[0]["cl_path"].ToString());
                        src.Append(column[0]["cl_default"].ToString());
                        
                    }
                    else if (column[0]["cl_options"].ToString() == "1")
                    {
                        src.Append(url); 
                    }
                    else
                    {
                        src.Append(url);  
                    }
                    str.Append(NewText.Replace("{field.url}", src.ToString().Replace("{page}","1")));  
                    str = str.Replace("{field.count}", "1");
                    
                    //循环生成分页连接
                    for (int i = 2; i < rowcount; i++)
                    {
                        string s = NewText;
                        //s.Append(NewText);
                        if (pid > 9)
                        {
                            if (i < (pid - 4) && i > 1)
                            {
                                continue;
                            }
                          
                        }
                        if (i > (pid+4) && i < rowcount)
                        {
                            break;
                        }
                        //替换标签
                        s = s.Replace("{field.url}", newurl.Replace("{page}", i.ToString()));
                        s = s.Replace("{field.count}",i.ToString());
                        str.Append(s);
                    }
                    str.Append(NewText.Replace("{field.url}", newurl.Replace("{page}", rowcount.ToString()).ToString()).Replace("{field.count}",rowcount.ToString()));
                }
                if (NewAllText != "")
                {
                    txt = txt.Replace(NewAllText, str.ToString());
                }
                /*分页End***************************/

                content = content.Replace(AllText,txt);

                content = Analysis_Loop(content, (page.PageView_Bywhere("Fm_model_article_view", "docid", int.Parse(count), pid, "colid=" + cid + "") as DataView).Table);
            }
            return content;
        }
        public string Analysis_Loop(string content,DataTable dt)
        {
            //标签解析开始---
            string Text = "";//存储标签Text
            string AllText = "";
            //实例化正则对象
            Regex r = new Regex(@"(\{fm:loop\}(?<text>[\s\S]*?)\{/fm:loop\})", RegexOptions.Compiled | RegexOptions.IgnoreCase);

            foreach (Match m in r.Matches(content))
            {
                //存储新的内容
                StringBuilder str = new StringBuilder();
                Text = m.Groups["text"].ToString();
                AllText = m.Groups[0].Value.ToString();

                int index = 1;
                foreach (DataRow row in dt.Rows)
                {
                    StringBuilder txt = new StringBuilder();
                    txt.Append(Text);
                    //标签解析
                    //索引标签
                    txt = txt.Replace("{field.index}", index.ToString());
                    index++;

                    txt = txt.Replace("{field.docid}", row["docid"].ToString());
                    txt = txt.Replace("{field.cid}", row["colid"].ToString());
                    //txt = txt.Replace("{field.cname}", row["cl_name"].ToString());
                    //txt = txt.Replace("{$title}",dv[num]["title"].ToString());
                    txt = txt.Replace("{field.click}", row["click"].ToString());
                    if (row["thumbnail"].ToString().Equals(""))
                    {
                        txt = txt.Replace("{field.thumbnail}", "/images/thumbnail.jpg");
                    }
                    else
                    {
                        txt = txt.Replace("{field.thumbnail}", row["thumbnail"].ToString());
                    }
                    txt = txt.Replace("{field.top}", row["topclick"].ToString());
                    txt = txt.Replace("{field.tread}", row["tread"].ToString());

                    //标题处理

                    Regex Rtitle = new Regex(@"(\{field.title\s+(?<attributes>[^\]]*?)\})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    string TitleAttribute = "";//存储属性
                    string TitleAll = "";
                    string TitleCount = null;
                    string title = row["title"].ToString();
                    //如果没有设置该参数则显示全部标题
                    if (Rtitle.Matches(txt.ToString()).Count <= 0)
                    {
                        txt = txt.Replace("{field.title}", title);
                    }
                    foreach (Match mat in Rtitle.Matches(txt.ToString()))
                    {
                        TitleAttribute = mat.Groups["attributes"].ToString();
                        TitleAll = mat.Groups[0].Value.ToString();

                        TitleCount = gb.TagVal(TitleAttribute, "count");

                        if (TitleCount != null)
                        {
                            int TCount = int.Parse(TitleCount);
                            title = title.Length > TCount ? title.Substring(0, TCount) : title;
                        }
                        txt.Replace(TitleAll, title);

                    }
                    txt = txt.Replace("field.color", row["color"].ToString());

                    txt = txt.Replace("{field.keywords}",row["keyword"].ToString());
                    txt = txt.Replace("{field.intro}",row["intro"].ToString());
                    txt = txt.Replace("{field.username}",row["username"].ToString());
                    txt = txt.Replace("{field.author}",row["author"].ToString());
                    txt = txt.Replace("{field.source}",row["source"].ToString());
                    //处理连接地址
                    if (row["html"].ToString().ToLower() == "true")
                    {
                        txt = txt.Replace("{field.url}", row["path"].ToString());
                    }
                    else
                    {
                        txt = txt.Replace("{field.url}", "/article.aspx?docid=" + row["docid"].ToString());
                    }
                    //处理时间
                    Regex r1 = new Regex(@"(\{field.writertime\s+(?<attributes>[^\]]*?)\})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    string att = "";//存储属性
                    string all = "";
                    string format = null;
                    foreach (Match m1 in r1.Matches(txt.ToString()))
                    {
                        //获取属性
                        att = m1.Groups["attributes"].ToString();
                        all = m1.Groups[0].Value.ToString();

                        format =gb.TagVal(att, "format");

                        DateTime time = DateTime.Parse(row["writertime"].ToString());

                        if (format != null)
                        {

                            format = format.Replace("yyyy", time.Year.ToString());

                            format = format.Replace("mm", time.Month.ToString());

                            format = format.Replace("dd", time.Day.ToString());
                        }
                        else
                        {
                            format = time.Date.ToString();
                        }
                        //替换时间标签
                        txt = txt.Replace(all, format);
                    }
                    str.Append(txt);
                }
                //替换整个标签的数据
                content = content.Replace(AllText, str.ToString());

            }
            return content;
        }
    }
}
