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;
        /// <summary>
        /// L1业务后台-HTTP端口(HTTP协议)
        /// </summary>
        public static string ERP_API_URL { get; set; }
        /// <summary>
        /// L1业务后台-登录账套名
        /// </summary>
        public static string ERP_ACCOUNT_NAME { get; set; }
        /// <summary>
        /// L1业务后台-登录账号
        /// </summary>
        public static string ERP_ACCOUNT_USERNAME { get; set; }
        /// <summary>
        /// L1业务后台-登录密码
        /// </summary>
        public static string ERP_ACCOUNT_PASSWORD { get; set; }
        /// <summary>
        /// L1业务后台-Token
        /// </summary>
        public static string ERP_TOKEN { get; set; }

        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);

                        string L1Password = xmlconfig.GetXmlFileValue(xmlfile, string.Empty, "L1Password", "");
                        GlobalVar.ERP_ACCOUNT_NAME = xmlconfig.GetXmlFileValue(xmlfile, string.Empty, "L1Server", "");
                        GlobalVar.ERP_API_URL = xmlconfig.GetXmlFileValue(xmlfile, string.Empty, "L1API", "");
                        GlobalVar.ERP_ACCOUNT_USERNAME = xmlconfig.GetXmlFileValue(xmlfile, string.Empty, "L1Usercode", "");
                        GlobalVar.ERP_ACCOUNT_PASSWORD = DESEncrypt.Decrypt(L1Password, "4A61A8B51C3E42BCAE991F6C913A6A33");//DONE: 解密

                        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("ChangePassword", typeof(ChangePasswordRequest), new ChangePasswordExcutor());
                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("UnLockUser", typeof(UnLockUserRequest), new UnLockUserExcutor());//删除用户列表
                excutorManager.AddMap("GetSysFuncPwr", typeof(GetSysFuncPwrRequest), new GetSysFuncPwrExcutor());//获取权限列表
                excutorManager.AddMap("GetDept", typeof(GetDeptRequest), new GetDeptExcutor());//获取部门列表
                excutorManager.AddMap("GetPriceList", typeof(GetPriceListRequest), new GetPriceListExcutor());//获取价格表列表
                excutorManager.AddMap("AuditPriceList", typeof(AuditPriceListRequest), new AuditPriceListExcutor());//审核价格表列表
                excutorManager.AddMap("SaveDept", typeof(SaveDeptRequest), new SaveDeptExcutor());//保存部门
                excutorManager.AddMap("DeleteDept", typeof(DeleteDeptRequest), new DeleteDeptExcutor());//删除部门
                excutorManager.AddMap("AuditDept", typeof(AuditDeptRequest), new AuditDeptExcutor());//审核部门
                excutorManager.AddMap("SaveProfitrate", typeof(SaveProfitrateRequest), new SaveProfitrateExcutor());// 保存工厂利润率
                excutorManager.AddMap("SaveWorkmanship", typeof(SaveWorkmanshipRequest), new SaveWorkmanshipExcutor());// 保存工艺加点设置
                excutorManager.AddMap("DeleteWorkmanship", typeof(DeleteWorkmanshipRequest), new DeleteWorkmanshipExcutor());// 删除工艺加点设置
                excutorManager.AddMap("AuditWorkmanship", typeof(AuditWorkmanshipRequest), new AuditWorkmanshipExcutor());// 删除工艺加点设置
                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("GetMtrlDefList", typeof(GetMtrlDefListRequest), new GetMtrlDefListExcutor());// 获取物料资料
                excutorManager.AddMap("SaveMtrlDef", typeof(SaveMtrlDefRequest), new SaveMtrlDefExcutor());// 保存物料资料
                excutorManager.AddMap("DeleteMtrlDef", typeof(DeleteMtrlDefRequest), new DeleteMtrlDefExcutor());// 删除物料资料
                excutorManager.AddMap("BanMtrlDef", typeof(BanMtrlDefRequest), new BanMtrlDefExcutor());// 禁用物料资料
                excutorManager.AddMap("CopyMtrlDef", typeof(CopyMtrlDefRequest), new CopyMtrlDefExcutor());// 复制物料资料
                excutorManager.AddMap("ModifyMtrlDefList", typeof(ModifyMtrlDefListRequest), new ModifyMtrlDefListExcutor());// 复制物料资料
                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("GetMattressImportDW2", typeof(GetMattressImportDW2Request), new GetMattressImportDW2Excutor());// 下拉选择床垫类别
                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("GetMattressPackagMx", typeof(GetMattressPackagMxRequest), new GetMattressPackagMxExcutor());// 包装方式切换
                excutorManager.AddMap("GetMattressSubspecs", typeof(GetMattressSubspecsRequest), new GetMattressSubspecsExcutor());// 获取主副规格

                excutorManager.AddMap("SaveBedNet", typeof(SaveBedNetRequest), new SaveBedNetExcutor());// 保存床网报价
                excutorManager.AddMap("DeleteBedNet", typeof(DeleteBedNetRequest), new DeleteBedNetExcutor());// 删除床网报价
                excutorManager.AddMap("AuditBedNet", typeof(AuditBedNetRequest), new AuditBedNetExcutor());// 审核床网报价

                excutorManager.AddMap("GetComputeMattress", typeof(GetComputeMattressRequest), new GetComputeMattressExcutor());// 计算床垫报价
                excutorManager.AddMap("GetComputeBednet", typeof(GetComputeBednetRequest), new GetComputeBednetExcutor());// 计算床网报价
                excutorManager.AddMap("GetComputeSpring", typeof(GetComputeSpringRequest), new GetComputeSpringExcutor());// 计算弹簧数量
                excutorManager.AddMap("CopyMattressAudited", typeof(CopyMattressAuditedRequest), new CopyMattressAuditedExcutor());// 复制审核床垫报价
                excutorManager.AddMap("ReCalculateNoAudit", typeof(ReCalculateNoAuditRequest), new ReCalculateNoAuditExcutor());// 重算床垫报价
                excutorManager.AddMap("ReCalculateBedNetNoAudit", typeof(ReCalculateBedNetNoAuditRequest), new ReCalculateBedNetNoAuditExcutor());// 重算床网报价
                excutorManager.AddMap("ReCalculateERPCost", typeof(ReCalculateERPCostRequest), new ReCalculateERPCostExcutor());// 重算床网报价

                excutorManager.AddMap("MattressYWAudit", typeof(MattressYWAuditRequest), new MattressYWAuditExcutor());// 床垫接口业务审核撤审
                excutorManager.AddMap("MattressJSAudit", typeof(MattressJSAuditRequest), new MattressJSAuditExcutor());// 床垫接口产品补充审核撤审
                excutorManager.AddMap("MattressJS2Audit", typeof(MattressJS2AuditRequest), new MattressJS2AuditExcutor());// 床垫接口清单补充审核撤审

                excutorManager.AddMap("SaveMattressInterface", typeof(SaveMattressInterfaceRequest), new SaveMattressInterfaceExcutor());// 床垫接口清单补充审核撤审
                excutorManager.AddMap("RefreshMattressInterface", typeof(RefreshMattressInterfaceRequest), new RefreshMattressInterfaceExcutor());// 刷新床垫配置清单
                excutorManager.AddMap("RefreshMattressInterfaceQd", typeof(RefreshMattressInterfaceQdRequest), new RefreshMattressInterfaceQdExcutor());// 刷新床垫清单
                excutorManager.AddMap("CreatMtrldef", typeof(CreatMtrldefRequest), new CreatMtrldefExcutor());// 生成L1物料
                excutorManager.AddMap("UpdateMtrlPrice", typeof(UpdateMtrlPriceRequest), new UpdateMtrlPriceExcutor());// 更新L1计划价
                excutorManager.AddMap("DelMtrlPf", typeof(CreatMtrldefRequest), new DelMtrlPfExcutor());// 删除L1清单
                excutorManager.AddMap("CreatPrdPf", typeof(CreatPrdPfRequest), new CreatPrdPfExcutor());// 生成L1清单

                excutorManager.AddMap("GetERPMtrldefList", typeof(GetERPMtrldefListRequest), new GetERPMtrldefListExcutor());// 获取ERP物料资料
                excutorManager.AddMap("GetERPConfigureList", typeof(GetERPConfigureListRequest), new GetERPConfigureListExcutor());// 获取ERP配置资料
                excutorManager.AddMap("GetERPWrkGrpList", typeof(GetERPWrkGrpListRequest), new GetERPWrkGrpListExcutor());// 获取工组列表
                excutorManager.AddMap("GetERPMtrlTypeList", typeof(GetERPMtrlTypeListRequest), new GetERPMtrlTypeListExcutor());// 获取ERP物料类型
                excutorManager.AddMap("GetMattressInterfaceList", typeof(GetMattressInterfaceListRequest), new GetMattressInterfaceListExcutor());// 获取产品清单明细
                //excutorManager.AddMap("GetSemiFinishedMxList", typeof(GetSemiFinishedMxListRequest), new GetSemiFinishedMxListExcutor());// 获取产品清单明细

                //excutorManager.AddMap("ImportSpring", typeof(ImportSpringRequest), new ImportSpringExcutor());
                excutorManager.AddMap("SaveMattressExtra", typeof(SaveMattressExtraRequest), new SaveMattressExtraExcutor());// 保存床网分区定义
                excutorManager.AddMap("DeleteMattressExtra", typeof(DeleteMattressExtraRequest), new DeleteMattressExtraExcutor());// 删除床网分区定义
                excutorManager.AddMap("SaveMattressExtraType", typeof(SaveMattressExtraTypeRequest), new SaveMattressExtraTypeExcutor());// 保存床网分区类型
                excutorManager.AddMap("DeleteMattressExtraType", typeof(DeleteMattressExtraTypeRequest), new DeleteMattressExtraTypeExcutor());// 删除床网分区类型

                excutorManager.AddMap("GetFormulaVarList",typeof(GetFormulaVarListRequest),new GetFormulaVarListExcutor());
                excutorManager.AddMap("FormulaCheck", typeof(FormulaCheckRequest),new FormulaCheckExcutor());

                excutorManager.AddMap("JLH_FetchPrice", typeof(JLH_FetchPriceRequest), new JLH_FetchPriceExcutor());
                excutorManager.AddMap("GetResetWiptype", typeof(GetResetWiptypeRequest), new GetResetWiptypeExcutor());
                excutorManager.AddMap("ImportMtrlPriceByExcel", typeof(ImportMtrlPriceByExcelRequest), new ImportMtrlPriceByExcelExcutor()); //更新物料价格表单价
                excutorManager.AddMap("UpdateL1Basicinfo", typeof(UpdateL1BasicinfoRequest), new UpdateL1BasicinfoExcutor()); // 更新L1基础资料（物料、物料分类、工组）
            }
            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;
            }
        }
    }
}