using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Timers;
//using DeiNiu.Utils;
namespace WindowsServiceOut
{
    public partial class Service1 : ServiceBase
    {//记录到event log中,地址是 C:\Windows\System32\winevt\Logs (双击查看即可,文件名为MyNewLog)
        static log4net.ILog log = log4net.LogManager.GetLogger("jobSvr");
        private static string logdir = "c:\\wmsJobLog";
        private static EventLog eventLog1;
        private static int eventId = 1;
        private Timer timer1 = new Timer(), timer2 = new Timer(), timer3 = new Timer(),
            timerNewWorld = new Timer(),  timer6 = new Timer();
        private int intervalOut = 1 * 60000, intervalTest = 2 * 60000, intervalDoc = 3 * 60000, intervalStockLack = 3*60 * 60000;
        private WindowsServiceOut.ServiceReferenceScheduledService.enumOutStockRequestStatus
            outStatus = WindowsServiceOut.ServiceReferenceScheduledService.enumOutStockRequestStatus.准备分拣;
        public Service1()
        {
            InitializeComponent();
             /*
            eventLog1 = new System.Diagnostics.EventLog();
            if (!System.Diagnostics.EventLog.SourceExists("ServiceOutRequestSyncSource"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                    "ServiceOutRequestSyncSource", "ServiceOutRequestSyncLog");
            }
            eventLog1.Source = "ServiceOutRequestSyncSource";
            eventLog1.Log = "ServiceOutRequestSyncLog";
            */
        }
        void initialIntervals()
        {
            using (ServiceReferenceScheduledService.ScheduledServiceClient client = new ServiceReferenceScheduledService.ScheduledServiceClient())
            {
                
                    int[] ins = client.getJobInterVal();
                    intervalOut = ins[0] > 0 ? ins[0] * 60000 : intervalOut;
                    intervalTest = ins[1] > 0 ? ins[1] * 60000 : intervalTest;  
                    intervalDoc = ins[2] > 0 ? ins[2] * 60000 : intervalDoc;
                    intervalStockLack = ins[3] > 0 ? ins[3] * 60000 : intervalStockLack; 
                    debugLog(string.Format("initialIntervals intervalOut:{0} intervalTest:{1} intervalDoc:{2} intervalStockLack:{3}", intervalOut/60000, intervalTest / 60000, intervalDoc / 60000, intervalStockLack / 60000));
                   if(intervalOut > 0 & timer1.Interval!= intervalOut)
                    {
                        debugLog(" new interal for out tasks . old is " + timer1.Interval / 60000 + " ,...............new interval = " + intervalOut / 60000);
                        timer1.Stop();
                        timer1.Interval = intervalOut; ;
                        timer1.Start();
                    }
#if DEBUG
                    if (intervalTest > 0 & timerNewWorld.Interval != intervalTest)
                    {
                        debugLog(" new interal for test tasks . old is " + timerNewWorld.Interval / 60000 + " ...............new interval = " + intervalTest / 60000);
                        timerNewWorld.Stop();
                        timerNewWorld.Interval = intervalTest; ;
                        timerNewWorld.Start();
                    }
#endif
                    if (intervalDoc > 0 & timer3.Interval != intervalDoc)
                    {
                        debugLog(" new interal for dictionary tasks . old is " + timer3.Interval / 60000 + " ...............new interval = " + intervalDoc / 60000);
                        timer3.Stop();
                        timer3.Interval = intervalDoc; ;
                        timer3.Start();
                    }
              
                /*
                if (intervalStockLack > 0 & timer4.Interval != intervalStockLack)
                {
                    debugLog(" new interal for stock enumOutStockRequestStatus tasks . old is" + timer4.Interval / 60000 + ",...............new interval = " + intervalStockLack/60000);
                    timer4.Stop();
                    timer4.Interval = intervalStockLack; ;
                    timer4.Start(); 
                } 
                */
            }
        }
        void doFirstStartJobs()
        {
            timer1.Interval = 5000; 
            timer1.Elapsed += new ElapsedEventHandler(this.OnTimer_1);
            timer1.Start();
            timer3.Interval = 10000;  
            timer3.Elapsed += new ElapsedEventHandler(this.OnTimer_3);
            timer3.Start();
        }
        protected override void OnStart(string[] args)
        {
            try
            {
             
               debugLog("In OnStart.");
                   
               // doFirstStartJobs();
                initialIntervals();
                timer6.Interval = 0.5 * 60000; // 30秒检查一次wave interval 
                timer6.Elapsed += new ElapsedEventHandler(this.OnTimer_6);
                timer6.Start();
            }
            catch (Exception er)
            {
                debugLog(er.InnerException.ToString());
                log.Error(er);  
                
                log.Debug("get interval failed ,use default for time intervals, to start timers......");
                    timer1.Interval = intervalOut; // 1分执行一次
                    timer1.Elapsed += new ElapsedEventHandler(this.OnTimer_1);
                    timer1.Start();
                    timer3.Interval = intervalDoc; // 3分钟
                    timer3.Elapsed += new ElapsedEventHandler(this.OnTimer_3);
                    timer3.Start();
#if DEBUG
                    timerNewWorld.Interval = intervalTest;// 2 * 60000; //18 * 60 * 60000; // 18 小时
                    timerNewWorld.Elapsed += new ElapsedEventHandler(this.OnTimer_NewWorld);
                    timerNewWorld.Start();
#endif
                    timer6.Interval = 0.5 * 60000; // 30秒检查一次wave interval 
                    timer6.Elapsed += new ElapsedEventHandler(this.OnTimer_6);
                    timer6.Start();
            
            }
            
                   
        }
        /// 
        /// 停止服务
        /// 
        protected override void OnStop()
        {
           // eventLog1.WriteEntry("In OnStop.");
            debugLog("In OnStop.");
        }
        /// 
        /// 继续服务
        /// 
        protected override void OnContinue()
        {
            //eventLog1.WriteEntry("In OnContinue.");
            debugLog("In OnContinue.");
        }
        bool isCanStart = true;
        int time1Cnt = 0;
       
