using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Text;
using System.Collections;
using System.Globalization;
using System.Web;
namespace nspLable.Function
{
    /// <summary>
    /// 标签调用的方法
    /// </summary>
    public class Function:Base.BasePage
    {


        /// <summary>
        ///  调用查询资讯列表
        /// </summary>
        /// <param name="strSelect">查询的内容</param>
        /// <param name="strWhere">查询条件</param>
        /// <param name="strTableName">查询的表、视图、存储过程</param>
        /// <returns></returns>
        public static DataTable GetDataTable(string strSelect, string strWhere, string strTableName, string strOrder)
        {
            SqlParameter[] param = new SqlParameter[] 
            {  
                new SqlParameter("@StrSelect",strSelect),
                new SqlParameter("@strWhere",strWhere),
                new SqlParameter("@strTableName", strTableName), 
                new SqlParameter("@strOrder", strOrder)
            };
            return SqlOperate.SqlHelper.ExecuteTable(CommandType.StoredProcedure, "SP_SelectByWhere", param);
        }


        /// <summary>
        /// 取得单个值
        /// </summary>
        /// <param name="strSelect">表字段</param>
        /// <param name="strWhere">条件</param>
        /// <param name="strTableName">数据表名</param>
        /// <returns>返回该字段的值</returns>
        public static string GetOnlyDate(string strSelect, string strWhere, string strTableName)
        {
            string Restr = "";
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.Append("select Top 1");
            strBuilder.Append(" ");
            strBuilder.Append(strSelect);
            strBuilder.Append(" from ");
            strBuilder.Append(strTableName);
            strBuilder.Append("  ");
            strBuilder.Append(strWhere);
            Restr = SqlOperate.SqlHelper.ExecuteScalar(strBuilder.ToString()).ToString();
            return Restr;
        }


        /// <summary>
        /// 检测模板是否存在
        /// </summary>
        /// <param name="FileUrl">模板路径</param>
        /// <returns></returns>
        private static bool CheckFile(string FileUrl)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + FileUrl.Replace("~/", "/").Replace("../../", "/");
            if (System.IO.File.Exists(path))
                return true;
            else
                return false;
        }

        /// <summary>
        /// 处理图片路径
        /// </summary>
        /// <param name="strImageURL"></param>
        /// <returns>返回绝对路径</returns>
        public static string ProcessImageUrl(string strImageURL)
        {
            string strURL = "{pb_weburl}Images/System/wutu.gif";
            if (strImageURL != "")
            {
                if (CheckFile(strImageURL))
                    strURL = strImageURL.Replace("~/", "{pb_weburl}").Replace("../../", "{pb_webUrl}");
            }
            return strURL;
                    
        }


        /// <summary>
        ///  调用查询资讯列表
        /// </summary>
        /// <param name="strSelect">SQL语句</param>
        /// <returns></returns>
        public static DataTable GetDataTable(string strSql)
        {
            return SqlOperate.SqlHelper.ExecuteTable(strSql);
        }


