using RMYY_CallCenter_Api.QuartzWorker;
using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace RMYY_CallCenter_Api
{
    public class MvcApplication : System.Web.HttpApplication
    {
        private static RMYY_CallCenter_Api.QuartzWorker.QuartzWorker _worker;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            Task.Run(() =>
            {
                //IIS直接更新dll有可能end事件晚于start事件，因此延迟1分钟启动定时任务
                Task.Delay(TimeSpan.FromMinutes(1)).Wait();
                _worker = new RMYY_CallCenter_Api.QuartzWorker.QuartzWorker();
                _worker.AddWork(new PushWorkorder());
                _worker.Start();

            }).ContinueWith(p =>
            {
                System.Diagnostics.Debug.WriteLine(DateTime.Now);
            });
        }
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            SqlChecker SqlChecker = new SqlChecker(this.Request, this.Response);
            SqlChecker.Check();
            HttpApplication app = (HttpApplication)sender;
            var context = app.Context;
            if (context == null) throw new ArgumentNullException("context");

            Dictionary<string, string> Params = new Dictionary<string, string>();
            Params.Add("request_url", context.Request.Url.ToString());

            bool issafe = true;
            foreach (var key in context.Request.Params.AllKeys)
            {
                if (key == "ALL_HTTP")
                {
                    break;
                }
                Params.Add(key, context.Request.Params[key]);
                try
                {
                    string paras = context.Request.Params[key].ToString();
                    if (!paras.Contains("data:image/png;base64,"))
                    {
                        SqlFilter(paras);
                    }
                }
                catch
                {
                    issafe = false;
                    break;
                }
            }
            if (!issafe)
            {
                context.Response.Write(new AjaxResult { state = ResultTypes.error.ToString(), message = "非法输入！" }.ToJson());
                context.Response.End();
            }

            
        }

        /// <summary>
        /// 检查危险字符
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public static string SqlFilter(string sInput)
        {
            if (sInput == null || sInput == "")
                return null;
            string sInput1 = sInput.ToLower();
            string output = sInput;
            //去掉星号*
            //string pattern = @"and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|\*|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators";
            string pattern = @"and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators";
            if (Regex.Match(sInput1, @"\b(" + pattern + @")\b", RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)
            {
                throw new Exception("字符串中含有非法字符!");
            }
            else
            {
                output = output.Replace("'", "''");
            }
            return output;
        }


    }
}
