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());//获取价格表列表
                excutorManager.AddMap("SaveDept", typeof(SaveDeptRequest), new SaveDeptExcutor());//保存部门
                excutorManager.AddMap("DeleteDept", typeof(DeleteDeptRequest), new DeleteDeptExcutor());//删除部门
                excutorManager.AddMap("SaveProfitrate", typeof(SaveProfitrateRequest), new SaveProfitrateExcutor());// 保存工厂利润率
                excutorManager.AddMap("SaveWorkmanship", typeof(SaveWorkmanshipRequest), new SaveWorkmanshipExcutor());// 保存工艺加点设置
                excutorManager.AddMap("DeleteWorkmanship", typeof(DeleteWorkmanshipRequest), new DeleteWorkmanshipExcutor());// 删除工艺加点设置
                excutorManager.AddMap("SaveBedNetType", typeof(SaveBedNetTypeRequest), new SaveBedNetTypeExcutor());// 保存床网类别定义
                excutorManager.AddMap("DeleteBedNetType", typeof(DeleteBedNetTypeRequest), new DeleteBedNetTypeExcutor());// 删除床网类别定义
                excutorManager.AddMap("SaveMattressType", typeof(SaveMattressTypeRequest), new SaveMattressTypeExcutor());// 保存床垫类别定义
                excutorManager.AddMap("DeleteMattressType", typeof(DeleteMattressTypeRequest), new DeleteMattressTypeExcutor());// 删除床垫类别定义
                excutorManager.AddMap("SaveMattressFormula", typeof(SaveMattressFormulaRequest), new SaveMattressFormulaExcutor());// 保存床垫公式定义
                excutorManager.AddMap("DeleteMattressFormula", typeof(DeleteMattressFormulaRequest), new DeleteMattressFormulaExcutor());// 删除床垫公式定义
                excutorManager.AddMap("SaveShrinkage", typeof(SaveShrinkageRequest), new SaveShrinkageExcutor());// 保存裥棉收缩率
                excutorManager.AddMap("DeleteShrinkage", typeof(DeleteShrinkageRequest), new DeleteShrinkageExcutor());// 删除裥棉收缩率
                excutorManager.AddMap("SaveSpring", typeof(SaveSpringRequest), new SaveSpringExcutor());// 保存弹簧资料
                excutorManager.AddMap("DeleteSpring", typeof(DeleteSpringRequest), new DeleteSpringExcutor());// 删除弹簧资料
                excutorManager.AddMap("AuditSpring", typeof(AuditSpringRequest), new AuditSpringExcutor());// 审核弹簧资料
                excutorManager.AddMap("GetBedNetVarList", typeof(GetBedNetVarListRequest), new GetBedNetVarListExcutor());// 获取物料类型
                excutorManager.AddMap("SaveBedNetVar", typeof(SaveBedNetVarRequest), new SaveBedNetVarExcutor());// 保存床网/床垫变量定义
                excutorManager.AddMap("DeleteBedNetVar", typeof(DeleteBedNetVarRequest), new DeleteBedNetVarExcutor());// 删除床网/床垫变量定义
                excutorManager.AddMap("GetMtrlTypeList", typeof(GetMtrlTypeListRequest), new GetMtrlTypeListExcutor());// 获取物料类型
                excutorManager.AddMap("SaveMtrlType", typeof(SaveMtrlTypeRequest), new SaveMtrlTypeExcutor());// 获取物料类型
                excutorManager.AddMap("DeleteMtrlType", typeof(DeleteMtrlTypeRequest), new DeleteMtrlTypeExcutor());// 获取物料类型
                excutorManager.AddMap("SaveMtrlDef", typeof(SaveMtrlDefRequest), new SaveMtrlDefExcutor());// 获取物料资料
                excutorManager.AddMap("DeleteMtrlDef", typeof(DeleteMtrlDefRequest), new DeleteMtrlDefExcutor());// 删除物料资料
                excutorManager.AddMap("BanMtrlDef", typeof(BanMtrlDefRequest), new BanMtrlDefExcutor());// 禁用物料资料
                excutorManager.AddMap("GetFormulaCompute", typeof(GetFormulaComputeRequest), new GetFormulaComputeExcutor());// 公式计算
                excutorManager.AddMap("SaveMultiPrice", typeof(SaveMultiPriceRequest), new SaveMultiPriceExcutor());// 保存多维度定价
                excutorManager.AddMap("DeleteMultiPrice", typeof(DeleteMultiPriceRequest), new DeleteMultiPriceExcutor());// 删除多维度定价
                excutorManager.AddMap("BanMultiPrice", typeof(BanMultiPriceRequest), new BanMultiPriceExcutor());// 禁用多维度定价
                excutorManager.AddMap("SaveBedNetArea", typeof(SaveBedNetAreaRequest), new SaveBedNetAreaExcutor());// 保存床网分区定义
                excutorManager.AddMap("DeleteBedNetArea", typeof(DeleteBedNetAreaRequest), new DeleteBedNetAreaExcutor());// 删除床网分区定义
                excutorManager.AddMap("SaveConfigureType", typeof(SaveConfigureTypeRequest), new SaveConfigureTypeExcutor());// 保存部件选配类型
                excutorManager.AddMap("DeleteConfigureType", typeof(DeleteConfigureTypeRequest), new DeleteConfigureTypeExcutor());// 删除部件选配类型
                excutorManager.AddMap("SaveConfigureCode", typeof(SaveConfigureCodeRequest), new SaveConfigureCodeExcutor());// 保存部件选配项
                excutorManager.AddMap("DeleteConfigureCode", typeof(DeleteConfigureCodeRequest), new DeleteConfigureCodeExcutor());// 删除部件选配项
                excutorManager.AddMap("SaveConfigureCodeMx", typeof(SaveConfigureCodeMxRequest), new SaveConfigureCodeMxExcutor());// 保存部件选配项值
                excutorManager.AddMap("DeleteConfigureCodeMx", typeof(DeleteConfigureCodeMxRequest), new DeleteConfigureCodeMxExcutor());// 删除部件选配项值
                excutorManager.AddMap("SaveMattress", typeof(SaveMattressRequest), new SaveMattressExcutor());// 保存床垫报价
                excutorManager.AddMap("SaveMattressAuditing", typeof(SaveMattressAuditingRequest), new SaveMattressAuditingExcutor());// 床垫报价:业务下单/取消
                excutorManager.AddMap("DelMattress", typeof(DelMattressRequest), new DelMattressExcutor());// 床垫报价:删除
                excutorManager.AddMap("SaveMattressBcp", typeof(SaveMattressBcpRequest), new SaveMattressBcpExcutor());// 保存半成品报价
                excutorManager.AddMap("DeleteMattressBcp", typeof(DeleteMattressBcpRequest), new DeleteMattressBcpExcutor());// 删除半成品报价
                excutorManager.AddMap("AuditMattressBcp", typeof(AuditMattressBcpRequest), new AuditMattressBcpExcutor());// 审核半成品报价

                excutorManager.AddMap("SaveBedNet", typeof(SaveBedNetRequest), new SaveBedNetExcutor());// 保存床网报价
                excutorManager.AddMap("DeleteBedNet", typeof(DeleteBedNetRequest), new DeleteBedNetExcutor());// 删除床网报价
                excutorManager.AddMap("AuditBedNet", typeof(AuditBedNetRequest), new AuditBedNetExcutor());// 审核床网报价
            }
            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;
            }
        }
    }
}