using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Spring.Context;
using Spring.Context.Support;
using Spring.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using Service;
using Domain;
using RCUHost;
using Common;
using System.IO;
using Service.Implement;
using uPLibrary.Networking.M2Mqtt;
using System.Net;
using uPLibrary.Networking.M2Mqtt.Messages;
using FluentScheduler;
using CommonEntity;
using WebSite.Job;
using System.Collections.Concurrent;

namespace WebSite
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : SpringMvcApplication
    {
        private readonly string currentUrl = System.Configuration.ConfigurationManager.AppSettings["CurrentUrl"];
        private readonly string code = System.Configuration.ConfigurationManager.AppSettings["code"];//需要同步PMS房态的酒店编码，多个以英文逗号隔开
        private readonly string send_to_debugger = System.Configuration.ConfigurationManager.AppSettings["send_to_debugger"];

        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SpringMvcApplication));

        public static IApplicationContext cxt = ContextRegistry.GetContext();
        public static long UDPServerErrorCount = 0;
        private IHostManager HostManager;
        private ISysHotelManager SysHotelManager;
        private IRoomStatusManager RoomStatusManager;
        private IDeviceControlReceiver DeviceControlReceiver;
        private IOverviewManager OverviewManager { get; set; }
        public IHostModalManager HostModalManager { get; set; }

        public static IHostServer hostServer { get; set; }
        //private IGroupManager GroupManager;
        //private IHostRoomCardManager HostRoomCardManager;
        private syncstatus.syncstatusSoapClient _client = null;//房态同步接口
        //private ServiceReference2.ThirdpartyServiceClient _client1 = null;
        //private XR_PMS.XRHotel_ServiceSoapClient _xrClient = null;//西软pms接口
        private object _lock = new object(), _lock1 = new object();
        //private List<Host> _hosts = null;//西软pms对接使用

        public static int TimeInterval = 1;
        public static string IntervalKey = "TimeInterval";
        /// <summary>
        /// 凌晨ECO
        /// </summary>
        public static string LingChenECO_IntervalKey = "LingChenECO_IntervalKey";
        public static string LingChenECO_MissionSysKey = "LingChenECO_MissionSysKey";
        public static string UDPLostKey = "UDPLostKey";
        public static string UDPLostIntervalKey = "UDPLostIntervalKey";
        public static string BlockLowerMachineKey = "BlockLowerMachineKey";

        public static string ZeroX19_PassHotelCodeKey = "ZeroX19_PassHotelCode";

        public void PreHot()
        {
            int minWorkerThreads = 32;
            int minCompletionPortThreads = 32;

            // 设置最小线程数
            System.Threading.ThreadPool.SetMinThreads(minWorkerThreads, minCompletionPortThreads);

            // 预热线程池
            var countdown = new System.Threading.CountdownEvent(minWorkerThreads);
            for (int i = 0; i < minWorkerThreads; i++)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(_ =>
                {
                    System.Threading.Thread.Sleep(100); // 模拟一点工作
                    countdown.Signal();
                });
            }

            // 等待所有预热任务完成
            countdown.Wait();
        }
        protected override void Application_Start(object sender, EventArgs e)
        {
            logger.Error("Web重启了");
            // 在应用程序启动时调用
            PreHot();
            log4net.Config.XmlConfigurator.Configure();//初始化log4net
            // 全局异常捕获，避免未处理异常导致进程崩溃
            AppDomain.CurrentDomain.UnhandledException += (s, args) =>
            {
                try
                {
                    var ex = args.ExceptionObject as Exception;
                    if (ex != null)
                    {
                        logger.Error("UnhandledException:" + ex.Message);
                        logger.Error(ex.StackTrace);
                    }
                }
                catch { }
            };
            TaskScheduler.UnobservedTaskException += (s, args) =>
            {
                try
                {
                    logger.Error("UnobservedTaskException:" + args.Exception.ToString());
                    args.SetObserved();
                }
                catch { }
            };
            SetInitAccount();
            StartHostServer();
            //StartHostServerNew();
            BLWMQTT.StartMqtt();
            //if ("1" == send_to_debugger)
            //{
            //    UDPLogServer.Init();
            //    logger.Error("初始化debugger通讯");
            //}
            if (!string.IsNullOrEmpty(code))
            {
                StartTimer();
            }
            //HeartBeat();


            long ll1 = CSRedisCacheHelper.ForeverGet<long>(UDPLostKey);

            System.Threading.Interlocked.Exchange(ref DataTongJi.DefineLostPackage, ll1);
            System.Threading.Interlocked.Exchange(ref DataTongJi.RecordLostPackage, 0);

            int ll2 = CSRedisCacheHelper.ForeverGet<int>(UDPLostIntervalKey);
            if (ll2 != 0)
            {
                DataTongJi.LostPackage_Interval = ll2;
            }

            var ll3 = CSRedisCacheHelper.ForeverGet<List<string>>(ZeroX19_PassHotelCodeKey);
            if (ll3 != null)
            {
                DataTongJi.ZeroX19_PassHotelCode = new ConcurrentBag<string>(ll3);
            }

            var tq = CSRedisCacheHelper.ForeverGet<RedisTongJiData>(IntervalKey);
            if (tq == null)
            {
                RedisTongJiData tq1 = new RedisTongJiData();
                tq1.url = "api/CaiJiData";
                tq1.cron_exp = string.Format("*/{0} * * * *", 10);
                tq1.mission_key = MvcApplication.IntervalKey;
                CSRedisCacheHelper.Forever<RedisTongJiData>(IntervalKey, tq1);
            }

            var GGG = CSRedisCacheHelper.ForeverGet<ConcurrentDictionary<string, ConcurrentBag<string>>>(BlockLowerMachineKey);
            if (GGG != null)
            {
                DataTongJi.BlockLowerMachineList = GGG;
            }

            StartCPUTongJiTask();

            //RCUOnLineCheck();
            base.Application_Start(sender, e);
        }

        public static string WanBuJianKongSourceFileName = "Para_copy.yaml";
        public static string WanBuJianKongTargetFileName = "C:\\Program Files\\windows_exporter\\textfile_inputs\\Para.prom";
        public static string JianKong_TxtData { get; set; }

        public static System.Timers.Timer RCUOnLineTimer = null;
        public void RCUOnLineCheck()
        {
            RCUOnLineTimer = new System.Timers.Timer();
            RCUOnLineTimer.Interval = 30 * 1000;
            RCUOnLineTimer.Elapsed += new ElapsedEventHandler(OnLineCheck_Elapsed);
            RCUOnLineTimer.Start();
        }
        private void OnLineCheck_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                var Q = DataTongJi.ONLINERCU;
                var DT = DateTime.Now;
                var V = Q.Where(A =>
                    {
                        var DT_E = A.Value.CurrentDateTime;
                        TimeSpan timespan = DT - DT_E;
                        if (timespan.TotalSeconds > 120)
                        {
                            return true;
                        }
                        return false;
                    });
                foreach (var item in V)
                {
                    var IF = item.Key;
                    RCUOnLineExtra N;
                    Q.TryRemove(IF, out N);
                }
            }
            catch (Exception ex)
            {
                logger.Error("RCUOnLineCheck 数量统计出错了:" + ex.Message);
            }
        }


        #region CPU统计
        private void CPUtimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var T = sender as Timer;
            try
            {
                // 防止重入
                T.Stop();
                double d = CPUData.GetCPU();
                DataTongJi.CPU_Data.Add(d);
                // 简单的上限保护，避免长期积累导致内存膨胀
                //if (DataTongJi.CPU_Data.Count > 1000)
                //{
                //    DataTongJi.CPU_Data = new System.Collections.Concurrent.ConcurrentBag<double>();
                //}
            }
            catch (Exception ex)
            {
                logger.Error("CPU 数量统计出错了:" + ex.Message);
            }
            finally
            {
                // 恢复计时器
                T.Start();
            }
        }
        public static System.Timers.Timer CPUTimer = null;
        public void StartCPUTongJiTask()
        {
            try
            {
                CPUTimer = new System.Timers.Timer();
                CPUTimer.Elapsed += new ElapsedEventHandler(CPUtimer_Elapsed);
                //10分钟统计一次
                //现在修改成20秒： 
                //CPUTimer.Interval = 1 * 60 * 1000;
                CPUTimer.Interval = 1000;
                CPUTimer.Start();
            }
            catch (Exception ex)
            {
                logger.Error("StartTask Error:" + ex.Message);
            }
        }

        #endregion

        #region 数量统计

        #endregion


        public void HeartBeat()
        {
            try
            {
                Timer timer = new Timer();
                timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
                timer.Interval = 20000;
                timer.Start();
            }
            catch (Exception)
            {

            }
        }

        private void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                if (BLWMQTT.MqttClientGlobal.IsConnected)
                {
                    BLWMQTT.MqttClientGlobal.Publish("blw/mqtt/heartbeat", Encoding.UTF8.GetBytes("hello beat"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                }
                else
                {
                    BLWMQTT.StartMqtt();
                }
            }
            catch (Exception)
            {

            }
        }


        protected void Application_End(object sender, EventArgs e)
        {
            try
            {
                //hostServer.Close();
                //System.Threading.Thread.Sleep(5000);
                //System.Net.WebRequest request = System.Net.WebRequest.Create(currentUrl);
                //System.Net.WebResponse response = request.GetResponse();
                //logger.Error("系统重启Web服务");
                //response.Close();
            }
            catch (Exception ex)
            {
                logger.Error("重启原因为:" + ex.Message);
                logger.Error(ex.StackTrace);
            }

        }

        protected override void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute(
                "Index", // 路由名称
                "Index.html", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
            );
            routes.MapRoute(
                "LogOn", // 路由名称
                "LogOn", // 带有参数的 URL
                new { controller = "Home", action = "LogOn", id = UrlParameter.Optional } // 参数默认值
            );
            routes.MapRoute(
                "chuangwei_user_login", // Route name
                "sky/api/login", // URL with parameters
                new { controller = "api", action = "login" } // Parameter defaults
            );
            routes.MapRoute(
                "chuangwei_user_refreshToken", // Route name
                "sky/api/refreshToken", // URL with parameters
                new { controller = "api", action = "refreshToken" } // Parameter defaults
            );
            routes.MapRoute(
                 "chuangwei_device_control", // Route name
                 "sky/api/device/control", // URL with parameters
                 new { controller = "iot", action = "ChuangWei_DeviceCommandControl" } // Parameter defaults
             );
            routes.MapRoute(
                 "chuangwei_hotel_info", // Route name
                 "sky/api/hotel/info", // URL with parameters
                 new { controller = "iot", action = "ChuangWei_HotelInfo" } // Parameter defaults
             );
            routes.MapRoute(
                 "chuangwei_room_info", // Route name
                 "sky/api/room/info", // URL with parameters
                 new { controller = "iot", action = "ChuangWei_RoomInfo" } // Parameter defaults
             );
            routes.MapRoute(
                 "chuangwei_device_info", // Route name
                 "sky/api/device/info", // URL with parameters
                 new { controller = "iot", action = "ChuangWei_DeviceInfo" } // Parameter defaults
             );
            routes.MapRoute(
             "chuangwei_yijiantousu", // Route name
             "sky/api/customer/complaint", // URL with parameters
                 new { controller = "iot", action = "ChuangWei_TouSu" } // Parameter defaults
             );
            routes.MapRoute(
                 "API", // Route name
                 "sky/{controller}/{action}/{id}", // URL with parameters
                 new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
             );
            base.RegisterRoutes(routes);
        }
        /// <summary>
        /// 设置初始账号
        /// </summary>
        private void SetInitAccount()
        {
            //初始化默认酒店
            SysHotelManager = (ISysHotelManager)cxt.GetObject("Manager.SysHotel");
            var hotel = SysHotelManager.Get(1);
            if (null == hotel)
            {
                hotel = new SysHotel
                {
                    Code = "1001",
                    Name = "默认酒店",
                    EName = "Default Hotel",
                    TWName = "默認酒店",
                    Sort = 1,
                    ParentID = 0,
                    ActiveIndicator = true,
                    CreatedBy = "System",
                    CreatedDate = DateTime.Now,
                    ModifiedBy = "System",
                    ModifiedDate = DateTime.Now,
                    ValidateDate = Convert.ToDateTime("2037-12-31"),
                    SysHotelGroup = new SysHotelGroup { ID = 1, Parent = null, Name = "酒店", Sort = 1 }
                };
                SysHotelManager.Save(hotel);
            }
            //初始化默认酒店超级管理员角色
            ISysRoleManager roleManager = (ISysRoleManager)cxt.GetObject("Manager.SysRole");
            var role = roleManager.Get(1);
            if (null == role)
            {
                role = new SysRole
                {
                    Name = "Administrator",
                    Sort = 1,
                    ActiveIndicator = true,
                    CreatedBy = "System",
                    CreatedDate = DateTime.Now,
                    ModifiedBy = "System",
                    ModifiedDate = DateTime.Now,
                    HotelID = 1,
                    SysHotelGroup = new SysHotelGroup { ID = 1 },
                };
                roleManager.Save(role);
            }
            //初始化admin账号
            ISysUserManager manger = (ISysUserManager)cxt.GetObject("Manager.SysUser");
            const string account = "admin";
            var user = manger.Get(account);
            if (user == null)
            {
                IList<SysHotel> hotels = new List<SysHotel>();
                hotels.Add(SysHotelManager.Get(1));
                user = new SysUsers
                {
                    Account = account,
                    Name = account,
                    Role = new SysRole { ID = 1 },
                    Group = new Group { ID = 1 },
                    SysHotelGroup = new SysHotelGroup { ID = 1 },
                    Hotels = hotels,
                    HotelID = 1,
                    ActiveIndicator = true,
                    CreatedBy = "System",
                    CreatedDate = DateTime.Now,
                    ModifiedBy = "System",
                    ModifiedDate = DateTime.Now
                };
                manger.Save(user);
            }
        }

        private void StartHostServerNew()
        {
            hostServer = new RCUHost.Implement.HostServer();
            hostServer.AddReceiver(new RCUHost.Implement.HeartReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.HostSearchReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.RoomCardReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.UpdateHostReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.UpdateHostFTPReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.UploadCurrentVersionReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.SyncTimeReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.RoomStatusReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.HostSecretReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.WordsReportReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.HostRegisterReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.ExplainDomainIPReceiver());

            //阿宝添加的
            hostServer.AddReceiver(new RCUHost.Implement.TFTPReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.TFTPSettingReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.UpgradeProgressBar());
            hostServer.AddReceiver(new RCUHost.Implement.RoomStatusChangedReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.AskRoomStatusChangedReceiver());
            //hostServer.AddReceiver((IReceiver)new RCUHost.Implement.New_RoomStatusReceiver());
            hostServer.AddReceiver(new RCUHost.Implement.New_RoomStatusReceiver());

        }
        /// <summary>
        /// 创建 HostServer 以便与下位机通信
        /// </summary>
        public static void StartHostServer()
        {
            //创建 HostServer 
            hostServer = (IHostServer)cxt.GetObject("RCUHost.HostServer");
            //加载 Receiver, 只有加载对应的Receiver管理软件才能接收对应主机上报的命令
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.HeartReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.HostSearchReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.RoomCardReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.UpdateHostReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.UpdateHostFTPReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.UploadCurrentVersionReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.SyncTimeReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.RoomStatusReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.HostSecretReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.WordsReportReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.HostRegisterReceiver"));
            //hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.UpdateConfigReceiver"));
            //hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.UpdateRCUFileReceiver"));
            //hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.DeviceControlReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.ExplainDomainIPReceiver"));
            //阿宝添加的
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.TFTPReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.TFTPSettingReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.UpgradeProgressBar"));
            //hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.HotelTimeReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.RoomStatusChangedReceiver"));
            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.AskRoomStatusChangedReceiver"));

            hostServer.AddReceiver((IReceiver)cxt.GetObject("RCUHost.New_RoomStatusReceiver"));
        }

        /// <summary>
        /// 启动定时器
        /// </summary>
        private void StartTimer()
        {
            HostManager = (IHostManager)cxt.GetObject("Manager.Host");
            RoomStatusManager = (IRoomStatusManager)cxt.GetObject("Manager.RoomStatus");
            DeviceControlReceiver = (IDeviceControlReceiver)cxt.GetObject("RCUHost.DeviceControlReceiver");
            OverviewManager = (IOverviewManager)cxt.GetObject("Manager.Overview");
            HostModalManager = (IHostModalManager)cxt.GetObject("Manager.HostModal");
            _client = new syncstatus.syncstatusSoapClient();

            Timer timer2 = new Timer(20000);//每20秒扫描一次
            timer2.Elapsed += new ElapsedEventHandler(syncRoomStatusCallback);//定时同步PMS房态
            timer2.Enabled = true;
            timer2.AutoReset = true;
        }

        protected void Session_Start()
        {
            if (this.Request.UserLanguages == null || this.Request.UserLanguages.Length < 1 ||
                (!string.IsNullOrEmpty(this.Request.UserLanguages[0]) && this.Request.UserLanguages[0].ToLower().StartsWith("zh")))
            {
                this.Session["isCN"] = 0;
                HttpCookie isCNCookie = new HttpCookie("isCN");
                isCNCookie.Value = "zh-cn";
                isCNCookie.Expires = DateTime.Now.AddYears(1);
                Response.Cookies.Add(isCNCookie);
            }
        }

        protected void Session_End(object sender, EventArgs e)
        {
        }

        private void syncRoomStatusCallback(object sender, ElapsedEventArgs e)
        {
            try
            {
                RCUHost.TimingHelper.HostTimingControlHelper.HostTimingControl(DeviceControlReceiver);//定时控制
                DateTime now = DateTime.Now;
                if (now.Hour == 00 && now.Minute == 00 && now.Second < 20)
                {
                    //UploadHostAbnormalRecords();
                }
                DataSet dsHotel = _client.GetHotelCode();
                lock (_lock1)
                {
                    foreach (DataRow row in dsHotel.Tables[0].Rows)
                    {
                        if (Convert.ToInt16(row["HotelID"]) > 0)
                        {
                            DataSet ds = _client.GetCheckInOrOutRecord(row["Code"].ToString());
                            if (ds != null && ds.Tables.Count > 2 && ds.Tables[3].Rows.Count > 0)
                            {
                                int hotelID = Convert.ToInt16(ds.Tables[3].Rows[0]["HotelID"].ToString());//与PMS同步接口所配置的HotelID
                                if (hotelID > 0)
                                {
                                    foreach (DataRow dr in ds.Tables[0].Rows)
                                    {
                                        var q = RoomStatusManager.Get(2);
                                        SyncRoomStatus(hotelID, dr, q, 0);//更新出租房态
                                    }
                                    foreach (DataRow dr in ds.Tables[1].Rows)
                                    {
                                        var q = RoomStatusManager.Get(8);
                                        SyncRoomStatus(hotelID, dr, q, 1);//更新退房房态
                                    }
                                    foreach (DataRow dr in ds.Tables[2].Rows)
                                    {
                                        var q = RoomStatusManager.Get(4);
                                        SyncRoomStatus(hotelID, dr, q, 2);//更新待租房态
                                    }
                                }
                                //logger.Error(string.Format("酒店({0})已同步房态", row["Code"].ToString() + row["Remark"].ToString()));
                            }
                        }
                    }
                    #region 跟第三方同步（已注释）
                    /*try
                    {
                        //跟西软pms同步房态
                        if (_xrClient != null && _hosts != null && _hosts.Count > 0)
                        {
                            XmlDocument xmlXRRoomStatus = new XmlDocument();
                            xmlXRRoomStatus.LoadXml(_xrClient.Roomview("", "", ""));
                            XmlNodeList list = xmlXRRoomStatus.SelectSingleNode("interface").ChildNodes;
                            if (list.Count > 0)
                            {
                                List<string> lstRooms = new List<string>() { };
                                foreach (Host host in _hosts)
                                {
                                    foreach (XmlNode node in list)
                                    {
                                        if (node["roomno"] != null && node["roomno"].InnerText == host.RoomNumber)
                                        {
                                            int roomStatusID = 16;//空房
                                            switch (Convert.ToInt16(node["roomstate"].InnerText))
                                            {
                                                case 1://空净房
                                                    roomStatusID = 4;//待租
                                                    break;
                                                case 2://空脏房
                                                    roomStatusID = 8;//退房
                                                    break;
                                                case 3://住净房
                                                case 4://住脏房
                                                    roomStatusID = 2;//出租
                                                    break;
                                                //case 5://维修房
                                                //case 6://临时房态（酒店自定义）
                                            }
                                            if (host.RoomStatus.ID != roomStatusID)
                                            {
                                                HostManager.ChangeRoomStatus(host, RoomStatusManager.Get(roomStatusID));
                                                lstRooms.Add(host.RoomNumber);
                                            }
                                            break;
                                        }
                                    }
                                }
                                if (lstRooms.Count > 0)
                                {
                                    logger.Error(string.Format("本次酒店（1099珠海度假村千禧宫）同步西软pms客房房态有：{0}", string.Join(",", lstRooms)));
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error("本次酒店（1099珠海度假村千禧宫）同步西软pms客房房态失败。原因：" + ex.ToString());
                    }*/

                    //判断已插卡取电但尚未开房5分钟后，上报报警数据给金天鹅PMS
                    /*Group group = GroupManager.Load(21);
                    IList<Host> hosts = HostManager.LoadAll(group);
                    foreach (Host host in hosts)
                    {
                        IList<HostRoomCard> hostRoomCards = HostRoomCardManager.LoadAll(host.RoomNumber, "");
                        if (hostRoomCards != null && hostRoomCards.Count > 0)
                        {
                            XmlDocument xmlDoc = new XmlDocument();
                            xmlDoc.LoadXml(_client1.GethHotelcode("宝来客控对接酒店"));
                            XmlElement element = xmlDoc.DocumentElement;
                            string hotelCode = element.GetElementsByTagName("Body")[0].ChildNodes[0].ChildNodes[0].InnerText;//"HOTEL1489374686";
                            xmlDoc = new XmlDocument();
                            XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");//创建类型声明节点  
                            xmlDoc.AppendChild(node);
                            XmlNode root = xmlDoc.CreateElement("request");
                            xmlDoc.AppendChild(root);
                            XmlNode card = xmlDoc.CreateElement("Alarm");
                            root.AppendChild(card);
                            XmlNode data = xmlDoc.CreateNode(XmlNodeType.Element, "hotelCode", null);
                            data.InnerText = hotelCode;//酒店代码
                            card.AppendChild(data);
                            data = xmlDoc.CreateNode(XmlNodeType.Element, "roomno", null);
                            data.InnerText = host.RoomNumber;//房间号
                            card.AppendChild(data);
                            data = xmlDoc.CreateNode(XmlNodeType.Element, "remark", null);
                            data.InnerText = "";//备注
                            card.AppendChild(data);
                            data = xmlDoc.CreateNode(XmlNodeType.Element, "state", null);

                            HostRoomCard hostRoomCard = hostRoomCards[hostRoomCards.Count - 1];

                            if (host.RoomStatus.ID != 2 && host.RoomCard != null)
                            {
                                if ((hostRoomCard.IsAlarm == null || hostRoomCard.IsAlarm == false) &&
                                    Convert.ToDateTime(hostRoomCard.InCardTime).AddMinutes(5) <= DateTime.Now)
                                {
                                    data.InnerText = "1";//报警
                                    card.AppendChild(data);
                                    data = xmlDoc.CreateNode(XmlNodeType.Element, "key", null);
                                    data.InnerText = "Wide_Third";//授权码
                                    card.AppendChild(data);
                                    //string result = _client1.send(xmlDoc.InnerXml);
                                    logger.Error(xmlDoc.InnerXml);//result + Environment.NewLine + 

                                    hostRoomCard.IsAlarm = true;
                                    HostRoomCardManager.Update(hostRoomCard);
                                }
                            }
                            else if (hostRoomCard.IsAlarm == true)
                            {
                                data.InnerText = "0";//取消报警
                                card.AppendChild(data);
                                data = xmlDoc.CreateNode(XmlNodeType.Element, "key", null);
                                data.InnerText = "Wide_Third";//授权码
                                card.AppendChild(data);
                                //string result = _client1.send(xmlDoc.InnerXml);
                                logger.Error(xmlDoc.InnerXml);//result + Environment.NewLine + 

                                hostRoomCard.IsAlarm = false;
                                HostRoomCardManager.Update(hostRoomCard);
                            }
                        }
                    }*/
                    #endregion
                }
            }
            catch (Exception ex)
            {
                logger.Error("定时同步房态异常。原因：" + ex.ToString());
            }
        }
        /// <summary>
        /// 同步房态
        /// </summary>
        /// <param name="hotelID">酒店ID</param>
        /// <param name="dr"></param>
        /// <param name="roomStatus">房态</param>
        /// <param name="flag">更新字段标记</param>
        private void SyncRoomStatus(int hotelID, DataRow dr, RoomStatus roomStatus, int flag)
        {
            _client.UpdateCheckInOrOutRecord(dr["Code"].ToString(), Convert.ToInt64(dr["ID"]), flag);//更新已同步状态

            string RoomNUM = dr["RoomNumber"].ToString();
            var T = new Tuple<int, string, RoomStatus>(hotelID, RoomNUM, roomStatus);
            Task.Factory.StartNew((state) =>
            {
                var T1 = state as Tuple<int, string, RoomStatus>;
                Host host = HostManager.GetByRoomNumber(T1.Item2, T1.Item1);
                if (host != null)
                {
                    int status_id2 = host.SysHotel.SwitchRoomStatus_PowerOff2;
                    int status_id4 = host.SysHotel.SwitchRoomStatus_PowerOff4;
                    int status_id8 = host.SysHotel.SwitchRoomStatus_PowerOff8;
                    int status_id16 = host.SysHotel.SwitchRoomStatus_PowerOff16;
                    if (status_id2 != 0 || status_id4 != 0 || status_id8 != 0 || status_id16 != 0)
                    {
                        if (status_id2 == roomStatus.ID||status_id4==roomStatus.ID||status_id8==roomStatus.ID||status_id16==roomStatus.ID)
                        {
                            HostModal h1 = new HostModal();
                            h1.Modal = new RoomTypeModal() { ModalAddress = "004000001", Type = DeviceType.ServiceInfo };
                            HostModalManager.SetDevice(host, h1, 2, 0, 25, 0, 0, 0);
                        }
                    }
                    HostManager.ChangeRoomStatus(host, T1.Item3);
                    string Key = CacheKey.SyncRoomStatus + "_" + host.HostNumber;
                    RoomStatusRequest ddd = new RoomStatusRequest();
                    ddd.HostNumber = host.HostNumber;
                    ddd.MAC = host.MAC;
                    ddd.Status = T1.Item3;
                    CSRedisCacheHelper.Set_PartitionWithForever<RoomStatusRequest>(Key, ddd);
                }
            }, T);
        }
        /// <summary>
        /// 定时上报主机异常记录
        /// </summary>
        private void UploadHostAbnormalRecords()
        {
            Task.Factory.StartNew(() =>
            {
                List<SysHotel> lstHotels = SysHotelManager.LoadAll().Where(r => !string.IsNullOrEmpty(r.FaultPushURL)).ToList();// && r.FaultPushURL.ToLower().IndexOf("iot.sditcn.com") > -1).ToList();//PDU上报
                foreach (SysHotel hotel in lstHotels)
                {
                    for (int i = 1; i < 4; i++)
                    {
                        System.Data.DataTable dt = OverviewManager.LoadHostAbnormalRecords(i, hotel.ID);//三种异常类型
                        XuanZhuResponse resp;
                        foreach (System.Data.DataRow dr in dt.Rows)
                        {
                            resp = new XuanZhuResponse();
                            resp.code = hotel.Code;
                            resp.roomNumber = dr["RoomNumber"].ToString();
                            resp.address = "";
                            resp.name = dr["AbnormalName"].ToString();
                            resp.status = 2;
                            resp.faultType = 1;
                            resp.faultData = 1;
                            //XuanZhuOperation.ReportService(hotel.FaultPushURL, resp);

                            MyHttp.SendHttpData(hotel.FaultPushURL, resp);
                        }
                    }
                    logger.Error(string.Format("定时上报酒店({0})主机异常记录", hotel.Code));
                }
            }, System.Threading.CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
        }


        protected void Application_Error(object sender, EventArgs e)
        {
            try
            {
                Exception ex = Server.GetLastError();
                logger.Error("IIS:" + ex.Message);
                logger.Error(ex.StackTrace);

                // 清理可能导致循环异常的资源
                HttpContext.Current.ClearError();
            }
            catch (Exception ex)
            {
                logger.Error("IIS Exception:" + ex.Message);
            }
        }

        // 存储恶意IP和请求频率
        private static ConcurrentDictionary<string, RequestInfo> _ipRequests = new ConcurrentDictionary<string, RequestInfo>();
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            try
            {
                var ip = Request.UserHostAddress;
                var url = Request.Url.AbsolutePath.ToLower();

                // 定期清理恶意IP记录，避免字典无限增长
                var nowUtc = DateTime.UtcNow;
                CleanupIpRecordIfNeeded(nowUtc);

                // 定义要拦截的路径模式
                var maliciousPatterns = new[] 
                {
                    @".*\.git/*",
                    @"^/sdk",
                    @"^/HNAP1",
                    @"^/evox",
                    @"^/nmaplowercheck",
                    @"^/phpmyadmin",
                    @"^/admin",
                    @"^/wp-login",
                    @"^/shell",
                    @"^/cmd",
                    @".*\.php$",
                    @".*\.asp$",
                    @".*\.git/credentials"
                    //@".*\.aspx$"
                };

                // 检查是否为恶意路径
                if (maliciousPatterns.Any(pattern => System.Text.RegularExpressions.Regex.IsMatch(url, pattern)))
                {
                    LogMaliciousRequest(ip, url);
                    Response.StatusCode = 403;
                    //Response.End();
                    Context.ApplicationInstance.CompleteRequest();
                    return;
                }
            }
            catch (Exception ex)
            {
                logger.Error("恶意请求出错了:" + ex.Message);
            }
        }

        private void LogMaliciousRequest(string ip, string url)
        {
            logger.Error("恶意IP:" + ip + " URL:" + url);
        }

        private bool IsMaliciousRequestRate(string ip)
        {
            // 简单的频率检查逻辑
            var now = DateTime.UtcNow;
            var info = _ipRequests.GetOrAdd(ip, _ => new RequestInfo());

            lock (info)
            {
                info.RequestCount++;
                info.LastRequest = now;

                // 如果1分钟内超过100次请求，认为是恶意请求
                if (info.RequestCount > 100 && (now - info.FirstRequest).TotalMinutes < 1)
                {
                    return true;
                }
                // 超过统计窗口则重置计数窗口
                if ((now - info.FirstRequest).TotalMinutes >= 1)
                {
                    info.FirstRequest = now;
                    info.RequestCount = 1;
                }
            }
            return false;
        }

        // 恶意IP记录清理节流控制
        private static DateTime _lastIpCleanup = DateTime.MinValue;
        private static readonly TimeSpan _ipCleanupInterval = TimeSpan.FromMinutes(1);
        private static readonly TimeSpan _ipRetention = TimeSpan.FromMinutes(10);

        private static void CleanupIpRecordIfNeeded(DateTime nowUtc)
        {
            if ((nowUtc - _lastIpCleanup) < _ipCleanupInterval) return;
            _lastIpCleanup = nowUtc;
            try
            {
                foreach (var kv in _ipRequests.ToArray())
                {
                    var info = kv.Value;
                    if ((nowUtc - info.LastRequest) > _ipRetention)
                    {
                        RequestInfo removed;
                        _ipRequests.TryRemove(kv.Key, out removed);
                    }
                }
            }
            catch { }
        }

        private class RequestInfo
        {
            public RequestInfo()
            {
                this.FirstRequest = DateTime.UtcNow;
            }
            public int RequestCount { get; set; }
            public DateTime FirstRequest { get; set; }
            public DateTime LastRequest { get; set; }
        }

        /// <summary>
        /// 获取当前登录帐号
        /// </summary>
        /// <returns></returns>
        //private IList<WebSite.Models.ActiveUserModel> GetActiveUsers()
        //{
        //    var activeUsers = Application["ActiveUsers"] as List<WebSite.Models.ActiveUserModel>;
        //    if (activeUsers == null)
        //    {
        //        activeUsers = new List<WebSite.Models.ActiveUserModel>();
        //        Application["ActiveUsers"] = activeUsers;
        //    }
        //    return activeUsers;
        //}
    }




}