using System;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;

namespace Stat.Plugin
{
    public class Common
    {

        /// <summary>
        /// 颜色列表(12组)
        /// </summary>
        /// <returns></returns>
        public static String[] RpColor()
        {
            return new string[12] { "AFD8F8", "F6BD0F", "8BBA00", "FF8E46", "008E8E", "D64646", "8E468E", "588526", "B3AA00", "008ED6", "9D080D", "A186BE" };

        }
        /// <summary>
        /// 方法：获取参数，如不存在，将返回0（）
        /// </summary>
        /// <param name="id">参数的 ID</param>
        /// <returns></returns>
        /// <remarks>Juju 2011-10-24</remarks>
        public static int Rq_Int(string id)
        {
            if (HttpContext.Current.Request[id.ToLower()] != null)
            {
                string str = HttpContext.Current.Request[id.ToLower()].Trim();
                int rInt = 0;
                Int32.TryParse(str, out rInt);
                return rInt;
            }
            return 0;
        }

        public static int ConvertToInt(string str)
        {
            int rInt = 0;
            int.TryParse(str, out rInt);
            return rInt;
        }

        /// <summary>
        /// 方法：获取参数，如不存在，将返回DateTime.Now
        /// </summary>
        /// <param name="dt">参数的 ID</param>
        /// <returns></returns>
        public static DateTime Rq_DateTime(string dt)
        {
            if (HttpContext.Current.Request[dt.ToLower()] != null)
            {
                try
                {
                    return Convert.ToDateTime(HttpContext.Current.Request[dt.ToLower()]);
                }
                catch (Exception)
                {
                    return new DateTime();
                }
            }
            return new DateTime();
        }
        /// <summary>
        /// 方法：获取参数，如不存在，将返回空值
        /// </summary>
        /// <param name="id">参数的 ID</param>
        /// <returns></returns>
        public static string Rq(string id)
        {
            if (HttpContext.Current.Request[id.ToLower()] != null)
            {
                return HttpContext.Current.Request[id.ToLower()].Trim();
            }
            return "";
        }
        /// <summary>
        /// 栏目的级别效果
        /// </summary>
        /// <param name="sName">栏目</param>
        /// <param name="sCode">编码</param>
        /// <returns></returns>
        public static string Getlevel(string sName, string sCode)
        {
            int Level = (sCode.Length / 4 - 1) * 2;
            string sStr = sCode.Length == 4 ? "" : "├";
            if (Level > 0)
            {
                for (int i = 0; i < Level; i++)
                    sStr += "－";
            }
            return sStr + sName;
        }
        /// <summary>
        /// 是否是数字
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static bool IsNumeric(string str)
        {
            Regex r = new Regex(@"^\d+(\.)?\d*$");
            if (r.IsMatch(str))
                return true;
            else
                return false;
        }
        /// <summary>
        /// 标题颜色
        /// </summary>
        /// <returns></returns>
        public static string[] ColorArray()
        {
            return new string[] { "", "#FF0000", "#37a61c", "#0066CC" };
        }
        /// <summary>
        /// 截取长度
        /// </summary>
        /// <param name="s">原字符</param>
        /// <param name="len">需要的长度</param>
        /// <returns></returns>
        public static string Cut(string str, int len)
        {
            int intLen = str.Length;
            int start = 0;
            int end = intLen;
            int single = 0;
            char[] chars = str.ToCharArray();
            for (int i = 0; i < chars.Length; i++)
            {
                if (Convert.ToInt32(chars[i]) > 255)
                {
                    start += 2;
                }
                else
                {
                    start += 1;
                    single++;
                }
                if (start >= len)
                {

                    if (end % 2 == 0)
                    {
                        if (single % 2 == 0)
                        {
                            end = i + 1;
                        }
                        else
                        {
                            end = i;
                        }
                    }
                    else
                    {
                        end = i + 1;
                    }
                    break;
                }
            }
            string temp = str.Substring(0, end);
            if (str.Length > end)
            {
                return temp + "...";
            }
            else
            {
                return temp;
            }

        }

