using CallCenter.QuartzService;
using CallCenter.Utility;
using CallCenterApi.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);

            int port = Int32.Parse(Configs.GetValue("quartz_port"));
            string ISfiring = Configs.GetValue("ISfiring");
            Task.Run(() =>
            {
                //IIS直接更新dll有可能end事件晚于start事件，因此延迟1分钟启动定时任务
                Task.Delay(TimeSpan.FromMinutes(1)).Wait();
                if (!CommonHelper.PortInUse(port))
                {
                    _worker = new QuartzWorker(port);
                    _worker.AddWork(new PushWorkorder());
                   
                    if (ISfiring=="1")
                    {
                        _worker.AddWork(new ZhengWuDuiJie());
                      
                    }
                    else if (ISfiring == "2")
                    {
                        _worker.AddWork(new SatisfactionClose());
                    }

                    _worker.Start();
                }

            }).ContinueWith(p =>
            {
                //System.Diagnostics.Debug.WriteLine(DateTime.Now);
            });
        }

        protected void Application_End()
        {
            if (_worker != null)
            {
                _worker.Stop();
            }
        }


        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;


            if (app != null && app.Context != null)

            {

                //移除Server

                app.Context.Response.Headers.Remove("Server");

                //移除X-AspNetMvc-Version，和上面效果一样

                app.Context.Response.Headers.Remove("X-AspNetMvc-Version");

            }

            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,"))
                    {
                        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());
            if (Configs.GetValue("IsLog").ToString() == "1")
            {
                log.Debug(Params.ToJson());
            }
        }
    }
}
