using CallCenter.QuartzService;
using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.Interface.Models.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Script.Serialization;
using System.Web.Security;

namespace CallCenterApi.Interface
{
    public class MvcApplication : System.Web.HttpApplication
    {
        private static QuartzWorker _worker;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            //clq 增加异常日志记录 自定义 HandleErrorAttribute
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            Task.Run(() =>
            {
                //IIS直接更新dll有可能end事件晚于start事件，因此延迟1分钟启动定时任务
                Task.Delay(TimeSpan.FromMinutes(1)).Wait();
                _worker = new CallCenter.QuartzService.QuartzWorker();
                _worker.AddWork(new SendMsg());             
                _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());

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

            //var log = LogFactory.GetLogger(this.GetType().ToString());

            var token = context.Request["token"];
            if (string.IsNullOrWhiteSpace(token))
            {
                //log.Debug(Params.ToJson());
                return;
            }
            try
            {
                ////获取缓存
                //var dict = CacheHelper.Get(token);
                //获取redis缓存
                var dict = RedisHelper.StringGet(token);

                if (dict == null)
                {
                    //log.Debug(Params.ToJson());
                    return;
                }
                Dictionary<string, string> userData = null;
                //获取FormsAuthenticationTicket对象
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);
                if (ticket != null && string.IsNullOrEmpty(ticket.UserData) == false)
                    userData = (new JavaScriptSerializer()).Deserialize<Dictionary<string, string>>(ticket.UserData); //还原用户数据
                if (ticket != null && userData != null)
                    context.User = new FormsPrincipal<Dictionary<string, string>>(ticket, userData);//重新给context.User赋值。

                //var obj = new { UserCode = userData["F_UserCode"], Params = Params };
                //log.Debug(Params.ToJson());

            }
            catch {
                /* 有异常也不要抛出，防止攻击者试探。 */
                //log.Debug(Params.ToJson());
            }
        }


    }
}
