using System;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using CallCenter.Utility;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.Net.NetworkInformation;
using CallCenterApi.DB;
using System.Collections.Generic;

namespace CallCenterApi.Common
{
    public class CommonHelper
    {
        public static string EncryptAES(string data, string key)
        {
            return EncryptHelper.EncryptAES(data, key);
        }

        public static string DecryptAES(string data, string key)
        {
            return data + "" == "" ? "" : EncryptHelper.DecryptAES(data.Replace(" ", "+"), key);
        }

        /// <summary>
        /// MD5函数
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <returns>MD5结果</returns>
        public static string MD5(string str)
        {
            byte[] b = Encoding.UTF8.GetBytes(str);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
                ret += b[i].ToString("x").PadLeft(2, '0');

            return ret;
        }

        public static string escape(string value)
        {
            if (value == null) return "";
            return Microsoft.JScript.GlobalObject.escape(value);
        }

        public static string unescape(string value)
        {
            if (value == null) return "";
            return Microsoft.JScript.GlobalObject.unescape(value);
        }

        public static string toString(object value)
        {
            if (value == null)
            {
                return "";
            }
            else
            {
                return value.ToString();
            }
        }

        public static int ToInt32(object value)
        {
            string str = toString(value);
            int result = 0;
            if (int.TryParse(str, out result) == false)
            {
                result = 0;
            }
            return result;
        }

        public static long ToInt64(object value)
        {
            string str = toString(value);
            long result = 0;
            if (long.TryParse(str, out result) == false)
            {
                result = 0;
            }
            return result;
        }

