using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Edu.Common.Plugin
{
    /// <summary>
    /// 字符相关辅助类
    /// </summary>
    public class StringHelper
    {

        #region "随机数"


        /// <summary>
        /// 随机生成8位随机数
        /// </summary>
        /// <returns></returns>
        public static string GenerateGuid8String()
        {
            string guid = GenerateGuid16String(Guid.NewGuid());
            return guid.Substring(0, 8);
        }

        /// <summary> 
        /// Guid to string(16) 
        /// </summary> 
        public static string GenerateGuid16String()
        {
            return GenerateGuid16String(Guid.NewGuid());
        }

        /// <summary> 
        /// Guid to string(16) 
        /// </summary> 
        public static string GenerateGuid16String(Guid guid)
        {
            long i = 1;
            foreach (byte b in guid.ToByteArray())
                i *= ((int)b + 1);
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }

        #endregion

        #region "日期相关"
        /// <summary>
        /// 获取星期的字符串
        /// </summary>
        /// <param name="day">指定日期</param>
        /// <returns></returns>
        public static string GetWeekChar(DateTime day)
        {
            string[] str = new string[] { "日", "一", "二", "三", "四", "五", "六" };
            int week = int.Parse(day.DayOfWeek.ToString("D"));
            return "星期" + str[week];
        }

        /// <summary>
        /// 获取周几的字符串
        /// </summary>
        /// <param name="day">指定日期</param>
        /// <returns></returns>
        public static string GetWeek(DateTime day)
        {
            string[] str = new string[] { "日", "一", "二", "三", "四", "五", "六" };
            int week = int.Parse(day.DayOfWeek.ToString("D"));
            return "周" + str[week];
        }

        /// <summary>
        /// 获取星期几[英文版]
        /// </summary>
        /// <param name="day"></param>
        /// <returns></returns>
        public static string GetWeek_eg(DateTime day)
        {
            string[] str = new string[] { "Sun", "Mon", "Tues", "Wed", "Thu", "Fri", "Sat" };
            int week = int.Parse(day.DayOfWeek.ToString("D"));
            return str[week];
        }

        /// <summary>
        /// 获取星期几的字符串
        /// </summary>
        /// <param name="day">指定日期</param>
        /// <returns></returns>
        public static string GetWeekDay(DateTime day)
        {
            string[] str = new string[] { "日", "一", "二", "三", "四", "五", "六" };
            int week = int.Parse(day.DayOfWeek.ToString("D"));
            return "星期" + str[week];
        }
        /// <summary>
        /// 得到两个日期总天数
        /// </summary>
        /// <param name="dStart">开始日期</param>
        /// <param name="dEnd">结束日期</param>
        /// <returns></returns>
        public static int GetDateDayInterval(DateTime? dStart, DateTime? dEnd)
        {
            if (!dStart.HasValue || !dEnd.HasValue) return 0;
            //TimeSpan ts = Convert.ToDateTime(dEnd.Value.ToString("yyyy-MM-dd"))-(Convert.ToDateTime(dStart.Value.ToString("yyyy-MM-dd")));
            int TotalDay = 0;
            while (true)
            {
                if (dStart.Value.ToString("yyyy-MM-dd") == dEnd.Value.ToString("yyyy-MM-dd"))
                {
                    TotalDay += 1;
                    break;
                }
                else
                {
                    TotalDay += 1;
                }
                dStart = dStart.Value.AddDays(1);
            }

            return TotalDay;
        }

        /// <summary>
        /// 得到两个日期之差的时间戳
        /// </summary>
        /// <param name="dStart">开始日期</param>
        /// <param name="dEnd">结束日期</param>
        /// <returns></returns>
        public static TimeSpan GetDayTimeSpan(DateTime? dStart, DateTime? dEnd)
        {
            if (!dStart.HasValue || !dEnd.HasValue) return new TimeSpan();
            return dEnd.Value - dStart.Value;
        }

        /// <summary>
        /// 格式化日期为字符串2018-01-01 12:00:00
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string FormatDateTimeStr(object date)
        {
            try
            {
                DateTime.TryParse(date.ToString(), out DateTime dt);
                return dt.ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch
            {

            }
            return "";
        }

        /// <summary>
        /// 格式化日期
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string FormatDate(object date)
        {
            try
            {
                DateTime.TryParse(date.ToString(), out DateTime dt);
                return dt.ToString("yyyy-MM-dd");
            }
            catch
            {

            }
            return "";
        }

        /// <summary>
        /// 时间戳转换为时间
        /// </summary>
        /// <param name="ticks"></param>
        /// <returns></returns>
        public static DateTime GetDateTimeByTicks(string ticks)
        {
            try
            {
                DateTime startTime = TimeZoneInfo.ConvertTime(new System.DateTime(1970, 1, 1), TimeZoneInfo.Local); // 当地时区
                DateTime dt = startTime.AddMilliseconds(long.Parse(ticks));
                return dt;
            }
            catch (Exception)
            {
                return new DateTime(1970, 1, 1);
            }
        }

       
        /// <summary>
        /// 获取年份月份中的最后一天
        /// </summary>
        /// <param name="year">年份</param>
        /// <param name="month">月份</param>
        /// <returns></returns>
        public static DateTime GetMonthLastDay(int year, int month)
        {
            return new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
        }

        /// <summary>
        /// 是否为日期+时间型字符串
        /// </summary>
        /// <param name="StrSource"></param>
        /// <returns></returns>
        public static bool IsDateTime(object StrSource)
        {
            DateTime dt = DateTime.Now;
            if (DateTime.TryParse(StrSource.ToString(), out dt))
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 时间
        /// </summary>
        /// <param name="Time"></param>
        /// <returns></returns>
        public static string GetTypeOfMeal(DateTime? Time)
        {
            string returnStr = "";
            if (Time.HasValue)
            {
                if (Time.Value.Hour < 10)
                {
                    returnStr = "早餐";
                }
                else if (Time.Value.Hour >= 10 && Time.Value.Hour < 14)
                {
                    returnStr = "午餐";
                }
                else
                {
                    returnStr = "晚餐";
                }
            }

            return returnStr;
        }


        /// <summary>
        /// 时间
        /// </summary>
        /// <param name="Time"></param>
        /// <returns></returns>
        public static string GetTypeOfTime(DateTime? Time)
        {
            string returnStr = "";
            if (Time.HasValue)
            {
                if (Time.Value.Hour < 10)
                {
                    returnStr = "早上";
                }
                else if (Time.Value.Hour >= 10 && Time.Value.Hour < 14)
                {
                    returnStr = "中午";
                }
                else
                {
                    returnStr = "晚上";
                }
            }

            return returnStr;
        }

        /// <summary>
        /// 获取星期简写
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetWeek(string value)
        {
            string dateStr = "";
            switch (value.ToLower())
            {
                case "monday":
                    dateStr = "Mon";
                    break;
                case "tuesday":
                    dateStr = "Tues";
                    break;
                case "wednesday":
                    dateStr = "Wed";
                    break;
                case "thursday":
                    dateStr = "Thu";
                    break;
                case "friday":
                    dateStr = "Fri";
                    break;
                case "saturday":
                    dateStr = "Sat";
                    break;
                case "sunday":
                    dateStr = "Sun";
                    break;
                default:
                    break;
            }
            return dateStr.ToUpper();
        }

        /// <summary>
        /// 根据日期获取星期几
        /// </summary>
        /// <param name="date">日期</param>
        /// <returns></returns>
        public static int GetWeekDayNum(DateTime date)
        {
            int week = 1;
            var dt = date.DayOfWeek.ToString();
            switch (dt)
            {
                case "Monday":
                    week = 1;
                    break;
                case "Tuesday":
                    week = 2;
                    break;
                case "Wednesday":
                    week = 3;
                    break;
                case "Thursday":
                    week = 4;
                    break;
                case "Friday":
                    week = 5;
                    break;
                case "Saturday":
                    week = 6;
                    break;
                case "Sunday":
                    week = 7;
                    break;
            }
            return week;
        }

        /// <summary>
        /// 获取月份简写
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetDate(string value)
        {

            string dateStr = "";
            switch (value)
            {
                case "01":
                    dateStr = "JAN";
                    break;
                case "02":
                    dateStr = "FEB";
                    break;
                case "03":
                    dateStr = "MAR";
                    break;
                case "04":
                    dateStr = "APR";
                    break;
                case "05":
                    dateStr = "MAY";
                    break;
                case "06":
                    dateStr = "JUN";
                    break;
                case "07":
                    dateStr = "JUL";
                    break;
                case "08":
                    dateStr = "AUG";
                    break;
                case "09":
                    dateStr = "SEP";
                    break;
                case "10":
                    dateStr = "OCT";
                    break;
                case "11":
                    dateStr = "NOV";
                    break;
                case "12":
                    dateStr = "DEC";
                    break;
                default:
                    break;
            }
            return dateStr;
        }


        /// <summary>
        /// 取得某月的第一天
        /// </summary>
        /// <param name="datetime">要取得月份第一天的时间</param>
        /// <returns></returns>
        public static DateTime FirstDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day);
        }

        /// <summary>
        /// 取得某月的最后一天
        /// </summary>
        /// <param name="datetime">要取得月份最后一天的时间</param>
        /// <returns></returns>
        public static DateTime LastDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
        }

        /// <summary>
        /// 取得上个月第一天
        /// </summary>
        /// <param name="datetime">要取得上个月第一天的当前时间</param>
        /// <returns></returns>
        public static DateTime FirstDayOfPreviousMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(-1);
        }

        /// <summary>
        /// 取得上个月的最后一天
        /// </summary>
        /// <param name="datetime">要取得上个月最后一天的当前时间</param>
        /// <returns></returns>
        public static DateTime LastDayOfPrdviousMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddDays(-1);
        }

        /// <summary>
        /// 获取某月总天数
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static int GetMonthTotalDay(DateTime dt)
        {
            int day = dt.AddDays(1 - dt.Day).AddMonths(1).AddDays(-1).Day;
            return day;
        }

        /// <summary>
        /// 获取日期之间的周六周天的天数
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public static int TotalDay(DateTime startTime, DateTime endTime)
        {
            int TotalDay = 0;
            int dayCount = (endTime - startTime).Days;
            if (dayCount == 1)
            {
                string dt = startTime.DayOfWeek.ToString();
                if (dt == "Friday" || dt == "Saturday")
                {
                    TotalDay = 2;
                }
                else if (dt == "Sunday")
                {
                    TotalDay = 1;
                }
            }
            else
            {
                int Saturday = 0;
                int Sunday = 0;
                for (int i = 0; i < dayCount; i++)
                {
                    string dt = startTime.AddDays(i + 1).DayOfWeek.ToString();
                    switch (dt)
                    {
                        case "Saturday":
                            Saturday += 1;
                            break;
                        case "Sunday":
                            Sunday += 1;
                            break;
                    }
                }
                if (Sunday == 0 && Saturday == 1)//截止日期只有一个周六
                {
                    TotalDay = 2;
                }
                else if (Sunday == 1 && Saturday == 0)// 截止日期只有一个周天
                {
                    TotalDay = 1;
                }
                else
                {
                    if (Saturday > Sunday)
                    {
                        TotalDay = Saturday + Sunday + 2;
                    }
                    else
                    {
                        TotalDay = Saturday + Sunday + 1;
                    }
                }
            }
            return TotalDay;
        }


        public static string DateStringFromNow(DateTime dt)
        {
            TimeSpan span = DateTime.Now - dt;
            if (span.TotalDays > 60)
            {
                return dt.ToShortDateString();
            }
            else
            if (span.TotalDays > 30)
            {
                return "1个月前";
            }
            else
            if (span.TotalDays > 14)
            {
                return "2周前";
            }
            else
            if (span.TotalDays > 7)
            {
                return "1周前";
            }
            else
            if (span.TotalDays > 1)
            {
                return string.Format("{0}天前", (int)Math.Floor(span.TotalDays));
            }
            else
            if (span.TotalHours > 1)
            {
                return string.Format("{0}小时前", (int)Math.Floor(span.TotalHours));
            }
            else
            if (span.TotalMinutes > 1)
            {
                return string.Format("{0}分钟前", (int)Math.Floor(span.TotalMinutes));
            }
            else
            if (span.TotalSeconds >= 1)
            {
                return string.Format("{0}秒前", (int)Math.Floor(span.TotalSeconds));
            }
            else
            {
                return "1秒前";
            }
        }

        #endregion

        #region 字符转换


        /// <summary>
        /// 为字符串左边填充字符
        /// <example>
        /// 111   LPAD(,'0',8)  -->  00000111
        /// </example>
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="swap">替换的字符</param>
        /// <param name="length">长度</param>
        /// <returns></returns>
        public static string LPAD(object str, string swap, int length)
        {
            string s = str.ToString();

            for (int i = 0; i < length - str.ToString().Length; i++)
            {
                s = swap + s;
            }

            return s;
        }

        /// <summary>
        /// 填充字符到字符串左边
        /// </summary>
        /// <param name="str"></param>
        /// <param name="swap">填充的字符</param>
        /// <param name="len">长度</param>
        /// <returns></returns>
        public static string LFillChar(string str, string swap, int len)
        {
            for (int i = 0; i < len; i++)
            {
                str = swap + str;
            }

            return str;
        }



        /// <summary>
        /// 获取数字的中文字符
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static string GetNumberChar(int number)
        {
            string[] str = new string[] { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二" };

            if (number < 0 && number > str.Length)
            {
                return "{没有该数字的中文名称}";
            }

            return str[number - 1];
        }

        /// <summary>
        /// 转换字符串为整形值
        /// </summary>
        /// <param name="val"></param>
        /// <param name="invaildReturnVal">当数值无效返回值</param>
        /// <returns></returns>
        public static int ParseInt(string val, int invaildReturnVal)
        {
            if (string.IsNullOrEmpty(val) || !ValidateHepler.IsNumber(val))
                return invaildReturnVal;

            return int.Parse(val);
        }

        /// <summary>
        /// 字符串转化为字节
        /// </summary>
        /// <param name="Str"></param>
        /// <returns></returns>
        public static byte[] ToByte(string Str)
        {
            return Convert.FromBase64String(Str);
        }

        /// <summary>
        /// 字节转化为字符串
        /// </summary>
        /// <param name="Byt"></param>
        /// <returns></returns>
        public static string ToStr(Byte[] Byt)
        {
            return Convert.ToBase64String(Byt);
        }

        /// <summary>
        /// 正常转换为字节
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static Byte[] NormalToByte(string str)
        {
            return Encoding.Default.GetBytes(str);
        }

        /// <summary>
        /// 正常专号为字符串
        /// </summary>
        /// <param name="Byt"></param>
        /// <returns></returns>
        public static string NormalToStr(byte[] Byt)
        {
            return Encoding.Default.GetString(Byt);
        }

        /// <summary>
        /// 截取指定长度HTML内容 （该方法未完成）
        /// </summary>
        /// <param name="html"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string SubstringHTML(string html, int len)
        {
            return "";
        }

        /// <summary>
        /// 截取指定长度字符
        /// </summary>
        /// <param name="str"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string Substring(string str, int len)
        {
            return Substring(str, len, "");
        }

        /// <summary>
        /// 截取指定长度字符,字符过长可填充指定符号
        /// </summary>
        /// <param name="str"></param>
        /// <param name="len"></param>
        /// <param name="endFillChar"></param>
        /// <returns></returns>
        public static string Substring(string str, int len, string endFillChar)
        {
            if (str.Length < len)
                return str;
            else
                return str.Substring(0, len) + endFillChar;
        }

        /// <summary>
        /// 移除字符串末尾指定字符
        /// </summary>
        /// <param name="str">需要移除的字符串</param>
        /// <param name="value">指定字符</param>
        /// <returns>移除后的字符串</returns>
        public static string RemoveLastChar(string str, string value)
        {
            int _finded = str.LastIndexOf(value);
            if (_finded != -1)
            {
                return str.Substring(0, _finded);
            }
            return str;
        }

        /// <summary>
        /// 过滤HTML标志
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string FilterHtml(string html)
        {
            if (string.IsNullOrWhiteSpace(html))
            {
                return "";
            }
            //删除脚本
            html = Regex.Replace(html, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML
            html = Regex.Replace(html, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);

            //Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"-->", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"<!--.*", "", RegexOptions.IgnoreCase);

            html = Regex.Replace(html, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"\r", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"\n", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"\\", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @";", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @":", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"<p>", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&ldquo;", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"</p>", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&nbsp;", "", RegexOptions.IgnoreCase);
            html = html.Replace("<", "");
            html = html.Replace(">", "");
            html = html.Replace("\r\n", "");


            return html;
        }

        /// <summary>
        /// 转换HTML的特殊代码为实际字符
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string HtmlToChar(object html)
        {
            string str = html.ToString();


            str = str.Replace("<br>", "\n");
            str = str.Replace("&gt;", ">");
            str = str.Replace("&lt;", "<");
            str = str.Replace("&nbsp;", " ");
            str = str.Replace("&quot;", "\"");

            str = Regex.Replace(str, "<[^>]+>", "");

            return str;
        }

        /// <summary>
        /// 字符串转化为HTML
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static string CharToHtml(object str)
        {
            if (str == null) return "";

            string c = str.ToString();
            c = c.Replace("<", @"&lt;");
            c = c.Replace(">", @"&gt;");
            c = c.Replace("\r\n", @"<br/>");
            c = c.Replace(" ", "&nbsp;");

            return c;
        }

        /// <summary>
        ///  App过滤HTML的特殊代码
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string AppHtmlFilterr(string html)
        {
            if (string.IsNullOrWhiteSpace(html))
            {
                return "";
            }
            html = RemoveLastChar(html, "</p>");
            html = html.Replace("<br>", "\n");
            html = html.Replace("</p>", "</p>\n");
            html = html.Replace("</li>", "</li>\n");
            //删除脚本
            html = Regex.Replace(html, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML
            html = Regex.Replace(html, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"-->", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"<!--.*", "", RegexOptions.IgnoreCase);

            html = Regex.Replace(html, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"\r", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"\\", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @";", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @":", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"<p>", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&ldquo;", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"</p>", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&nbsp;", "", RegexOptions.IgnoreCase);
            html = html.Replace("<", "");
            html = html.Replace(">", "");
            return html;
        }

        /// <summary>
        /// 替换成Word换行符
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>

        public static string WordHtmlFilter(string html)
        {
            if (string.IsNullOrWhiteSpace(html))
            {
                return "";
            }
            html = RemoveLastChar(html, "</p>");

            html = html.Replace("</p>", "</p>");
            html = html.Replace("</li>", "</li>");
            //删除脚本
            html = Regex.Replace(html, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML
            html = Regex.Replace(html, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"-->", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"<!--.*", "", RegexOptions.IgnoreCase);

            html = Regex.Replace(html, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"\r", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"\\", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @";", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @":", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"<p>", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&ldquo;", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"</p>", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"&nbsp;", "", RegexOptions.IgnoreCase);
            html = html.Replace("<", "");
            html = html.Replace(">", "");
            return html;
        }
        #endregion

        #region url 相关

        /// <summary>
        /// 为url附加参数,自动识别？号
        /// </summary>
        /// <param name="url">原始网址</param>
        /// <param name="paramName">URL参数名称</param>
        /// <param name="paramValue">参数值不做urlenode处理，有需要外部处理</param>
        public static string AppendUrlParam(string url, string paramName, object paramValue)
        {
            string parm = string.Format("{0}={1}", paramName, paramValue.ToString());

            if (!url.Contains("?"))
                url += "?";
            if (url.Contains("&"))
                url += "&";

            url += parm;

            return url;
        }

        /// <summary>
        /// urlEncode字符串编码，转换为大写格式
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string UrlEncodeToUpperCase(string value)
        {

            value = System.Web.HttpUtility.UrlEncode(value, Encoding.UTF8);
            byte[] buf = Encoding.ASCII.GetBytes(value);// value.GetBytes("ASCII");//这里是我个人的扩展方法，等同于Encoding.ASCII.GetBytes(str)
            for (int i = 0; i < buf.Length; i++)
                if (buf[i] == '%')
                {
                    if (buf[i + 1] >= 'a') buf[i + 1] -= 32;
                    if (buf[i + 2] >= 'a') buf[i + 2] -= 32;
                    i += 2;
                }
            return Encoding.ASCII.GetString(buf);
        }
        /// <summary>
        /// urlEncode字符串编码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UrlEncode(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                return System.Web.HttpUtility.UrlEncode(str).Replace("+", "%20");
            }
            else
            {
                return "";
            }

        }
        /// <summary>
        /// urlDecode字符串编码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UrlDecode(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                return System.Web.HttpUtility.UrlDecode(str);
            }
            else
            {
                return "";
            }

        }

        /// <summary>
        /// 字符串转Unicode
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToUnicodeString(string str)
        {
            StringBuilder strResult = new StringBuilder();
            if (!string.IsNullOrEmpty(str))
            {
                for (int i = 0; i < str.Length; i++)
                {
                    strResult.Append("\\u");
                    strResult.Append(((int)str[i]).ToString("x"));
                }
            }
            return strResult.ToString();
        }
        /// <summary>
        /// Unicode转字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string FromUnicodeString(string str)
        {
            //最直接的方法Regex.Unescape(str);
            StringBuilder strResult = new StringBuilder();
            if (!string.IsNullOrEmpty(str))
            {
                string[] strlist = str.Replace("\\", "").Split('u');
                try
                {
                    for (int i = 1; i < strlist.Length; i++)
                    {
                        int charCode = Convert.ToInt32(strlist[i], 16);
                        strResult.Append((char)charCode);
                    }
                }
                catch
                {
                    return Regex.Unescape(str);
                }
            }
            return strResult.ToString();
        }

        #endregion

        #region 数组字符串

        /// <summary>
        /// 把数组格式化为字符串 [1,2,3,4]
        /// </summary>
        /// <param name="val">数组</param>
        /// <returns>
        /// 格式 : 1,2,3,4
        /// </returns>
        public static string ArrayToString(string[] val)
        {
            if (val == null || val.Length == 0)
                return null;

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < val.Length; i++)
            {
                if (i != val.Length - 1)
                    sb.Append(string.Format("{0},", val[i].Trim()));
                else
                    sb.Append(val[i].Trim());
            }

            return sb.ToString();
        }

        /// <summary>
        /// 把数组格式化为字符串 [1,2,3,4]
        /// </summary>
        /// <param name="val">数组</param>
        /// <returns>
        /// 格式 : 1,2,3,4
        /// </returns>
        public static string ArrayToString(int[] val)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < val.Length; i++)
            {
                if (i != val.Length - 1)
                    sb.Append(string.Format("{0},", val[i]));
                else
                    sb.Append(val[i]);
            }

            return sb.ToString();
        }

        /// <summary>
        /// 把数组格式化为字符串 [1,2,3,4]
        /// </summary>
        /// <param name="val">数组</param>
        /// <param name="split">间隔符号</param>
        /// <returns>
        /// 格式 : 1,2,3,4
        /// </returns>
        public static string ArrayToString(string[] val, string split)
        {
            if (val == null || val.Length == 0)
                return null;

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < val.Length; i++)
            {
                if (i != val.Length - 1)
                    sb.Append(val[i].Trim() + split);
                else
                    sb.Append(val[i].Trim());
            }

            return sb.ToString();
        }

        /// <summary>
        /// 将字符串转换为数组
        /// </summary>
        /// <param name="str">eg: (1,2,3,4)</param>
        /// <returns></returns>
        public static int[] StringToArray(string str)
        {
            string[] ary = str.Split(',');
            int[] val = new int[ary.Length];

            for (int i = 0; i < ary.LongLength; i++)
            {
                val[i] = int.Parse(ary[i]);
            }

            return val;
        }
        /// <summary>
        /// 将字符串转换为List int eg: (1,2,3,4)
        /// </summary>
        /// <param name="str">eg: (1,2,3,4)</param>
        /// <returns></returns>
        public static List<int> StringToListInt(string str)
        {
            string[] ary = str.Split(',');
            List<int> val = new List<int>();

            for (int i = 0; i < ary.LongLength; i++)
            {
                val.Add(Convert.ToInt32(ary[i]));
            }
            return val;
        }
        /// <summary>
        /// 将字符串转换为List int
        /// </summary>
        /// <param name="str">eg: (1,2,3,4)</param>
        /// <returns></returns>
        public static List<string> StringToListString(string str)
        {
            string[] ary = str.Split(',');
            List<string> val = new List<string>();

            for (int i = 0; i < ary.LongLength; i++)
            {
                val.Add(ary[i]);
            }
            return val;
        }
        #endregion

        #region 验证码
        /// <summary>
        /// 生成随机验证码
        /// </summary>
        /// <param name="codeCount">验证码长度</param>
        /// <returns></returns>
        public static string CreateRandomCode(int codeCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9";
            string[] allCharArray = allChar.Split(',');
            string randomCode = "";
            int temp = -1;

            Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(10);
                if (temp == t)
                {
                    return CreateRandomCode(codeCount);
                }
                temp = t;
                randomCode += allCharArray[t];
            }
            return randomCode;
        }
        #endregion

        #region 文件类型相关
        /// <summary>
        /// 验证是否为视频文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static bool IsVideo(string fileName)
        {
            string fileExtension = Path.GetExtension(fileName).ToLower();
            string allFileExtension = @".drc,.dsm,.dsv,.dsa,.dss.vob,.ifo,.d2v,.flv,.fli,.flc,.flic,.ivf,.mkv,.mpg,.mpeg,.mpe,.m1v,.m2v,.mpv2,.mp2v,.dat,.ts,.tp .tpr,.pva,.pss,.mp4,.m4v,.m4p,.m4b,.3gp,.3gpp,.3g2,.3gp2,.ogm,.mov,.qt,.amr,.ratdvd,.rt,.rp,.smi,.smil,.rm,.ram,.rmvb,.rpm,.roq,.swf,.smk,.bik,.wmv,.wmp,.wm,.asf,.avi,.asx,.m3u,.pls,.wvx,.wax,.wmx,.mpcpl";
            return allFileExtension.Contains(fileExtension);
        }
        /// <summary>
        /// 验证是否为音频文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static bool IsVoice(string fileName)
        {
            string fileExtension = Path.GetExtension(fileName).ToLower();
            string allFileExtension = @".wav,.wma,.ra,.ogg,.mpc,.m4a,.aac,.mpa,.mp2,.m1a,.m2a,.mp3,.mid,.midi,.rmi,.mka,.ac3,.dts,.cda,.au,.snd,.aif,.aifc,.aiff ";
            return allFileExtension.Contains(fileExtension);
        }
        /// <summary>
        /// 验证是否为图片文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static bool IsImg(string fileName)
        {
            string fileExtension = Path.GetExtension(fileName).ToLower();
            string allFileExtension = @".bmp,.jpg,.png,.tiff,.gif,.pcx,.tga,.exif,.fpx,.svg,.psd,.cdr,.pcd,.dxf,.ufo,.eps,.ai,.raw,.WMF,webp";
            return allFileExtension.Contains(fileExtension);
        }
        #endregion

        #region Url获取Get参数
        /// <summary>
        /// 将查询字符串解析转换为名值集合.
        /// </summary>
        /// <param name="queryString"></param>
        /// <returns></returns>
        public static NameValueCollection GetQueryString(string queryString)
        {
            return GetQueryString(queryString, null, true);
        }

        /// <summary>
        /// 将查询字符串解析转换为名值集合.
        /// </summary>
        /// <param name="queryString"></param>
        /// <param name="encoding"></param>
        /// <param name="isEncoded"></param>
        /// <returns></returns>
        public static NameValueCollection GetQueryString(string queryString, Encoding encoding, bool isEncoded)
        {
            queryString = queryString.TrimStart('?');
            NameValueCollection result = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
            if (!string.IsNullOrEmpty(queryString))
            {
                int count = queryString.Length;
                for (int i = 0; i < count; i++)
                {
                    int startIndex = i;
                    int index = -1;
                    while (i < count)
                    {
                        char item = queryString[i];
                        if (item == '=')
                        {
                            if (index < 0)
                            {
                                index = i;
                            }
                        }
                        else if (item == '&')
                        {
                            break;
                        }
                        i++;
                    }
                    string key = null;
                    string value = null;
                    if (index >= 0)
                    {
                        key = queryString.Substring(startIndex, index - startIndex);
                        value = queryString.Substring(index + 1, (i - index) - 1);
                    }
                    else
                    {
                        key = queryString.Substring(startIndex, i - startIndex);
                    }
                    if (isEncoded)
                    {
                        result[MyUrlDeCode(key, encoding)] = MyUrlDeCode(value, encoding);
                    }
                    else
                    {
                        result[key] = value;
                    }
                    if ((i == (count - 1)) && (queryString[i] == '&'))
                    {
                        result[key] = string.Empty;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 解码URL.
        /// </summary>
        /// <param name="encoding">null为自动选择编码</param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string MyUrlDeCode(string str, Encoding encoding)
        {
            if (encoding == null)
            {
                Encoding utf8 = Encoding.UTF8;
                //首先用utf-8进行解码                     
                string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
                //将已经解码的字符再次进行编码.
                string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
                if (str == encode)
                    encoding = Encoding.UTF8;
                else
                    encoding = Encoding.GetEncoding("gb2312");
            }
            return HttpUtility.UrlDecode(str, encoding);
        }
        #endregion

        /// <summary>
        /// 26个数字转换为对应的26个字母
        /// </summary>
        /// <param name="NUM"></param>
        /// <returns></returns>
        public static string ReturnEnChar(int NUM)
        {
            string EnChar = "";
            switch (NUM)
            {
                case 1:
                    EnChar = "A";
                    break;
                case 2:
                    EnChar = "B";
                    break;
                case 3:
                    EnChar = "C";
                    break;
                case 4:
                    EnChar = "D";
                    break;
                case 5:
                    EnChar = "E";
                    break;
                case 6:
                    EnChar = "F";
                    break;
                case 7:
                    EnChar = "G";
                    break;
                case 8:
                    EnChar = "H";
                    break;
                case 9:
                    EnChar = "I";
                    break;
                case 10:
                    EnChar = "J";
                    break;
                case 11:
                    EnChar = "K";
                    break;
                case 12:
                    EnChar = "L";
                    break;
                case 13:
                    EnChar = "M";
                    break;
                case 14:
                    EnChar = "N";
                    break;
                case 15:
                    EnChar = "O";
                    break;
                case 16:
                    EnChar = "P";
                    break;
                case 17:
                    EnChar = "Q";
                    break;
                case 18:
                    EnChar = "R";
                    break;
                case 19:
                    EnChar = "S";
                    break;
                case 20:
                    EnChar = "T";
                    break;
                case 21:
                    EnChar = "U";
                    break;
                case 22:
                    EnChar = "V";
                    break;
                case 23:
                    EnChar = "W";
                    break;
                case 24:
                    EnChar = "X";
                    break;
                case 25:
                    EnChar = "Y";
                    break;
                case 26:
                    EnChar = "Z";
                    break;
            }

            return EnChar;
        }

        /// <summary>
        /// 获取文件内容
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static string GetFileContent(string filePath)
        {
            if (File.Exists(filePath))
            {
                string content = File.ReadAllText(filePath);
                return content;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 获取文件内容
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static string GetFileContent(string filePath, Encoding encoding)
        {
            if (File.Exists(filePath))
            {
                string content = File.ReadAllText(filePath, encoding);
                return content;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 替换索引出为“*”
        /// </summary>
        /// <param name="Input">输入字符串</param>
        /// <returns></returns>
        public static string GetStarString(string Input)
        {
            string Output = "";
            switch (Input.Length)
            {
                case 1:
                    Output = "*";
                    break;
                case 2:
                    Output = Input[0] + "*";
                    break;
                case 0:
                    Output = "";
                    break;
                default:
                    Output = Input.Substring(0, 1);
                    for (int i = 0; i < Input.Length - 2; i++)
                    {
                        Output += "*";
                    }
                    Output += Input.Substring(Input.Length - 1, 1);
                    break;
            }
            return Output;
        }

        /// <summary>
        /// 判断是否有中文
        /// </summary>
        /// <param name="inputStr"></param>
        /// <returns></returns>
        public static bool IsChinese(string inputStr)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(inputStr, @"^[\u4e00-\u9fa5]+$");
        }

        /// <summary>
        /// 去掉查询的不可见字符
        /// </summary>
        /// <param name="inputStr"></param>
        /// <returns></returns>
        public static string GetNDateStr(string inputStr)
        {
            string str = inputStr;
            if (str.Contains("\u200e") || str.Contains("年") || str.Contains("月") || str.Contains("日"))
            {
                str = str.Replace("\u200e", "").Replace("年", "-").Replace("月", "-").Replace("日", "");
            }
            return str;
        }
    }
}
