using LJLib.LocalLog;
using LJLib.Net.SPI.Server;
using LJLib.Tools.DEncrypt;
using LJLib.Tools.File;
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using JLHHJSvr.BLL;
using JLHHJSvr.Com;
using JLHHJSvr.Com.APP;
using JLHHJSvr.DBA;
using JLHHJSvr.Excutor;
using JLHHJSvr.Excutor.APP;
using JLHHJSvr.LJLib.HttpServer;

namespace JLHHJSvr
{
    public static class GlobalVar
    {
        private static ExcutorManager excutorManager = null;
        private static Timer _timer = null;
        private static object _syncRoot = new object();
        private static bool _initing = false;

        public static ILJServer server
        {
            get
            {
                return excutorManager;
            }
        }

        internal static void Init()
        {
            Trace.Listeners.Clear();
            Trace.Listeners.Add(new LocalTraceListener(new SyncLogger(new Logger(App_Data))));

            try
            {
                _timer = new Timer((state) =>
                {
                    lock (_syncRoot)
                    {
                        if (_initing)
                        {
                            return;
                        }
                        _initing = true;
                    }
                    try
                    {
                        if (_timer == null)
                        {
                            return;
                        }
                        // 获取数据库连接
                        string xmlfile = GlobalVar.XmlFile;
                        XmlConfig xmlconfig = new XmlConfig();
                        string connectionString = xmlconfig.GetXmlFileValue(xmlfile, string.Empty, "ConnectionString", string.Empty);

                        if (string.IsNullOrEmpty(connectionString))
                        {
                            Trace.Write("未设置数据库连接");
                        }
                        else
                        {
                            try
                            {
                                connectionString = DESEncrypt.Decrypt(connectionString, "4A61A8B51C3E42BCAE991F6C913A6A33");//DONE: 解密
                                GlobalVar.ConnectionString = connectionString;

                                // DONE: 更新数据库
                                var version = new ParkDbVersion();
                                version.CreateTables(GlobalVar.ConnectionString);

                                BllHelper.InitUser(GlobalVar.ConnectionString);

                                _timer.Dispose();
                                _timer = null;
                            }
                            catch (Exception ex)
                            {
                                Trace.Write(ex.ToString());
                                GlobalVar.ConnectionString = string.Empty;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.Write(ex.ToString());
                    }
                    finally
                    {
                        _initing = false;
                    }                   
                }, null, 0, 10000);

                

                // HTTP服务
                excutorManager = new ExcutorManager();
                // excutorManager.AddMap("HelloWord", typeof(HelloWordRequest), new HelloWordExcutor());
                excutorManager.AddMap("Login", typeof(LoginRequest), new LoginExcutor());//登陆
                excutorManager.AddMap("GetSysUserFileString", typeof(GetSysUserFileStringRequest), new GetSysUserFileStringExcutor());
                excutorManager.AddMap("SetSysUserFileString", typeof(SetSysUserFileStringRequest), new SetSysUserFileStringExcutor());

                excutorManager.AddMap("CommonDynamicSelect", typeof(CommonDynamicSelectRequest), new CommonDynamicSelectExcutor());

                excutorManager.AddMap("GetFileByMd5", typeof(GetFileByMd5Request), new GetFileByMd5Excutor());//根据md5获取文件
                excutorManager.AddMap("PostFile", typeof(PostFileRequest), new PostFileExcutor());//上传文件
                excutorManager.AddMap("GetUserList", typeof(GetUserListRequest), new GetUserListExcutor());//获取用户列表
                excutorManager.AddMap("SaveUserList", typeof(SaveUserListRequest), new SaveUserListExcutor());//保存用户列表
                excutorManager.AddMap("DelUserList", typeof(DelUserListRequest), new DelUserListExcutor());//删除用户列表
                excutorManager.AddMap("GetSysFuncPwr", typeof(GetSysFuncPwrRequest), new GetSysFuncPwrExcutor());//获取权限列表
                excutorManager.AddMap("GetDept", typeof(GetDeptRequest), new GetDeptExcutor());//获取部门列表
                excutorManager.AddMap("GetPriceList", typeof(GetPriceListRequest), new GetPriceListExcutor());//获取价格表列表

            }
            catch (Exception ex)
            {
                Trace.Write(ex.ToString());
            }
        }


        public static string ConnectionString { get; set; }

        public static string BinPath
        {
            get
            {
                return Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "");
            }
        }

        public static bool webapp { get; set; }
        public static string App_Data
        {
            get
            {
                string app_data = BinPath;
                if (webapp)
                {
                    app_data = Directory.GetParent(app_data).FullName + "\\App_Data";
                }
                if (!Directory.Exists(app_data))
                {
                    Directory.CreateDirectory(app_data);
                }
                return app_data;
            } 
        }

        public static string XmlFile
        {
            get
            {
                return App_Data + "\\config.xml";
            }
        }

        public static string App_Files
        {
            get
            {
                string app_files = App_Data + "\\App_Files";
                if (!Directory.Exists(app_files))
                {
                    Directory.CreateDirectory(app_files);
                }
                return app_files;
            }
        }
        public class ParkFileModel:IFileDBModel
        {
            public byte[] GetBytes(string md5)
            {
                if (!string.IsNullOrEmpty(md5))
                {
                    using (var con = new SqlConnection(ConnectionString))
                    using (var cmd = con.CreateCommand())
                    {
                        con.Open();
                        cmd.CommandText = @"SELECT filedata
                                                FROM   st_file
                                                WHERE  filemd5 = @filemd5 ";
                        cmd.Parameters.Clear();
                        cmd.Parameters.AddWithValue("@filemd5", md5);
                        using (var reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                return reader["fileData"] == DBNull.Value ? null : (byte[]) reader["fileData"];
                            }
                        }
                    }
                }
                return null;
            }
        }
    }
}