        /// <summary>
        ///  调用查询资讯列表
        /// </summary>
        /// <param name="strSelect">查询的内容</param>
        /// <param name="strWhere">查询条件</param>
        /// <param name="strTableName">查询的表、视图、存储过程</param>
        /// <returns></returns>
        public static DataTable GetDataTable(string strSelect, string strWhere, string strTableName)
        {
            SqlParameter[] param = new SqlParameter[] 
            {  
                new SqlParameter("@StrSelect",strSelect),
                new SqlParameter("@strWhere",strWhere),
                new SqlParameter("@strTableName", strTableName), 
                new SqlParameter("@strOrder", "")
            };
            return SqlOperate.SqlHelper.ExecuteTable(CommandType.StoredProcedure, "SP_SelectByWhere", param);
        }


        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="p_strContent"></param>
        /// <returns></returns>
        public string SeparatePages(string p_strContent)
        {
            int m_intPageSize = 10000;  //文章每页大小
            int m_intCurrentPage = 1;   //设置第一页为初始页
            int m_intTotalPage = 0;     //共分几页
            int m_intArticlelength = p_strContent.Length;//文章长度
            string m_strRet = p_strContent;
            string m_strPageInfo = "";
            if (m_intPageSize < m_intArticlelength)
            {//如果每页大小大于文章长度时就不用分页了
                if (m_intArticlelength % m_intPageSize == 0)
                {//set total pages count 
                    m_intTotalPage = m_intArticlelength / m_intPageSize;
                }
                else
                {//if the totalsize
                    m_intTotalPage = m_intArticlelength / m_intPageSize + 1;
                }
                if (HttpContext.Current.Request.QueryString["pages"] != null)
                {
                    try  //set Current page number
                    {
                        m_intCurrentPage = Convert.ToInt32(HttpContext.Current.Request.QueryString["pages"]);
                        if (m_intCurrentPage > m_intTotalPage)
                            m_intCurrentPage = m_intTotalPage;
                    }
                    catch  //处理不正常的地址栏的值
                    {
                        m_intCurrentPage = m_intCurrentPage;
                    }
                }
                //set the page content 设置获取当前页的大小
                m_intPageSize = m_intCurrentPage < m_intTotalPage ? m_intPageSize : (m_intArticlelength - m_intPageSize * (m_intCurrentPage - 1));
                m_strRet = p_strContent.Substring(m_intPageSize * (m_intCurrentPage - 1), m_intPageSize);
                m_strPageInfo = "<p></p>";
                for (int i = 1; i <= m_intTotalPage; i++)
                {
                    if (i == m_intCurrentPage)
                        m_strPageInfo += "<b>" + i + "</b>｜";
                    else
                        m_strPageInfo += "<a href=当前页?pages=" + i + ">" + i + "</a>｜";
                }
                //输出显示各个页码
                //this.labPageNumber.Text = ;
            }
            return m_strRet + m_strPageInfo;
        }


        /// <summary>
        /// 长内容分页 哈希表需要引用命名空间System.Collections 
        /// </summary>
        /// <param name="n_content">新闻内容</param>
        /// <param name="page">是新闻当前页数</param>
        /// <param name="size">每页显示字符长度</param>
        /// <param name="linkurl">页码链接地址</param>
        /// <returns></returns>
        public static Hashtable SeparatePages(string n_content, string page, int size, string linkurl)
        {
            //在此处放置初始化页的用户代码



            System.Collections.Hashtable returnHash = new System.Collections.Hashtable();
            int start, stops, t, stat, pp, pagecount, pagesize;
            string pa, articletxt, articletext, html;
            int pig = 0;
            //变量初始值
            stat = 0;
            start = 0; //开始查询的字符串位置，初始为0
            stops = 0;
            pagesize = size;//定义每页至少显示字符串数
            pagecount = 0;
            html = "";
            //获得当前的页码
            pa = page;
            if (pa == "" || pa == null)
            {
                pa = "1";
            }
            pp = Convert.ToInt32(pa);   //获得当前页码
            //获得内容
            articletxt = n_content;
            //判断页面的内容长度是否大于定义的每页至少显示字符串数
            if (articletxt.Length >= pagesize) // 如果大于字符串数，则我们可以分页显示
            {
                t = articletxt.Length / pagesize; //获得大致的总页数
                for (int j = 0; j <= t; j++)
                { //如果查询开始位置到查询的范围超出整个内容的长度，那么就不用寻找断点（分页点）；反之，查找
                    if (start + pagesize < articletxt.Length)
                    {
                        stat = articletxt.ToLower().IndexOf("</p>", start + pagesize); //查找</P>分页点的位置
                        if (stat == -1)
                            stat = articletxt.ToLower().IndexOf("<br>", start + pagesize); //查找</P>分页点的位置
                        if (stat == -1)
                            stat = articletxt.ToLower().IndexOf("<br/>", start + pagesize); //查找</P>分页点的位置
                    }
                    if (stat <= 0)//如果找不到
                    {
                        stat = start + pagesize;
                    }
                    //else
                    //{
                    stops = stat; //分页点的位置也就作为这一页的终点位置
                    if (start < articletxt.Length)
                    {
                        if ((articletxt.Length - start) < pagesize)
                        {
                            if (pig == 0)
                            {
                                pagecount = pagecount + 1;
                            }
                            pig = 1;
                        }
                        else
                        {
                            pagecount = pagecount + 1;
                        }
                    }
                    if (start + pagesize >= articletxt.Length) //如果起始位置到查询的范围超出整个内容的长度，那么这一页的终点位置为内容的终点
                    {
                        stops = articletxt.Length;
                    }
                    if (pp == j + 1) //如果是当前，那么输出当前页的内容
                    {
                        articletext = articletxt.Substring(start, stops - start); //取内容的起始位置到终点位置这段字符串输出
                        returnHash["content"] = articletext;
                    }
                    start = stat; //将终点位置作为下一页的起始位置
                    //}
                }// pagecount = pagecount - 1;
            }
            else
            {
                returnHash["content"] = n_content;
            }
            //分页部分(这里就简单多了)
            //定义分页代码变量
            if (pagecount > 1) //当页数大于1的时候我们显示页数
            {
                if (pp - 1 > 0) //显示上一页，方便浏览
                { html = html + "<a href=\"" + linkurl + "-p" + (pp - 1)  + Base.BasePage.Config.Rewrite+ "\">[上一页]</a> "; }
                else
                {
                    if (pp == 1)
                    { html = html + ""; }
                    else
                    { html = html + "<a href=\"" + linkurl + "-p\"" + (1)  + Base.BasePage.Config.Rewrite +"\">[上一页]</a> "; }
                }
                for (int i = 1; i <= pagecount; i++)
                {
                    if (i == pp) //如果是当前页，无链接显示
                    { html = html + "[" + i + "] "; }
                    else
                    { html = html + "<a href=\"" + linkurl + "-p" + i + Base.BasePage.Config.Rewrite + "\">[" + i + "]</a> "; }
                }
                if (pp + 1 > pagecount) //显示下一页，方便浏览
                {
                    if (pp == pagecount)
                    { html = html + ""; }
                    else
                    { html = html + "<a href=\"" + linkurl + "-p" + (pagecount)  + Base.BasePage.Config.Rewrite+ "\">[下一页]</a></p>"; }
                }
                else
                {
                    html = html + "<a href=\"" + linkurl + "-p" + (pp + 1)  + Base.BasePage.Config.Rewrite+ "\">[下一页]</a></p>";
                }
            }
            returnHash["pagetxt"] = html;
            return returnHash;
        }


