using Core.Mes.IBaseInterface;
using System;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Timers;
using System.Collections;
using Core.Mes.ServerFrameWork;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace Core.Mes.ServerListener
{
    public class MesServerListener : ServiceBase
    {
        private static int HeartBeatTime = 6;

        private string _serverManager = "";
        public string ServerManager
        {
            get { return _serverManager; }
        }

        private static Thread _t = null;

        private ServerListenerStatus _status = ServerListenerStatus.Stop;
        public ServerListenerStatus Status
        {
            set
            {
                _status = value;
                if (_status == ServerListenerStatus.Start)
                {
                    StartListener();
                }
                else
                {
                    StopListener();
                }
            }
            get { return _status; }
        }

        private IServerPool obj = null;
        private IContainer components = null;
        private ServerConfigure _servConf = new ServerConfigure();

        private Hashtable _htServiceKeys = new Hashtable();
        public Hashtable HTServiceKeys
        {
            get { return _htServiceKeys; }
        }

        private Hashtable _htDispatcher = new Hashtable();
        public Hashtable HtDispatcher
        {
            get { return _htDispatcher; }
        }

        public MesServerListener()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            //Thread.Sleep(10000);
            Console.WriteLine("服务启动");
            Util.CreateLogDirectory();
            InitServer();

            try
            {
                string text = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["HeartBeatTime"].Value.ToString();
                HeartBeatTime = int.Parse(text);
            }
            catch
            {
                HeartBeatTime = 6;
            }

            StartListener();
        }

        private void StartListener()
        {
            if (_t == null)
            {
                _t = new Thread(CheckServer);
                _t.Name = "CORE.MES 监控服务";
                _t.Start();
            }
        }

        protected override void OnStop()
        {
            StopListener();
        }

        private void StopListener()
        {
            if (_t != null)
            {
                Util.AppListenerLog("停止监控服务...");
                try
                {
                    _t.Abort();
                    _t = null;
                }
                catch { }
            }
            Console.WriteLine("服务结束");
        }

        private void InitServer()
        {
            RemotingGate rg = new RemotingGate();

            string ServerURL = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["RemoteServerUrl"].Value.ToString().Trim();
            UriBuilder ub = new UriBuilder(ServerURL);
            ServerURL = string.Format("Tcp://{0}:{1}", ub.Host, ub.Port);

            obj = new IServerPool();
            obj.DBManagerList = null;
            obj.ServerName = "ServerListener";
            obj.AssemblyName = "";
            obj.HTServiceKeys = HTServiceKeys;
            obj.HtExtServer = null;
            obj.ServerConfig = null;
            obj.OwnObjects = new ArrayList() { this };

            obj.LoadClass(typeof(ServerListener), "");

            if (_htDispatcher.ContainsKey(obj.ServerName))
            {
                Dispatcher dp = (Dispatcher)(_htDispatcher[obj.ServerName]);
                RemotingServices.Disconnect(dp);
                dp.MemoryDispose();
                _htDispatcher.Remove(obj.ServerName);
            }

            Dispatcher myDisp = new Dispatcher(obj, new ServerConfigure(), new ArrayList() { this });
            _htDispatcher.Add(obj.ServerName, myDisp);

            RemotingServices.Marshal(myDisp, obj.ServerName);

            //Core.Mes.ServerFrameWork.IComponent module = (Core.Mes.ServerFrameWork.IComponent)Activator.CreateInstance(typeof(ServerListener));
        }

        private void CheckServer()
        {
            Util.AppListenerLog("启动监控服务...");
            int CheckTimes = 3;
            do
            {
                Thread.Sleep(HeartBeatTime * 1000);
                try
                {
                    DateTime dt = DateTime.Now;

                    CallingMessageEx par = new CallingMessageEx();
                    par.ServerName = "ServerCommon";
                    par.ClassName = "Core.Mes.ServerCommon.UserInfoManager";
                    par.MethodName = "CheckAlive";
                    par.args = new object[] { dt };

                    par.RedirectLimit = 0;
                    par.InnerServerRedirect = true;

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

                    string RemoteServerUrl = "";
                    try
                    {
                        RemoteServerUrl = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["RemoteServerUrl"].Value.ToString();
                    }
                    catch
                    {
                        throw new Exception("读取配置[RemoteServerUrl]失败!");
                    }

                    try
                    {
                        _serverManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["ServerManager"].Value.ToString();
                        _serverManager = Path.GetFullPath(ServerManager);
                    }
                    catch
                    {
                        throw new Exception("读取配置[ServerManager]失败!");
                    }

                    if (Util.ExistCoreMesServer(ServerManager, false) && CheckTimes > 0)
                    {
                        try
                        {
                            ICommon MasterChecker = (ICommon)Activator.GetObject(typeof(ICommon), RemoteServerUrl);
                            ReturnObjectEx rtn = MasterChecker.MethodHandlerEx(par, new ValidateInfo());
                            if (rtn.ErrCode == 1314 && rtn.RealObject != null && (DateTime)(((ArrayList)rtn.RealObject)[1]) == dt)
                            {
                                CheckTimes = 3;
                                continue;
                            }
                        }
                        catch { }
                        CheckTimes--;
                        continue;
                    }

                    CheckTimes = 3;
                    Util.AppListenerLog("检测主进程应用服务失败，监听程序将重新开启主进程服务...");

                    Util.ExistCoreMesServer(ServerManager, true);
                    Util.StartCoreMesServer(ServerManager, 3);
                }
                catch (Exception ex)
                {
                    Util.AppListenerLog("服务重新启动失败：" + ex.Message);
                }
            } while (true);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && components != null)
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            components = new Container();
            base.ServiceName = "Core.Mes.ServerListener";
        }
    }

}