        /// <summary>
        /// 是否登录
        /// </summary>
        /// <returns></returns>
        public static bool IsLogin(string Uid, string PassToken)
        {
            if (string.IsNullOrEmpty(Uid) || string.IsNullOrEmpty(PassToken) || Uid == "0" || PassToken == "0")
            {
                return false;
            }

            if (PassToken.Length <= 37)
            {
                return false;
            }
            string salt = PassToken.Substring(32);
            if (MD5(Uid + salt + "0fc7b78cfa1cb49f5d265e261dc70675") == PassToken.Substring(0, 32))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool IsLogin()
        {
            var uid = HttpContext.Current.Request["uid"];
            var PassToken = HttpContext.Current.Request["PassToken"];
            return CommonHelper.IsLogin(uid, PassToken);
        }

        public static string getSourceIP()
        {
            string SourceIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; /* 获得用户 IP 地址 */
            if (string.IsNullOrEmpty(SourceIP))
            {
                SourceIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; /* 兼容已有程序 */
            }
            if (SourceIP != null)
            {
                if (SourceIP.IndexOf(";") != -1)
                {
                    SourceIP = SourceIP.Split(';')[0];
                    if (SourceIP.IndexOf(",") != -1)
                    {
                        SourceIP = SourceIP.Split(',')[0];
                    }
                }
                SourceIP = SourceIP.Trim();
            }
            return SourceIP;
        }

        /// <summary>
        /// 字符串数组转十进制数组
        /// </summary>  
        /// <param name="strArray">字符串数组</param>
        /// <returns>十进制数组</returns>
        public static decimal[] ToDecimalArray(string[] strArray)
        {
            decimal[] decArray = new decimal[strArray.Length];
            for (int i = 0; i < strArray.Length; i++)
            {
                decArray[i] = Convert.ToDecimal(strArray[i]);
            }
            return decArray;
        }

        /// <summary>
        /// 全局静态随机数生成器
        /// </summary>
        public static Random ranNumber = new Random();


        public static string DirtyFilter(string text)
        {
            if (text == null) return "";
            string dirtyWords = "";
            if (HttpContext.Current.Cache["dirtywords"] == null)
            {
                string path = HttpContext.Current.Server.MapPath("/Txt/dirtywords.txt");
                if (System.IO.File.Exists(path)) dirtyWords = System.IO.File.ReadAllText(path, Encoding.UTF8);
                HttpContext.Current.Cache.Add("dirtywords", dirtyWords, null, DateTime.Now.AddDays(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
            }
            dirtyWords = HttpContext.Current.Cache["dirtywords"].ToString();
            dirtyWords = dirtyWords.Trim('\r', '\n', ' ');
            if (dirtyWords != "")
            {
                text = System.Text.RegularExpressions.Regex.Replace(text, dirtyWords, "*", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            }
            return text;
        }

        public static string DirtyFilterBroadCast(string text)
        {
            if (text == null) return "";
            string dirtyWords = "";
            string path = HttpContext.Current.Server.MapPath("/Txt/boradcast.txt");
            if (System.IO.File.Exists(path)) dirtyWords = System.IO.File.ReadAllText(path, Encoding.UTF8);
            if (dirtyWords != "")
            {
                text = System.Text.RegularExpressions.Regex.Replace(text, dirtyWords, "**", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            }
            return text;
        }
        /// <summary>
        /// GB2312转化为UTF-8
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] gb2312toutf8(string str)
        {
            Encoding utf8 = Encoding.GetEncoding("UTF-8");
            Encoding gb2312 = Encoding.GetEncoding("GB2312");
            byte[] gb = gb2312.GetBytes(str);
            gb = Encoding.Convert(gb2312, utf8, gb);
            //return utf8.GetString(gb);
            return gb;
        }
        /// <summary>
        /// UTF-8转化为GB2312
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static byte[] utf8togb2312(string text)
        {
            Encoding utf8 = Encoding.GetEncoding("UTF-8");
            Encoding gb2312 = Encoding.GetEncoding("GB2312");
            byte[] bs = utf8.GetBytes(text);
            bs = Encoding.Convert(utf8, gb2312, bs);
            //return gb2312.GetString(bs);
            return bs; 
        }

        private static string IP_Url = "http://iframe.ip138.com/ic.asp";
        private static string IP_Url2 = "http://www.ip.cn";
        /// <summary>
        /// 获取本机外网ip地址
        /// </summary>
        /// <returns></returns>
        public static string GetOuterNetIP()
        {
            string ip = "0.0.0.0";
            string html = GetSourceTextByUrl(IP_Url);
            Regex regex = new Regex(@"((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)");
            if (regex.Match(html).Success)
            {
                ip = regex.Match(html).Value;
            }
            else
            {
                html = GetSourceTextByUrl(IP_Url2);
                if (regex.Match(html).Success)
                {
                    ip = regex.Match(html).Value;
                }
            }
            return ip;
        }

        public static string GetSourceTextByUrl(string url)
        {
            try
            {
                Uri uri = new Uri(url);
                WebRequest webreq = WebRequest.Create(uri);
                Stream s = webreq.GetResponse().GetResponseStream();
                StreamReader sr = new StreamReader(s, System.Text.Encoding.Default);
                string all = sr.ReadToEnd();         //读取网站返回的数据  格式：您的IP地址是：[x.x.x.x] 
                int i = all.IndexOf("[") + 1;
                string tempip = all.Substring(i, 15);
                string ip = tempip.Replace("]", "").Replace(" ", "").Replace("<", "");     //去除杂项找出ip
                return ip;
                //WebRequest request = WebRequest.Create(url);
                //request.Timeout = 200000;//20秒超时
                //WebResponse response = request.GetResponse();

                //Stream resStream = response.GetResponseStream();
                //StreamReader sr = new StreamReader(resStream);
                //return sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public static bool FileIsExist(string url)
        {
            try
            {
                //创建根据网络地址的请求对象
                System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.CreateDefault(new Uri(url));
                httpWebRequest.Method = "HEAD";
                httpWebRequest.Timeout = 1000;
                //返回响应状态是否是成功比较的布尔值
                return (((System.Net.HttpWebResponse)httpWebRequest.GetResponse()).StatusCode == System.Net.HttpStatusCode.OK);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取签名
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string getsigncode(string controller, string action, string sign)
        {
            string signcode = EncryptHelper.MD5Encrypt(controller.ToLower() + "/" + action.ToLower() + "+" + EncryptHelper.SHA1Encrypt(sign + "+" + DateTime.Now.ToString("yyyyMMdd")));
            return signcode;
        }

        /// <summary>
        /// 判断IP是否被占用
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        public static bool PortInUse(int port)
        {
            bool inUse = false;

            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();

            foreach (IPEndPoint endPoint in ipEndPoints)
            {
                if (endPoint.Port == port)
                {
                    inUse = true;
                    break;
                }
            }

            return inUse;
        }


        /// <summary>
        ///   ///// 12345来源是110平台的工单结案时调用这个接口更新110的表的数据
        /// </summary>
        /// <param name="workorderid"></param>
        public static void pushresult(string workorderid)
        {
            string url = Configs.GetValue("PushAyResultUrl");
            //  string url = "http://localhost:51927/api/BusWorkorder/update";

            Model.T_Bus_WorkOrder oldmodel = new BLL.T_Bus_WorkOrder().GetModel(workorderid);

            //根据工单编号获取110的报警单编号
            string jjdbh = "";
            var objorderid = DbHelperSQL.GetSingle("select jjdbh from dy_jjdb where workorderId='" + workorderid + "'");
            if (objorderid != null)
            {
                jjdbh = objorderid.ToString();
            }
            else
            {

                return;
            }

            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("jjdbh", jjdbh);
            dic.Add("F_Result", oldmodel.F_Result);

            var result = Post(url, dic);

        }
        public static string Post(string url, Dictionary<string, object> dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }
    }
}
