using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
namespace QMHTIS.HisService
{
    /// <summary>
    /// 服务管理
    /// </summary>
    public class ServiceManager
    {
        #region 成员变量

        private readonly bool _throwOnStart;//启动时出现异常是否抛出
        private readonly bool _throwOnStop;//停止时出现异常是否抛出
        private readonly bool _throwUnhandled;//停用时出现异常是否抛出
        NSC.Net.NetService.TCP.TCPNetServer _net = null;
        NSC.Service.ApplicationServiceEngine AppEngine = new NSC.Service.ApplicationServiceEngine();
        #endregion

        #region 启动服务

        public bool Start()
        {

            //设置动态库跟路径
            if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["BusinessDLLPath"]) == false)
            {
                NSC.Service.SystemServiceEngine.DllRootPath = ConfigurationManager.AppSettings["BusinessDLLPath"];
            }
            else
            {
                NSC.Service.SystemServiceEngine.DllRootPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                NSC.Service.ApplicationServiceEngine.DllRootPath = NSC.Service.SystemServiceEngine.DllRootPath;
            }

            Common.Config.ConfigSetting.InitSettings();
            Common.Applications.Verification.ClientVerification.Init();            

            //加载系统服务
            NSC.Service.SystemServiceEngine sse = new NSC.Service.SystemServiceEngine();
            sse.Load();
            
            //加载应用服务
            AppEngine.Load();

            _net = new NSC.Net.NetService.TCP.TCPNetServer();
            _net.EndPoint = new NET.RemoteEndPoint();
            _net.EndPoint.IP = System.Net.IPAddress.Any;
            if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["HtisPort"]) == false)
            {
                _net.EndPoint.Port = int.Parse(ConfigurationManager.AppSettings["HtisPort"]);
            }
            else
            {
                _net.EndPoint.Port = 9501;
            }
            _net.EndPoint.ConnectionLength = 100000;
            _net.EndPoint.ThreadLength = 1000;
            _net.EndPoint.Timeout = 15000;


            _net.VerifyClientBegin += new NSC.Net.NetService.TCP.TCPNetServer.OnVerifyClientBegin(net_VerifyClientBegin);
            _net.ApplicationServiceHandleBegin += new NSC.Net.NetService.TCP.TCPNetServer.OnApplicationServiceHandleBegin(_net_ApplicationServiceHandleBegin);
            _net.Start();
            //设置sap接口信息
            //SapInterface.SapInterfaceFactory.Config();
            //QMAPP.BLL.ExternalService.ServiceInvokeContext.AWMSServiceUrl = ConfigurationManager.AppSettings["AWMSServiceUrl"];
            Console.WriteLine("SERVICE STARTED!");
            WriteLogFile("SERVICE STARTED!");
            return true;
        }
        public void WriteLogFile(string logMessage)
        {
            string logfilepath = "C:\\";
            if (!Directory.Exists(logfilepath))
            {
                Directory.CreateDirectory(logfilepath);
            }
            logfilepath = logfilepath  + "log.txt";

            StreamWriter sw = new StreamWriter(@logfilepath, true);

            //sw.WriteLine("写日志:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo));
            sw.WriteLine(logMessage);
            sw.Flush();
            sw.Close();
        }
        NSC.NetServiceStruct _net_ApplicationServiceHandleBegin(NSC.NetServiceStruct data)
        {
            return AppEngine.ServiceHandler(Common.Data.UserAuthority.User, data, true);
        }

        #endregion

        #region 停止服务

        public bool Stop()
        {
            if (_net!=null)
                _net.Dispose();
            Console.WriteLine("服务停止!");

            Console.ReadLine();

            return true;
        }

        #endregion

        #region 暂停服务

        public bool Pause()
        {
            Console.WriteLine("服务暂停!");
            return true;
        }

        #endregion

        #region 继续服务

        public bool Continue()
        {
            Console.WriteLine("服务继续!");
            return true;
        }

        #endregion

        #region 验证客户端

        /// <summary>
        /// 验证客户端
        /// </summary>
        /// <param name="clientsn">客户端sn</param>
        /// <returns>用户权限级别</returns>
        Common.Data.UserAuthority net_VerifyClientBegin(string clientsn)
        {
            //客户端授权验证
            if (Common.Config.ConfigSetting.GetSetting("0000") == "Y")
            {
                return Common.Applications.Verification.ClientVerification.VerifyClient(clientsn);
            }
            else
            {
                return Common.Applications.Verification.ClientVerification.GetVerification(clientsn);
            }
        }

        #endregion
    }
}