using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using Core.Mes.ClientFrameWork;
using Core.Mes.IBaseInterface;
using System.Configuration;
using System.IO;

namespace Core.Mes.ServerListener
{
    public partial class MesServerListener : ServiceBase
    {
        public MesServerListener()
        {
            InitializeComponent();
        }
        private static System.Timers.Timer aTimer;

        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
            //this.EventLog.WriteEntry("Core.Mes.ServerListener服务启动成功", System.Diagnostics.EventLogEntryType.SuccessAudit);
            //step1:
            InitServer();
            CreateLogDirectory();
            


            //step2:
            aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
            aTimer.Interval = 1 * 60 * 1000;
            aTimer.Start();
            GC.KeepAlive(aTimer);


        }
        private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
        {
            //AppListenerLog("");
            //AppListenerLog("准备检查进程，Checking=" + Checking);
            if (Checking == false)
            {
                
                CheckServer();
            }

        }


        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
            aTimer.Stop();
            //this.EventLog.WriteEntry("Core.Mes.ServerListener服务关闭成功", System.Diagnostics.EventLogEntryType.SuccessAudit);
            //AppListenerLog("");
            //AppListenerLog("Core.Mes.ServerListener服务关闭成功");
            //AppListenerLog("");
        }


        #region

        /// <summary>
        /// 
        /// </summary>
        private void InitServer()
        {
            try
            {
                string url = ConfigurationManager.AppSettings["RemoteServerUrl"];
                ClientCommon._RemotingHelp.InitServerUrlList("ServerCommon", url);
       

            }
            catch(Exception ex)
            {
                
                this.EventLog.WriteEntry("监听程序启动失败，原因是初始化服务端发生错误："+ex.Message, System.Diagnostics.EventLogEntryType.Error);
                AppListenerLog("监听程序启动失败，原因是初始化服务端发生错误：" + ex.Message);
            }
        }

        private bool Checking = false;
        private void CheckServer()
        {

            Checking = true;
            CallingMessage temp_par = new CallingMessage();
            temp_par.ServerName = "ServerCommon";
            temp_par.ClassName = "Core.Mes.ServerCommon.UserInfoManager";
            temp_par.MethodName = "MesSystemListener";
            temp_par.args = null;

            temp_par.ServerType = MesServerType.IComponentContainServer;
            temp_par.TransType = NetWorkTransType.Remoting;
            temp_par.visitType = VisitType.Method;

            
  
            bool bMain = ClientCommon._RemotingHelp.ReConMainServer(temp_par);
            if (bMain == true)//连接返回True重启服务
            {
                string path = ConfigurationManager.AppSettings["ServerManager"];
                this.EventLog.WriteEntry("检测主进程应用服务失败，监听程序将重新开启主进程服务...", System.Diagnostics.EventLogEntryType.Error);
                AppListenerLog("检测主进程应用服务失败，监听程序将重新开启主进程服务...");
                try
                {
                    
                    Configuration configuration = ConfigurationManager.OpenExeConfiguration(path);
                    string ProcessId = configuration.AppSettings.Settings["MainProcessId"].Value;


                    try
                    {
                        int iProcessId = 0;
                        int.TryParse(ProcessId, out iProcessId);
                        Process process = Process.GetProcessById(iProcessId);
                        process.Kill();
                        string Directory = System.IO.Path.GetDirectoryName(path);
                        string FullName = System.IO.Path.GetFileName(path);
                        Process p = new Process();
                        p.StartInfo.WorkingDirectory = Directory;
                        p.StartInfo.FileName = FullName;
                        p.Start();
                        this.EventLog.WriteEntry("主进程服务开启成功", System.Diagnostics.EventLogEntryType.Information);
                        AppListenerLog("主进程服务开启成功");

                    }
                    catch
                    {
                        try
                        {

                            string Directory = System.IO.Path.GetDirectoryName(path);
                            string FullName = System.IO.Path.GetFileName(path);
                            Process p = new Process();
                            p.StartInfo.WorkingDirectory = Directory;
                            p.StartInfo.FileName = FullName;
                            p.Start();
                            this.EventLog.WriteEntry("主进程服务开启成功", System.Diagnostics.EventLogEntryType.Information);
                            AppListenerLog("主进程服务开启成功");
                        }
                        catch (Exception ex)
                        {

                            this.EventLog.WriteEntry("开启主进程服务失败，错误原因：" + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                            AppListenerLog("开启主进程服务失败，错误原因："+ ex.Message);

                        }

                    }
                    System.Threading.Thread.Sleep(10 * 1000);
                    
                }
                catch (ConfigurationErrorsException ex)
                {
                    AppListenerLog("读取主进程配置错误："+ex.Message+"\n 路径为：" + path);
                }
  
            }

            bool bChild = ClientCommon._RemotingHelp.ReConChildServer(temp_par);
            if (bChild == true)//连接返回True重启服务
            {
                string path = ConfigurationManager.AppSettings["ServerManager"];
                this.EventLog.WriteEntry("检测子进程应用服务失败，监听程序将重新开启子进程服务...", System.Diagnostics.EventLogEntryType.Error);
                AppListenerLog("检测子进程应用服务失败，监听程序将重新开启子进程服务...");
                try
                {
                    Configuration configuration = ConfigurationManager.OpenExeConfiguration(path);
                    string ProcessId = configuration.AppSettings.Settings["ChildProcessId"].Value;

                    try
                    {
                        int iProcessId = 0;
                        int.TryParse(ProcessId, out iProcessId);
                        Process process = Process.GetProcessById(iProcessId);
                        process.Kill();
                        string Directory = System.IO.Path.GetDirectoryName(path);
                        string FullName = System.IO.Path.GetFileName(path);
                        Process p = new Process();
                        p.StartInfo.WorkingDirectory = Directory;
                        p.StartInfo.FileName = FullName;
                        p.Start();
                        
                        this.EventLog.WriteEntry("子进程服务开启成功", System.Diagnostics.EventLogEntryType.Information);
                        AppListenerLog("子进程服务开启成功");
                    }
                    catch
                    {
                        try
                        {
                            string Directory = System.IO.Path.GetDirectoryName(path);
                            string FullName = System.IO.Path.GetFileName(path);
                            Process p = new Process();
                            p.StartInfo.WorkingDirectory = Directory;
                            p.StartInfo.FileName = FullName;
                            p.Start();
                            this.EventLog.WriteEntry("子进程服务开启成功", System.Diagnostics.EventLogEntryType.Information);
                            AppListenerLog("子进程服务开启成功");

                        }
                        catch (Exception ex)
                        {
                            this.EventLog.WriteEntry("开启子进程应用服务失败，错误原因：" + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                            AppListenerLog("开启子进程应用服务失败，错误原因："+ex.Message);
                        }

                    }
                    System.Threading.Thread.Sleep(10 * 1000);

                }

                catch (ConfigurationErrorsException ex)
                {
                    AppListenerLog("读取子进程配置错误："+ex.Message+" \n路径："+path );
                }  

            }
            //AppListenerLog("进程检查完毕");
            //AppListenerLog("");
            Checking = false;


        }
        #endregion

        #region 建立目录
        // 2012-9-7 add longjing
        private static string logpath = "";
        private  void CreateLogDirectory()
        {
            
            try
            {
                //logpath = ConfigurationManager.AppSettings["ServerListenerLogPath"];
                logpath = System.Environment.CurrentDirectory + "/log/AppListener/";

                if (!Directory.Exists(logpath))
                {
                    Directory.CreateDirectory(logpath);
                }
                //AppListenerLog("");
                //AppListenerLog("Core.Mes.ServerListener服务开启成功");
                //AppListenerLog("");
            }
            catch (ConfigurationErrorsException ex)
            {
                this.EventLog.WriteEntry("监听程序启动失败，原因是建立监听日志目录发生错误：" + ex.Message, System.Diagnostics.EventLogEntryType.Error);
               

            }

        }
        #endregion

        #region 监听日志 add longjing

        private static object lockObj = new object();

        public void AppListenerLog(string str)
        {
            //string path = string.Format("E:/maliang/CXMES/Client/log/AppListener/AppListenerLog_{0}.txt", System.DateTime.Now.ToString("yyyy_MM_dd"));
            try
            {
                string path = string.Format("{1}AppListenerLog_{0}.txt", System.DateTime.Now.ToString("yyyy_MM_dd"), logpath);
                if (!File.Exists(path))
                {
                    File.Create(path);
                }

                lock (lockObj)
                {


                    using (StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8))
                    {

                        StringBuilder sbtxt = new StringBuilder();


                        sbtxt.AppendLine(string.Format("{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                        sbtxt.AppendLine(str);
                        sbtxt.AppendLine("======================================================");
                        
                        sw.WriteLine(sbtxt.ToString());
                        
                        

                    }
                }
            }
            catch (Exception ex)
            {
                this.EventLog.WriteEntry("监听程序写日志时发生错误：" + ex.Message, System.Diagnostics.EventLogEntryType.Error);

            }
        }


        #endregion



        //#region 异常日志
        //public void AppListenerErrorLog(string str, string errmessage,string errpath)
        //{
        //    //string path = string.Format("E:/maliang/CXMES/Client/log/AppListener/AppListenerErrorLog_{0}.txt", System.DateTime.Now.ToString("yyyy_MM_dd"));
        //    try
        //    {
        //        string path = string.Format("{1}AppListenerLog_{0}.txt", System.DateTime.Now.ToString("yyyy_MM_dd"), logpath);
        //        if (!File.Exists(path))
        //        {
        //            File.Create(path);
        //        }
        //        lock (lockObj)
        //        {


        //            using (StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8))
        //            {

        //                StringBuilder sbtxt = new StringBuilder();
        //                sbtxt.AppendLine("======================================================");
        //                sbtxt.AppendLine(string.Format("{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
        //                sbtxt.AppendLine(str);
        //                sbtxt.AppendLine(errmessage);
        //                sbtxt.AppendLine(errpath);
        //                sbtxt.AppendLine("======================================================");
        //                sw.WriteLine(sbtxt.ToString());

        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        this.EventLog.WriteEntry("监听程序写异常日志时发生错误：" + ex.Message, System.Diagnostics.EventLogEntryType.Error);
        //    }
        //}

        //#endregion
    }
}