       // int normalPrcocessCnt = 0;
        /// 
        /// 出库相关任务处理
        /// 
        /// 
        /// 
        public void OnTimer_1(object sender, ElapsedEventArgs args)
        {
            time1Cnt++;
            debugLog("OnTimer_1 is bussy? " + !isCanStart);
            if (!isCanStart)
            {
                return;
            }
            isCanStart=false;
            
          
            timer1.Stop();
         /*
            if (normalPrcocessCnt > intervalStockLack/intervalOut)
            {
                outStatus = WindowsServiceOut.ServiceReferenceScheduledService.enumOutStockRequestStatus.库存不足;
                normalPrcocessCnt = 0; 
            }
            debugLog("outStatus: "+ outStatus);
            normalPrcocessCnt++;
            */
            using (ServiceReferenceScheduledService.ScheduledServiceClient client = new ServiceReferenceScheduledService.ScheduledServiceClient())
            { 
                debugLog("OnTimer_1 start process out ,,,\n,,,,,,,,,,,,,,,,,,,,,,,,/n,,,,,,,,,,,,,,,,,,,,>>> " + time1Cnt);log.Debug("");
                try
                {
                    string result= client.processOut(outStatus);
                    log.Debug(result);
                     isCanStart = true;
                }
                catch (Exception er)
                {
                    log.Error(er);
                }
                finally
                {
                    isCanStart = true;
                }
                outStatus = WindowsServiceOut.ServiceReferenceScheduledService.enumOutStockRequestStatus.准备分拣;
                log.Debug("");
                debugLog("OnTimer_1 end process out ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,<<< " + time1Cnt);
            }
            isCanStart = true;
            if (intervalOut > 0 & timer1.Interval != intervalOut)
            {
                debugLog(" new interal for out tasks . old is" + timer1.Interval / 60000 + ",...............new interval = " + intervalOut / 60000);
              
                timer1.Interval = intervalOut; ;
                
            }
            timer1.Start();
         
        }
        /// 
        /// 入库相关的任务
        /// 
        /// 
        /// 
        public void OnTimer_2(object sender, ElapsedEventArgs args)
        {
            // TODO: Insert monitoring activities here.
            //  eventLog1.WriteEntry("OnTimer_10", EventLogEntryType.Information, eventId++);
            debugLog("OnTimer_2 begin");
            timer2.Stop();
            using (ServiceReferenceScheduledService.ScheduledServiceClient client = new ServiceReferenceScheduledService.ScheduledServiceClient())
            {
                debugLog("start sync in requests ");
                client.syncInRequest();
                debugLog("end sync in requests ");
            }
            if (intervalTest > 0 & timer2.Interval != intervalTest)
            {
                debugLog(" new interal for stock in tasks . old is" + timer2.Interval / 60000 + ",...............new interval = " + intervalTest / 60000);
              
                timer2.Interval = intervalTest; ;
              
            }
            timer2.Start();
            debugLog("OnTimer_2 end");
        }
        /// 
        /// 基本资料同步
        /// 
        /// 
        /// 
        public void OnTimer_3(object sender, ElapsedEventArgs args)
        {
            // TODO: Insert monitoring activities here.
            //eventLog1.WriteEntry("OnTimer_60", EventLogEntryType.Information, eventId++);
            debugLog("OnTimer_3 begin");
            timer3.Stop();
            using (ServiceReferenceScheduledService.ScheduledServiceClient client = new ServiceReferenceScheduledService.ScheduledServiceClient())
            {
                try
                {
                    debugLog("start sync syncGoods ");
                    client.syncGoods();
                    debugLog("end sync syncGoods ");
                    debugLog("start sync syncNewOwners ");
                    client.syncNewOwners();
                    debugLog("end sync syncNewOwners ");
                    debugLog("start syncCustomer ");
                    client.syncCustomer();
                    debugLog("end  syncCustomer ");
                }
                catch (Exception er)
                {
                    debugLog("OnTimer_3  exception:" + er.Message + "/n" + er.StackTrace);
                }
            }
            if (intervalDoc > 0 & timer3.Interval != intervalDoc)
            {
                debugLog(" new interal for dictionary tasks . old is" + timer3.Interval / 60000 + ",...............new interval = " + intervalDoc / 60000);
                
                timer3.Interval = intervalDoc; ;
            
            }
           
            timer3.Start();
            debugLog("OnTimer_3 end");
        }
        public void OnTimer_NewWorld(object sender, ElapsedEventArgs args)
        {
#if DEBUG
            debugLog("OnTimer_NewWorld begin");
            timerNewWorld.Stop();
            using (ServiceReferenceScheduledService.ScheduledServiceClient client = new ServiceReferenceScheduledService.ScheduledServiceClient())
            {
                debugLog("start  test ...........");
                try
                {
                    client.truncateDataForTestOnly();
                } catch (Exception er)
                {
                    log.Error(er);
                }
                debugLog("test done ..... enjoy! ");
            }
            if (intervalTest> 0 & timerNewWorld.Interval != intervalTest)
            {
                debugLog(" new interal for test tasks . old is" + timerNewWorld.Interval / 60000 + ",...............new interval = " + intervalTest / 60000);
                timerNewWorld.Interval = intervalTest; ;
            }
            timerNewWorld.Start();
            debugLog("OnTimer_NewWorld end");
#endif
        }
        public void OnTimer_6(object sender, ElapsedEventArgs args)
        {
            debugLog("OnTimer_6 begin");
            timer6.Stop();
            try { initialIntervals(); }
            catch
            {
            } 
            timer6.Start();
            debugLog("OnTimer_6 end");
        }
        /// 
        /// 记录到指定路径:D:\log.txt
        /// 
        /// 
        private static void debugLog(string message)
        {//LogHelper.debug(typeof(Service1), message);
       
            log.Debug(message);
           /* try
            {
               // eventLog1.WriteEntry(message, EventLogEntryType.Information, eventId++);
              
                
                string logName = string.Format("{0}-{1}-{2}-{3}.txt", logdir + "\\jobLog",
                    DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day);
                using (FileStream stream = new FileStream(logName, FileMode.Append))
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.WriteLine(String.Format("{0}:{1}", DateTime.Now, message));
                }
               
            }
            catch (Exception er)
            {
              //  eventLog1.WriteEntry(er.Message, EventLogEntryType.Information, eventId++);
                log.Debug(er);
            }
              */
        }
    }
}