using System;
using System.Collections.Generic;
using System.Threading;
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 System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using System.Net;

namespace WebCode
{
    


    /// <summary>
    /// function 的摘要说明
    /// </summary>
    public class function
    {
        public function()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        

        /// <summary>
        /// Email防止采集 
        /// </summary>
        /// <param name="s_in"></param>
        /// <returns></returns>
        public static string EmailEncode(string s_in)
        {
            char[] c_con = s_in.ToCharArray();
            StringBuilder sb_ret = new StringBuilder();

            for (int i = 0; i < c_con.Length; i++)
            {
                sb_ret.Append("&#" + Convert.ToInt32(c_con[i]).ToString("000") + ";");
            }

            return sb_ret.ToString();
        }

    

        /// <summary>
        /// 获得链接中变量的值
        /// </summary>
        /// <param name="s_url"></param>
        /// <param name="s_name"></param>
        /// <returns></returns>
        public static string GetUrlPara(string s_url, string s_name)
        {
            return Regex.Match(s_url, "&?" + s_name + "=(?<name>[^&]*)", RegexOptions.IgnoreCase).Groups["name"].ToString();

        }

        

        public static void DeleteFiles(string Dir, string searchPattern)
        {
            foreach (string s in System.IO.Directory.GetFiles(Dir, searchPattern))
                System.IO.File.Delete(s);
        }

        

        /// <summary>
        /// 替换页面中的内容 tags 链接 李旭日做的正则表达式
        /// </summary>
        /// <param name="s_in"></param>
        /// <param name="s_word"></param>
        /// <param name="s_target"></param>
        /// <returns></returns>
        public static string ReplaceHTML(string s_in, string s_word, string s_target, int i_count)
        {
            ReplaceExt re = new ReplaceExt();
            if (string.IsNullOrEmpty(s_word))
                return s_in;
            else
                return re.Replace(s_in, s_word, s_target, i_count);

        }

        /// <summary>
        /// 获得非空内容
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetValue(object obj)
        {
            if (obj == null)
            {
                return "";
            }
            else
            {
                return obj.ToString();
            }
        }

       

        

        /// <summary>
        /// 处理页面路径
        /// </summary>
        /// <param name="s_urlpath"></param>
        /// <returns></returns>
        public static string GetUrlMd5(string s_urlpath)
        {
            string s_url = s_urlpath;
            if (s_url.Length > 1)
            {
                if (s_url.Substring(s_url.Length - 1) == "/")
                    s_url = s_url.Substring(0, s_url.Length - 1);
            }
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s_url.ToLower(), "MD5");
        }

       


        /// <summary>
        /// 返回上一个链接
        /// </summary>
        /// <returns></returns>
        public static string BackUrl()
        {
            string s_ret = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
            if (String.IsNullOrEmpty(s_ret))
                s_ret = "";

            return s_ret;
        }

        /// <summary>
        /// '查询蜘蛛
        /// </summary>
        /// <returns></returns>
        public static bool GetBot()
        {

            bool b_ret = false;

            if (GetSpiderBot() != "")
                b_ret = true;

            return b_ret;
        }

        /// <summary>
        /// 获得蜘蛛程序
        /// </summary>
        /// <returns></returns>
        public static string GetSpiderBot()
        {
            string s_agent = "";
            string s_bot = "(?<bot>googlebot|msnbot|slurp|baiduspider|sogou|yodaobot)";
            string s_ret = "";
            s_agent = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];

            if (s_agent == null)
                return "";

            if (Regex.IsMatch(s_agent, s_bot, RegexOptions.IgnoreCase))
            {

                s_ret = Regex.Match(s_agent, s_bot, RegexOptions.IgnoreCase).Groups["bot"].Value;
            }