        /// <summary>
        /// 时间格式转换
        /// </summary>
        /// <param name="t">时间</param>
        /// <param name="style">需要的时间格式
        /// -1 无
        /// 0：默认
        /// 1：2009年12月25日
        /// 2：18:51:49
        /// 3：2010-1-23
        /// 4：18:51       
        /// 5：12-25      
        /// </param>
        /// <returns></returns>
        public static string Cut(DateTime t, int style)
        {
            string tep = string.Empty;

            switch (style)
            {
                case -1:
                    break;
                case 0:
                    tep = t.ToString();
                    break;
                case 1:
                    tep = t.ToLongDateString();
                    break;
                case 2:
                    tep = t.ToLongTimeString();
                    break;
                case 3:
                    tep = t.ToShortDateString();
                    break;
                case 4:
                    tep = t.ToShortTimeString();
                    break;
                case 5:
                    tep = t.Month.ToString() + "-" + t.Day.ToString();
                    break;
                default:
                    tep = t.ToString();
                    break;
            }
            return tep;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string SafeRequest(string str)
        {
            return str;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="DateTime1"></param>
        /// <param name="DateTime2"></param>
        /// <returns></returns>
        public static TimeSpan DateDiff(DateTime DateTime1, DateTime DateTime2)
        {

            TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
            TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();
            return ts;
        }
        public static bool ChkForm(string obj)
        {
            if (obj.IndexOf('>') > -1 || obj.IndexOf('<') > -1 || obj.IndexOf('\'') > -1 || obj.IndexOf("\"\"") > -1)
                return false;
            else
                return true;
        }
        /// <summary>
        /// 去掉文章内容的 标签
        /// </summary>
        public static string DealHtml(string str)
        {
            str = Regex.Replace(str, @"\<(img)[^>]*>|<\/(img)>", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\<(table|tbody|tr|td|th|)[^>]*>|<\/(table|tbody|tr|td|th|)>", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\<(div|blockquote|fieldset|legend)[^>]*>|<\/(div|blockquote|fieldset|legend)>", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\<(font|i|u|h[1-9]|s)[^>]*>|<\/(font|i|u|h[1-9]|s)>", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\<(style|strong)[^>]*>|<\/(style|strong)>", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\<a[^>]*>|<\/a>", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\<(meta|iframe|frame|span|tbody|layer)[^>]*>|<\/(iframe|frame|meta|span|tbody|layer)>", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"\<br[^>]*", "", RegexOptions.IgnoreCase);
            return str;
        }
        /// <summary>
        /// 弹出 提示
        /// </summary>
        /// <param name="tep"></param>
        public static void Alert(string msg, string path)
        {
            HttpContext.Current.Response.Write("<script>alert(\"" + msg + "\");location.href=\"" + path + "\";</script>");
        }
        /// <summary>
        /// 弹出 提示
        /// </summary>
        /// <param name="tep"></param>
        public static void Alert(string msg)
        {
            HttpContext.Current.Response.Write("<script>alert(\"" + msg + "\");</script>");
        }
        /// <summary>
        /// 弹出 提示 并 整 窗口导航
        /// </summary>
        /// <param name="tep"></param>
        public static void Alert_Top(string msg, string path)
        {
            HttpContext.Current.Response.Write("<script>alert(\"" + msg + "\");top.location.href=\"" + path + "\";</script>");
        }
        /// <summary>
        /// 整 窗口导航
        /// </summary>
        /// <param name="path"></param>
        public static void top_location(string path)
        {
            HttpContext.Current.Response.Write("<script>top.location.href=\"" + path + "\";</script>");
        }
        /// <summary>
        /// 历史记录跳转
        /// </summary>
        /// <param name="i"></param>
        public static void HistoryGo(int i)
        {
            HttpContext.Current.Response.Write("<script>history.go(" + i + ");</script>");
        }



        /// <summary>
        /// 提示：出错提示！
        /// </summary>
        /// <param name="w"></param>
        public static void ShowErr(string ex)
        {
            HttpContext.Current.Response.Write("<link href=\"css/old/style.css\" type=text/css rel=stylesheet>");
            string err = "<table cellpadding=3 cellspacing=1 align=center class=tableborder style='width:60%'><tr align=center><th width='100%' height=25 colspan=2>系统信息 </th></tr><tr><td width='100%' bgcolor='ffffff' colspan=2 align='left'> ";
            err += "<b>产生错误的可能原因：</b><br>";
            err += "<br><li>" + ex + "</li>";
            if (ex == null || ex.Length == 0)
            {
                err += "<br><li>您是否仔细阅读了帮助文件，可能您还没有登陆或者不具有使用当前功能的权限。 </li>";
            }
            err += "<br></td></tr><tr><td valign=middle colspan=2 align=center class=forumRowHighlight><a href=# onclick=history.go(-1)>返回上一页</a></td></tr></table>";
            HttpContext.Current.Response.Write(err);
            HttpContext.Current.Response.End();
        }
        /// <summary>
        /// 进度条
        /// </summary>
        /// <param name="current">当前数</param>
        /// <param name="count">总数</param>
        public static void processBar(int current, int count)
        {
            if (current == 0)
            {
                string strFileName = HttpContext.Current.Request.PhysicalApplicationPath + "\\plugin\\progressbar.htm";
                System.IO.StreamReader sr = new System.IO.StreamReader(strFileName, System.Text.Encoding.Default);
                string strHtml = sr.ReadToEnd();
                HttpContext.Current.Response.Write(strHtml);
                sr.Close();
                HttpContext.Current.Response.Flush();
            }
            HttpContext.Current.Response.Write("<script>setPgb(\"pgbMain\"," + ((current + 1) * 100) / count + ");</script>");
            HttpContext.Current.Response.Flush();
        }
        /// <summary>
        /// 创建 文件
        /// </summary>
        public static void CreatFile(string fullPath)
        {

            fullPath = HttpContext.Current.Server.MapPath(fullPath);
            string _Path = fullPath.Substring(0, fullPath.LastIndexOf('\\'));
            if (!System.IO.File.Exists(fullPath))
            {
                if (!System.IO.Directory.Exists(_Path))
                {
                    System.IO.Directory.CreateDirectory(_Path);
                }
                System.IO.File.CreateText(fullPath);
            }
        }

        /// <summary>
        /// 获取 MD5 加密 后的 字符串
        /// </summary>
        /// <param name="tep">加密前的 字符串</param>
        /// <returns></returns>
        public static string MD5(string tep)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(tep, "MD5").ToString();
        }
        /// <summary>
        /// 标题加上颜色
        /// </summary>
        /// <param name="TColor">颜色编号</param>
        /// <param name="Title">标题</param>
        /// <returns></returns>
        public static string TitleAddColor(int TColor, string Title)
        {
            string TempStr = "";
            switch (TColor)
            {
                case 1:
                    TempStr = "#FF0000";
                    break;
                case 2:
                    TempStr = "#37a61c";
                    break;
                case 3:
                    TempStr = "#0066CC";
                    break;
            }
            if (TColor == 0)
                return Title;
            else
                return "<font color=\"" + TempStr + "\">" + Title + "</font>";
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string GetHTTP_HOST()
        {
            return HttpContext.Current.Request.ServerVariables["HTTP_HOST"].ToString();
        }
        public static int GetWebConfig_int(string wName)
        {
            int hour = 0;

            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Cache[wName] == null)
                {

                    if (ConfigurationManager.AppSettings.Get(wName) != null)
                    {
                        hour = int.Parse(ConfigurationManager.AppSettings.Get(wName));
                    }
                    HttpContext.Current.Cache.Insert(wName, hour);
                }
                return int.Parse(HttpContext.Current.Cache[wName].ToString());
            }
            else
            {
                return int.Parse(ConfigurationManager.AppSettings.Get(wName));
            }
        }

