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, intervalNoticeErp = 5 * 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()
        {
            debugLog(" start to get job intervals...... ");
            using (ServiceReferenceScheduledService.ScheduledServiceClient client = new ServiceReferenceScheduledService.ScheduledServiceClient())
            {
                debugLog("  get job intervals as   ");
                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;
                    intervalNoticeErp = ins[4] > 0 ? ins[4] * 60000 : intervalNoticeErp;
                debugLog(string.Format("initialIntervals intervalOut:{0} intervalTest:{1} intervalDoc:{2} intervalStockLack:{3} intervalNoticeErp:{4}", intervalOut/60000, intervalTest / 60000, intervalDoc / 60000, intervalStockLack / 60000, intervalNoticeErp / 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 (intervalNoticeErp > 0 & timer2.Interval != intervalNoticeErp)
                {
                    debugLog(" new interal for i NoticeErp tasks . old is " + timer2.Interval / 60000 + " ,...............new interval = " + intervalNoticeErp / 60000);
                    timer2.Stop();
                    timer2.Interval = intervalNoticeErp;  
                    timer2.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(); 
                      
                    } 
                    */
                     
            }
            debugLog("  done.... get job intervals...... ");
        }
        protected override void OnStart(string[] args)
        { 
            
           // 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();
            
                    timer2.Interval = intervalNoticeErp; // 
                    timer2.Elapsed += new ElapsedEventHandler(this.OnTimer_2);
                    timer2.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();
            
            try
            {
             
                    debugLog("In OnStart.");
               
                    initialIntervals();
                
            }
            catch (Exception er)
            {
                debugLog(er.InnerException.ToString());
                log.Error(er);
            }
            
                   
        }
        /// 
        /// 停止服务
        /// 
        protected override void OnStop()
        {
           // eventLog1.WriteEntry("In OnStop.");
            debugLog("In OnStop.");
        }
        /// 
        /// 继续服务
        /// 
        protected override void OnContinue()
        {
            //eventLog1.WriteEntry("In OnContinue.");
            debugLog("In OnContinue.");
        }
        private void processOut()
        {
          
            using (ServiceReferenceScheduledService.ScheduledServiceClient client = new ServiceReferenceScheduledService.ScheduledServiceClient())
            {
                log.Debug(" to process out...");
                string result = client.processOut(outStatus);
                lastOut = DateTime.Now;
                log.Debug(result);
            }
        }
        bool isCanStart = true;
        int time1Cnt = 0;
        DateTime lastOut = DateTime.Now;
        // 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++;
               */
            debugLog("OnTimer_1 start process out ,,,\n,,,,,,,,,,,,,,,,,,,,,,,,/n,,,,,,,,,,,,,,,,,,,,>>> " + time1Cnt); log.Debug("");
            try
            {
                 processOut();
                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();
            try
            {
                using (ServiceReferenceScheduledService.ScheduledServiceClient client = new ServiceReferenceScheduledService.ScheduledServiceClient())
                {
                    debugLog("start notice erp process  ");
                    client.noticeErp();
                    debugLog("end notice erp ");
                }
            }
            catch (Exception er)
            {
                log.Error(er);
            }
            finally
            {
               
            }
            if (intervalNoticeErp > 0 & timer2.Interval != intervalNoticeErp)
            {
                debugLog(" new interal for NoticeErp tasks . old is" + timer2.Interval / 60000 + ",...............new interval = " + intervalNoticeErp / 60000);
                timer2.Interval = intervalNoticeErp; ;
            }
            timer2.Start();
            debugLog("OnTimer_2 end");
        }
        bool canTest = true;
        /// 
        /// 基本资料同步
        /// 
        /// 
        /// 
        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())
            {
                try
                {
                    if (canTest)
                    { 
                        canTest=false;
                        debugLog("start  test ...........");
                        client.truncateDataForTestOnly();
                        canTest = true;
                        debugLog("test done ..... enjoy! ");
                    }
                }
                catch (Exception er)
                {
                    log.Error(er);
                    canTest = true;
                }
            
            }
            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
            {
            } 
            /*
         if(lastOut.AddMilliseconds(intervalOut*5) < DateTime.Now)
            {
               // isCanStart = true;
             //   log.Debug(" force to process out...");
          
                try
                {
                    processOut();
                    isCanStart = true;
                }
                catch (Exception er)
                {
                    log.Error(er);
                }
                
            }
            
     
        if( lastOut.AddMilliseconds(intervalOut)< DateTime.Now)
            {
                timer1.Stop();
                timer1.Interval = intervalOut;
                timer1.Elapsed += new ElapsedEventHandler(this.OnTimer_1);
                timer1.Start();
                log.Debug("call timer1 to start....");
            }
         */
            timer6.Start();
            debugLog("OnTimer_6 end");
        }
        /// 
        /// 记录到指定路径:D:\log.txt
        /// 
        /// 
        private static void debugLog(string message)
        { 
       
            log.Debug(message);
          
        }
    }
}