            return s_ret.ToLower();
        }

        public static void GCClear()
        {
            GC.Collect();
        }

        /// <summary>
        /// 获得某模板的内容
        /// </summary>
        /// <param name="i_id"></param>
        /// <returns></returns>
        public static string GetTemplateHTML(int i_id)
        {
            string s_ret = "";
            string s_fn = DataSet.GetInstance().GetDataString("select T_Path from User_Template where  T_ID=" + i_id, "@T_Path@");
            if (!String.IsNullOrEmpty(s_fn))
            {
                s_ret = function.ReadText("/template/html/" + s_fn);
            }

            return s_ret;
        }

        public static void WriteText(string s_fn, string s_content)
        {
            string s_ret = "";
            string s_path = HttpContext.Current.Server.MapPath("/") + s_fn.Replace("/", "\\");

            System.IO.File.WriteAllText(s_path, s_content, System.Text.Encoding.UTF8);

            //if (!File.Exists(s_path))
            //{

                
            //}
        }


        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="s_fn"></param>
        /// <returns></returns>
        public static string ReadText(string s_fn)
        {
            string s_ret = "";
            string s_path = HttpContext.Current.Server.MapPath("/") + s_fn.Replace("/", "\\");
            if (File.Exists(s_path))
            {
                s_ret = System.IO.File.ReadAllText(s_path, System.Text.Encoding.UTF8);
            }
            return s_ret;
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="s_fn"></param>
        /// <returns></returns>
        public static string ReadPathText(string s_path)
        {
            string s_ret = "";
            if (File.Exists(s_path))
            {
                s_ret = System.IO.File.ReadAllText(s_path, System.Text.Encoding.UTF8);
            }
            return s_ret;
        }

        
        

        public static int GetNumber(Object o_in)
        {
            //转换成数字
            if (o_in != null)
            {
                if (String.IsNullOrEmpty(o_in.ToString()))
                    return 0;
                else
                {
                    if (function.isNumeric(o_in.ToString()))
                    {
                        return Int32.Parse(o_in.ToString());
                    }
                    else
                        return 0;
                }
            }
            else
                return 0;


        }

        public static int Ceil(double d_get)
        {
            //22.2=23 -22.2=-22
            if (d_get > (Int32)d_get)
                return (int)(d_get + 1);
            else
                return (int)(d_get);

        }


        private static string GetNumberPageUrl(string s_url, int i_page)
        {
            string s_ret = s_url;
            if (i_page == 1)
                s_ret = s_ret.Replace("_P1", "");

            return s_ret;
        }

        public static string GetNumberPage(string s_url, int i_pageNow, int i_pageCount)
        {
            return GetNumberPage(s_url, i_pageNow, i_pageCount, false);
        }

        /// <summary>
        /// 获得翻页
        /// </summary>
        /// <param name="s_url"></param>
        /// <param name="i_pageNow"></param>
        /// <param name="i_pageCount"></param>
        /// <returns></returns>
        public static string GetNumberPage(string s_url, int i_pageNow, int i_pageCount,bool b_imagebar)
        {
            //获得页数
            Language lang = Language.GetInstance();

            if (i_pageCount == 1)
                return "";

            int i_min = 0, i_max = 0;
            int i_cyc = 0;
            StringBuilder sb_ret = new StringBuilder();

            i_min = i_pageNow - 5;
            if (i_min <= 0)
            {
                i_min = 1;
            }

            i_max = i_min + 9;

            if (i_max > i_pageCount)
            {
                i_max = i_pageCount;
            }

            if ((i_max - i_min < 9) && (i_max - 9 > 0))
            {
                i_min = i_max - 9;
            }

            if (i_pageNow > 1)
            {
                if (b_imagebar) //图片
                {
                    sb_ret.Append("<a class='prepage' href=\"" + GetNumberPageUrl(s_url.Replace("@pagenumber@", (i_pageNow - 1).ToString()), (i_pageNow - 1)) + "\" >&nbsp;</a> ");
                }
                else
                {
                    sb_ret.Append("<a class='prepage' href=\"" + GetNumberPageUrl(s_url.Replace("@pagenumber@", (i_pageNow - 1).ToString()), (i_pageNow - 1)) + "\" >" + lang["上一页"] + "</a> ");
                }
                
            }

            for (i_cyc = i_min; i_cyc <= i_max; i_cyc++)
            {
                if (i_cyc == i_pageNow)
                {
                    //本页
                    sb_ret.Append("<span  class='nowpage' >" + i_cyc.ToString() + "</span> ");
                }
                else
                {
                    //如果页面为1，就去掉 _P1
                    if (b_imagebar)
                    {
                        sb_ret.Append("<a  class='pagenumber'   href=\"" + GetNumberPageUrl(s_url.Replace("@pagenumber@", i_cyc.ToString()), i_cyc) + "\" >" + i_cyc.ToString() + "</a> ");
                    }
                    else
                    {
                        sb_ret.Append("<a  class='pagenumber'   href=\"" + GetNumberPageUrl(s_url.Replace("@pagenumber@", i_cyc.ToString()), i_cyc) + "\" >[" + i_cyc.ToString() + "]</a> ");
                    }
                }
            }

            if (i_pageNow < i_pageCount)
            {
                if (b_imagebar)
                {
                    sb_ret.Append("<a  class='nextpage'  href=\"" + s_url.Replace("@pagenumber@", (i_pageNow + 1).ToString()) + "\" >&nbsp;</a> ");
                }
                else
                {
                    sb_ret.Append("<a  class='nextpage'  href=\"" + s_url.Replace("@pagenumber@", (i_pageNow + 1).ToString()) + "\" >" + lang["下一页"] + "</a> ");
                }
                
            }



            return sb_ret.ToString();

        }

        

        /// <summary>
        /// 获取安全的内容
        /// </summary>
        /// <param name="s_in"></param>
        /// <returns></returns>
        public static string GetSafeString(string s_in)
        {
            return s_in.Replace("'", "''");
        }

        public static void Alert(string s_tip)
        {
            //加入提示

            if (s_tip != "")
            {
                RunScript("alert('" + s_tip.Replace("'", "\'") + "');");
            }


        }

        public static void RunScript(string s_run)
        {
            //运行程序
            HttpContext.Current.Response.Write("<script language=\"javascript\">\n " + s_run + "; \n </script>");
        }

        public static string GetPara(string s_in)
        {
            //得到输入参数
            return GetRequest(HttpContext.Current.Request.Params[s_in]);
        }

        

        public static string GetRequest(Object o_in)
        {
            //返回request的值
            if (o_in == null)
            {
                return "";
            }
            else
            {
                return o_in.ToString();
            }
        }

        public static bool isNumeric(string str)
        {
            //判断是否是数字
            return Regex.IsMatch(str, @"^[+-]?\d*$");
        }

        public static string GetPageHTMLOutput(string s_in)
        {

            //按照一点的格式输出内容
            s_in = System.Web.HttpUtility.HtmlEncode(s_in);
            s_in = s_in.Replace("\r\n", " ");
            s_in = s_in.Replace("  ", "&nbsp;&nbsp;");
            s_in = s_in.Replace("\"", "&quot;");

            return s_in;

        }

        public static string DocumentWrite(string s_in)
        {
            return "document.write(\"" + s_in.Replace("\"", "\\\"") + "\") \r\n";
        }

        public static string GetHTMLOutput(string s_in)
        {

            //按照一点的格式输出内容
            s_in = System.Web.HttpUtility.HtmlEncode(s_in);
            s_in = s_in.Replace("\r\n", "<br />");
            s_in = s_in.Replace("  ", "&nbsp;&nbsp;");
            s_in = s_in.Replace("\"", "&quot;");

            return s_in;

        }

        /// <summary>
        /// 获得有限的字符
        /// </summary>
        /// <param name="s_in"></param>
        /// <param name="i_len"></param>
        /// <returns></returns>
        public static string GetLimitChar(string s_in, int i_len)
        {
            //获得合适长度的字符
            s_in = s_in.Trim();
            int i_str = ((byte[])Encoding.Default.GetBytes(s_in)).Length;
            string s_ret = "";
            if (i_str < i_len)
            {
                s_ret = s_in;
            }
            else
            {
                string s_char;
                int i_cyc, i_now = 0;
                for (i_cyc = 0; i_cyc < s_in.Length; i_cyc++)
                {
                    s_char = s_in.Substring(i_cyc, 1);
                    i_now += ((byte[])Encoding.Default.GetBytes(s_char)).Length;
                    if (i_now > i_len)
                    {
                        break;
                    }
                    else
                    {
                        s_ret += s_char;
                    }

                }
            }
            if (s_ret != s_in)
            {
                s_ret += "...";
            }

            return s_ret;

        }

        public static string GetLimitRevChar(string s_in, int i_len)
        {
            //获得合适长度的字符
            s_in = s_in.Trim();
            int i_str = GetStringLength(s_in);
            StringBuilder s_ret = new StringBuilder();

            if (i_str < i_len)
            {
                s_ret.Append(s_in);
            }
            else
            {
                //避免出现半个汉字的情况
                string s_char;
                int i_cyc, i_now = 0;
                for (i_cyc = s_in.Length - 1; i_cyc > 0; i_cyc--)
                {
                    s_char = s_in.Substring(i_cyc, 1);
                    i_now += ((byte[])Encoding.Default.GetBytes(s_char)).Length;
                    if (i_now > i_len)
                    {
                        break;
                    }
                    else
                    {
                        s_ret.Insert(0, s_char);
                    }
                }
                s_ret.Insert(0, "...");
            }

            return s_ret.ToString();

        }

        /// <summary>
        /// 获得字符串真实的长度
        /// </summary>
        /// <param name="s_in"></param>
        /// <returns></returns>
        public static int GetStringLength(string s_in)
        {
            return ((byte[])Encoding.Default.GetBytes(s_in)).Length;
        }

        /// <summary>
        /// 建立目录
        /// </summary>
        /// <param name="buildPath"></param>
        public static void BuildDirectory(string buildPath)
        {

            if (!System.IO.Directory.Exists(buildPath))
            {
                System.IO.Directory.CreateDirectory(buildPath);
            }
        }

        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="path"></param>
        public static void RemoveDirectory(string path)
        {
            

            DeleteFiles(path, "*.*");
        }

        

        /// <summary>
        /// 通过字符串返回日期
        /// </summary>
        /// <param name="s_value"></param>
        /// <returns></returns>
        public static DateTime GetDateTime(string s_value)
        {
            DateTime o_ret = new DateTime(1900, 1, 1);
            try
            {
                o_ret = DateTime.Parse(s_value);
            }
            catch (Exception ex)
            {

            }
            return o_ret;
        }

        public static string GetDate(string s_value)
        {
            DateTime o_ret = new DateTime(1900, 1, 1);
            try
            {
                if (!string.IsNullOrEmpty(s_value))
                    o_ret = DateTime.Parse(s_value);
            }
            catch (Exception ex)
            {

            }
            return o_ret.ToString("yyyy-MM-dd");
        }

        public static string GetTime(string s_value)
        {
            DateTime o_ret = new DateTime(1900, 1, 1);
            try
            {
                o_ret = DateTime.Parse(s_value);
            }
            catch (Exception ex)
            {

            }
            return o_ret.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public static string GetMTime(string s_value)
        {
            DateTime o_ret = new DateTime(1900, 1, 1);
            try
            {
                o_ret = DateTime.Parse(s_value);
            }
            catch (Exception ex)
            {

            }
            return o_ret.ToString("yyyy-MM-dd HH:mm");
        }

        
    }
}