        public static string GetWebConfig_Str(string wName)
        {
            string str = "";
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Cache[wName] == null)
                {

                    if (ConfigurationManager.AppSettings.Get(wName) != null)
                    {
                        str = ConfigurationManager.AppSettings.Get(wName);

                    }
                    HttpContext.Current.Cache.Insert(wName, str);
                }
                return HttpContext.Current.Cache[wName].ToString();
            }
            else
            {
                return ConfigurationManager.AppSettings.Get(wName);
            }
        }

        public static string GetVpageParmar(Model.SearchInfo model)
        {
            string str = string.Empty;
            if (model.BrowserID != 0) { str += "&bs=" + model.BrowserID; }
            if (model.OperatingSystemId != 0) { str += "&sys=" + model.OperatingSystemId; }
            if (model.ResolutionId != 0) { str += "&rs=" + model.ResolutionId; }
            if (model.LanguageId != 0) { str += "&lg=" + model.LanguageId; }
            if (model.ColorDepthId != 0) { str += "&cd=" + model.ColorDepthId; }
            if (model.NetClrVersionId != 0) { str += "&fw=" + model.NetClrVersionId; }
            //
            if (model.IsAlexa > -1) { str += "&ax=" + model.IsAlexa; }
            if (model.IsJava > -1) { str += "&ja=" + model.IsJava; }
            //
            if (model.View_Alone > 0) { str += "&ax=" + model.View_Alone; }
            if (model.CoId > 0) { str += "&co=" + model.CoId; }
            if (model.CtId > 0) { str += "&ct=" + model.CtId; }

            return str;
        }
    }
}