        /// <summary>
        /// 返回标签参数信息(0:参数错误，1:页面不存在，2：不能使用此标签)
        /// </summary>
        /// <returns></returns>
        public static string ErrInfo(int ErrID)
        {
            string strErrInfo = "";
            switch (ErrID)
            {
                case 0:
                    strErrInfo = "标签参数不正确，请检查标签参数";
                    break;
                case 1:
                    strErrInfo = "该页面不存在！";
                    break;
                case 2:
                    strErrInfo = "该标签不能在此模板使用！";
                    break;
                case 3:
                    strErrInfo = "此模板不存在！";
                    break;
                default:
                    strErrInfo = "";
                    break;
            }
            return strErrInfo;
        }


        /// <summary>
        /// 取得标签中的属性值
        /// </summary>
        /// <param name="strInfo"></param>
        /// <returns></returns>
        public static string[] GetAttribute(string strInfo)
        {
            string[] strCount;
            string str1 = "";
            Regex regex;
            RegexOptions options;
            options = RegexOptions.Singleline | RegexOptions.IgnoreCase;
            regex = new Regex(@"{PR:WS_\w+}", options);

            foreach (Match match in regex.Matches(strInfo))
            {
                str1 += match.Groups[0].ToString() + "|";
            }
            strCount = str1.Split('|');
            return strCount;
        }


        /// <summary>
        /// 取得指定字符之间的字符串
        /// </summary>
        /// <param name="str">要查找的字符串</param>
        /// <param name="StartStr">起始位置</param>
        /// <param name="EndStr">要取得的字符串长度</param>
        /// <returns></returns>
        public static string GetString(string str, int startIndex, int Length)
        {
            int intStart = 0;
            int intEnd = 0;
            if (startIndex > 0) intStart = startIndex;
            if (Length > 0) intEnd = Length;
            if (intEnd > intStart)
                if (str.Length < Length)
                    return str.Substring(intStart);
                else
                    return str.Substring(intStart, Length);
            else
                return str.Substring(intStart);

        }
        
        
        /// <summary>
        /// 取得从起始位置开始的指定长度的字符串
        /// </summary>
        /// <param name="str">要查找的字符串</param>
        /// <param name="EndStr">要取得的字符串长度</param>
        /// <returns></returns>
        public static string GetString(string str, int Length)
        {
            int intEnd = 0;
            if (Length > 0) intEnd = Length;
            if (intEnd > 0)
            {
                if (str.Length < intEnd)
                    return str;
                else
                    return str.Substring(0, intEnd);
            }
            return str;
        }


