﻿using System;
using System.IO;
using System.Configuration;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using PlugNT.Custom;
using PlugNT.Cms.Core;
using PlugNT.Common.Templet;

namespace PlugNT.Cms.Page
{
    public abstract class BasePager : SitePager
    {

        protected string tmpFilePath = null;                                                    //模板路径
        protected PageType pageType = PageType.Index;                                           //页面类型
        protected int currPageCount = 0;                                                        //当前页
        protected string currUrl = "";                                                          //当前url
        protected string pageArgs = "";                                                         //查询参数
        protected string andWhere = "";                                                         //查询条件
        protected bool enableCache = true;                                                      //启用缓存
        private Dictionary<string, string> list = new Dictionary<string, string>();


        #region 输出内容到客户端
        protected void Write()
        {
            //执行显示数据
            switch (pageType)
            {
                case PageType.Index:
                    this.Response.Write(GetIndexPageString());
                    break;
                case PageType.Show:
                    this.Response.Write(GetShowPageString());
                    break;
                case PageType.List:
                    this.Response.Write(GetListPageString());
                    break;
                default:
                    break;
            }
            this.Response.Flush();
        }
        #endregion


        #region 根据模板得到内容
        private string GetIndexPageString()
        {
            if (tmpFilePath == null || tmpFilePath == "")
            {
                return "模板路径参数未指定！";
            }
            HtmlBuilder html = new HtmlBuilder();
            html.TablePostFix = PlugNT.Custom.WebConfig.TablePostfix;
            html.HtmlTempletPath = tmpFilePath;
            if (enableCache)
            {
                object templetstring = PlugNT.Common.DataCache.GetCache(currUrl);
                if (templetstring == null)
                {
                    templetstring = html.GetCacheSimpleTempletString();
                    PlugNT.Common.DataCache.SetCache(currUrl, templetstring);
                }
                string reTempletstring = ReplaceTags(templetstring.ToString());
                return html.GetSimpleTempletString(reTempletstring);
            }
            else
            {
                string reTempletstring = ReplaceTags(html.GetCacheSimpleTempletString());
                return html.GetSimpleTempletString(reTempletstring);
            }
        }

        private string GetShowPageString()
        {
            if (tmpFilePath == null || tmpFilePath == "")
            {
                return "模板路径参数未指定！";
            }
            if (Request.QueryString["id"] == null)
            {
                return "ID参数未指定！";
            }
            string sid = Request.QueryString["id"].Trim();
            if (!PlugNT.Common.Utils.IsNumeric(sid))
            {
                return "ID参数不是数字！";
            }
            int id = int.Parse(sid);
            HtmlBuilder html = new HtmlBuilder();
            html.TablePostFix = PlugNT.Custom.WebConfig.TablePostfix;
            html.HtmlTempletPath = tmpFilePath;
            html.IdValue = id;
            if (enableCache)
            {
                object templetstring = PlugNT.Common.DataCache.GetCache(currUrl);
                if (templetstring == null)
                {
                    templetstring = html.GetCacheSimpleTempletString();
                    PlugNT.Common.DataCache.SetCache(currUrl, templetstring);
                }
                string reTempletstring = ReplaceTags(templetstring.ToString());
                return html.GetSimpleTempletString(reTempletstring);
            }
            else
            {
                string reTempletstring = ReplaceTags(html.GetCacheSimpleTempletString());
                return html.GetSimpleTempletString(reTempletstring);
            }
        }

        private string GetListPageString()
        {
            if (tmpFilePath == null || tmpFilePath == "")
            {
                return "模板路径参数未指定！";
            }
            HtmlBuilder html = new HtmlBuilder();
            html.TablePostFix = PlugNT.Custom.WebConfig.TablePostfix;
            html.HtmlTempletPath = tmpFilePath;
            int currPage = currPageCount;
            try
            {
                if (enableCache)
                {
                    object templetstring = PlugNT.Common.DataCache.GetCache(currUrl);
                    if (templetstring == null)
                    {
                        templetstring = html.GetCacheListTempletString();
                        PlugNT.Common.DataCache.SetCache(currUrl, templetstring);
                    }
                    string reTempletstring = ReplaceTags(templetstring.ToString());
                    return html.GetListTempletString(reTempletstring, currPage, currUrl, pageArgs, andWhere);
                }
                else
                {
                    string reTempletstring = ReplaceTags(html.GetCacheListTempletString());
                    return html.GetListTempletString(reTempletstring, currPage, currUrl, pageArgs, andWhere);
                }

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        #endregion


        #region 动态模板内容
        /// <summary>
        /// 不区分大小写
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="value">值</param>
        protected void SetNameValue(string key, string value)
        {
            key = key.ToLower();
            if (list.ContainsKey(key))
            {
                list[key] = value;
            }
            else
            {
                list.Add(key, value);
            }
        }

        private string ReplaceTags(string template)
        {
            if (template.Contains(HtmlLabel.startFlg + HtmlLabel.dynamicFlg))
            {
                List<RegTag> tags = RegTemplet.GetRegTagsDistinct(template, HtmlLabel.dynamicFlg);
                foreach (RegTag tag in tags)
                {
                    string name = RegTemplet.GetAttribute(tag.Attributes, HtmlLabel.nameProperty);
                    if (name != "")
                    {
                        string ltvalue = null;
                        if (list.TryGetValue(name, out ltvalue))
                        {
                            template = template.Replace(tag.OuterText, ltvalue);
                        }
                    }
                    template = template.Replace(tag.OuterText, "");
                }
            }
            return template;
        }
        #endregion


        #region 重载方法

        /// <summary>
        /// 覆盖系统默认的错误页
        /// </summary>
        protected override void OnError(EventArgs e)
        {
            HttpContext ctx = HttpContext.Current;
            Exception exception = ctx.Server.GetLastError();
            string errorInfo =
                "\r\n<br /><b>发生错误的 URL:</b> <font color=red>" + ctx.Request.Url.ToString() +
                "</font>" +
                "\r\n<br /><b>错误源: </b> <font color=red>" + exception.Source +
                "</font>" +
                "\r\n<br /><b>错误信息: </b> <font color=red>" + exception.Message +
                "</font>" +
                "\r\n<br /><b>Stack trace: </b> <br /><font color=red>" + exception.StackTrace +
                "</font>";

            ctx.Response.Write(errorInfo);
            ctx.Response.Write("<br><br><br><center>系统异常！请和管理员联系！</center>");
            ctx.Server.ClearError();

            base.OnError(e);
        }
        #endregion

    }
}

