using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Text;

namespace BookDemo.QA
{
    public static class Common
    {
        /// <summary>
        /// 获取Session中的UserName
        /// </summary>
        /// <returns></returns>
        public static string GetUserName()
        {
            if (HttpContext.Current.Session["UserName"] != null)
                return HttpContext.Current.Session["UserName"].ToString();
            else
                return "";
        }

        /// <summary>
        /// 验证用户是否登陆，如果未登录，则转到登陆页面
        /// </summary>
        /// <returns></returns>
        public static void CheckLogin()
        {
            //如果用户未登陆，则跳转到登陆页面，并提供参数，在登陆后条转会当前页面
            if (HttpContext.Current.Session["UserName"] == null || HttpContext.Current.Session["UserName"].ToString().Length == 0)
            {
                //获得Url编码后的当前Url地址，用于在Login页面登陆后返回本页面
                string returnUrl = System.Web.HttpContext.Current.Server.UrlEncode(System.Web.HttpContext.Current.Request.Url.PathAndQuery);
                System.Web.HttpContext.Current.Response.Redirect("~/Login.aspx?ReturnUrl=" + returnUrl, true);
            }
        }

        /// <summary>
        /// 生成树形结构的目录
        /// </summary>
        /// <param name="ddlCatalogs">目录下拉菜单</param>
        /// <param name="ctx">BookDemoEntities 实体</param>
        /// <param name="showHead">是否显示“根目录”</param>
        public static void BindToDdlCatalogs(DropDownList ddlCatalogs, BookDemoEntities ctx, bool showHead)
        {
            ddlCatalogs.Items.Clear();//清空ddlCatalogs所有选项

            //如果显示“根目录”，则添加一个选项
            if (showHead)
                ddlCatalogs.Items.Add(new ListItem("根目录", "0"));

            //顶层目录  因为这里只有2层，所以我们不需要递归，直接写就可以
            List<QACatalog> topCatalogs = (from c in ctx.QACatalog  //从QACatalog中查找
                                           where c.Layer == 0       //层次为0
                                           orderby c.DisplayOrder   //排序
                                           select c).ToList();
            //遍历顶层目录topCatalogs
            foreach (var topCatalog in topCatalogs)
            {
                //添加一级目录选项
                ddlCatalogs.Items.Add(new ListItem("　┠" + topCatalog.Name, topCatalog.Id.ToString()));
                //查询下属二级目录
                List<QACatalog> secCatalogs = (from c in ctx.QACatalog where c.Layer == 1 && c.ParentID == topCatalog.Id orderby c.DisplayOrder select c).ToList();
                //遍历添加下属二级目录
                foreach (var secCatalog in secCatalogs)
                {
                    //添加二级目录选项
                    ddlCatalogs.Items.Add(new ListItem("　　┠" + secCatalog.Name, secCatalog.Id.ToString()));
                }
            }
        }

        /// <summary>
        /// 生成树形结构的目录，使用缓存数据
        /// </summary>
        /// <param name="ddlCatalogs"></param>
        /// <param name="showHead"></param>
        public static void BindToDdlCatalogs(DropDownList ddlCatalogs, bool showHead)
        {
            CatalogCache catalogCache = new CatalogCache();
            List<QACatalog> catalogs = catalogCache.Data;

            ddlCatalogs.Items.Clear();//清空ddlCatalogs所有选项

            //如果显示“根目录”，则添加一个选项
            if (showHead)
                ddlCatalogs.Items.Add(new ListItem("根目录", "0"));

            //顶层目录  因为这里只有2层，所以我们不需要递归，直接写就可以
            List<QACatalog> topCatalogs = (from c in catalogs  //从QACatalog中查找
                                           where c.Layer == 0       //层次为0
                                           orderby c.DisplayOrder   //排序
                                           select c).ToList();
            //遍历顶层目录topCatalogs
            foreach (var topCatalog in topCatalogs)
            {
                //添加一级目录选项
                ddlCatalogs.Items.Add(new ListItem("　┠" + topCatalog.Name, topCatalog.Id.ToString()));
                //查询下属二级目录
                List<QACatalog> secCatalogs = (from c in catalogs where c.Layer == 1 && c.ParentID == topCatalog.Id orderby c.DisplayOrder select c).ToList();
                //遍历添加下属二级目录
                foreach (var secCatalog in secCatalogs)
                {
                    //添加二级目录选项
                    ddlCatalogs.Items.Add(new ListItem("　　┠" + secCatalog.Name, secCatalog.Id.ToString()));
                }
            }
        }

        /// <summary>
        /// 高亮关键字
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        public static string HighlightKeyword(this string str, string keyword)
        {
            string replaceFormat = "<strong><font color=\"red\">{0}</font></strong>";//替换格式
            //正则表达式，前面字符不重复
            //注意，这里的(?<!{0})不能使用[^{0}]，因为[^{0}]是占位的，而(?<!{0})不占位
            string expr = @"(?<!{0})(?<kw>{0})";//关键字的组名为kw
            string pattern = string.Format(expr, keyword);//完整正则表达式
            string evaluator = string.Format(replaceFormat, "${kw}");//替换字符串
            string highlighted = Regex.Replace(str, pattern, evaluator, RegexOptions.IgnoreCase);
            return highlighted;
        }


/// <summary>
/// 高亮关键字
/// </summary>
/// <param name="str">原始字符串</param>
/// <param name="keyword">关键字</param>
/// <returns></returns>
public static string HighlightKeywords(this string str, string keywords)
{
    if (string.IsNullOrEmpty(keywords))
    {
        return str;//如果关键字为空，则返回原始字符串
    }
    string replaceFormat = "<strong><font color=\"red\">{0}</font></strong>";//替换格式
    //获取关键字数组，分割字符为“+”
    string[] keywordsArr = keywords.Split(new string[] { " ", "+", "," }, StringSplitOptions.RemoveEmptyEntries);
    string keyword = string.Join("|", keywordsArr);//组成单关键字字符串，以"|"符号分割，用于正则表达式

    //正则表达式，前面字符不重复
    //注意，这里的(?<!{0})不能使用[^{0}]，因为[^{0}]是占位的，而(?<!{0})不占位
    string expr = @"(?<!{0})(?<kw>{0})";//关键字的组名为kw
    string pattern = string.Format(expr, keyword.ToString());//完整正则表达式
    string evaluator = string.Format(replaceFormat, "${kw}");//替换字符串
    string highlighted = Regex.Replace(str, pattern, evaluator, RegexOptions.IgnoreCase);//以高亮关键字代码替换原始关键字
    return highlighted;//返回结果
}
    }
}