        /// <summary>
        /// 日期转换
        /// </summary>
        /// <param name="DateStr">需要转换的日期</param>
        /// <param name="DateModel">要转换成的格式[1:yyyy-mm-dd]</param>
        /// <returns></returns>
        public static string DateTransform(DateTime DateStr, string DateModel)
        {
            string Restr = "";
            if (DateStr.ToString() != string.Empty)
                switch (DateModel)
                {
                    case "yyyy/MM/dd":
                        Restr = DateStr.ToString("yyyy/MM/dd", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "MM/dd/yyyy":
                        Restr = DateStr.ToString("MM/dd/yyyy", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "yyyy-mm-dd":
                        Restr = DateStr.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "MM-dd-yyyy":
                        Restr = DateStr.ToString("MM-dd-yyyy", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "yyyy.MM.dd":
                        Restr = DateStr.ToString("yyyy.MM.dd", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "MM.dd.yyyy":
                        Restr = DateStr.ToString("MM.dd.yyyy", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "yyyy年MM月dd日":
                        Restr = DateStr.ToString("yyyy年MM月dd日", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "MM月dd日yyyy年":
                        Restr = DateStr.ToString("MM月dd日yyyy年", DateTimeFormatInfo.InvariantInfo);
                        break;
                    default:
                        Restr = DateStr.ToShortDateString();
                        break;
                }
            return Restr;
        }


        /// <summary>
        /// 日期转换
        /// </summary>
        /// <param name="DateStr">需要转换的日期</param>
        /// <param name="DateModel">要转换成的格式[1:yyyy-mm-dd]</param>
        /// <returns></returns>
        public static string DateTransform(string DateStr, int DateModel)
        {
            string Restr = "";
            if (DateStr != string.Empty)
                switch (DateModel)
                {
                    case 1:
                        Restr = Convert.ToDateTime(DateStr).ToShortDateString();
                        break;
                }
            return Restr;
        }


        /// <summary>
        /// 日期转换
        /// </summary>
        /// <param name="DateStr">需要转换的日期</param>
        /// <param name="DateModel">要转换成的格式[1:yyyy-mm-dd]</param>
        /// <returns></returns>
        public static string DateTransform(string DateStr, string DateModel)
        {
            string Restr = "";
            if (DateStr != string.Empty)
                switch (DateModel)
                {
                    case "yyyy-mm-dd":
                        Restr = Convert.ToDateTime(DateStr).ToShortDateString();
                        break;
                }
            return Restr;
        }


        /// <summary>
        /// 检测Get请求的是否为整数
        /// </summary>
        /// <param name="strParam">传回来的参数</param>
        /// <returns>如果不是</returns>
        public static bool CheckQueryStringisInt(string strParame)
        {
            if (HttpContext.Current.Request.QueryString[strParame] == null || HttpContext.Current.Request.QueryString[strParame] == "")
            {
                return false;
            }
            else
            {    
                return Regex.IsMatch(HttpContext.Current.Request.QueryString[strParame].ToString(), @"^\+?[1-9][0-9]*$");
            }
        }

        /// <summary>
        ///  把Get请求转换为INT类型
        /// </summary>
        /// <param name="strParame"></param>
        /// <returns></returns>
        public static int StringtoIntforQueryString(string strParame)
        {
            if (HttpContext.Current.Request.QueryString[strParame] == null || HttpContext.Current.Request.QueryString[strParame] == "")
            {
                throw new Exception(ErrInfo(0));
            }
            else
            {
                if (Regex.IsMatch(HttpContext.Current.Request.QueryString[strParame].ToString(), @"^\+?[1-9][0-9]*$"))
                {
                    return Convert.ToInt32(HttpContext.Current.Request.QueryString[strParame].ToString());
                }
                else
                {
                    throw new Exception(ErrInfo(0));
                }
            }
        }
    }
}