using System;
using System.Linq;
using CSRedis;
using Siger.Middlelayer.Common.Configuration;

namespace Siger.Middlelayer.Redis.Repositories
{
    public abstract class RedisRepositoryBase
    {
        protected const string ZSetChangeToolsRecordName = "KM_ChangeToolsRecord_Config";
        protected const string HashParameterExceptionConfigName = "CNC_ParameterException_Config";

        protected const string HashMachineCycleUsage = "KM_MachineCycleUsage";
        protected const string HashMachineInfo = "CNC_EquipmentState";
        protected const string HashTrendTransfer = "KM_TrendTransfer";
        protected const string ZSetProgramlist = "JK_ProgramList";
        protected const string HashRatedLifeConfig = "KM_RatedLife_Config";
        protected const string HashMonitorTarget = "KM_monitorTargets";
        protected const string HashAlarmCondition = "Tool_AlarmCondition";
        protected const string HashBlxStnCache = "KM_BLXStn_CaChe";
        protected const string HashBlxCCTime = "KM_BLXCCTime_CaChe";
        protected const string HashPressureTemperature = "CNC_PressureTemperature"; //利达压铸,熔炉
        protected const string HashMouldConfig = "CNC_Mould_Config"; //模具编号配置
        protected const string HashMouldUsageData = "CNC_MouldUsage"; //模具使用寿命
        protected const string HashMachineMouldUsage = "CNC_MachineMouldUsage"; //设备下模具使用寿命
        protected const string HashToolMS = "KM_ToolMS";//磨损
        protected const string HashToolResiduallife = "TMS_Predicted_Tool_Residual_Life";//预测寿命
        protected const string HashToolLastProcessProgram = "TMS_Last_Process_Program";//最近一次加工程序号
        protected const string HashKMLampConfig = "KM_Lamp_Config"; // 报警客户端地址配置表
        protected const string HashAlarmRulesConfig = "CNC_AlarmRules_Config"; //非故障代码配置表
        protected const string HashTMSProcessLabeling = "TMS_Process_Labeling";//刀具标定
        protected const string HashTMSPLabelingResult = "TMS_Process_Labeling_Result";//刀具标定过程
        protected const string HashTMSToolSequence = "TMS_ToolSequence_Config";//刀具加工顺序排序模板
        protected const string TMSToolCycleSortConfig = "TMS_ToolCycleSort_Config";//刀具加工顺序排序
        protected const string HashTMSToolCCInitializeConfig = "JK_CCInitialize_Config";//刀具CC 数据切分
        protected const string HashQMSRatedTimeLifeConfig = "QMS_RatedTimeLife_Config"; //安灯监控配置表
        protected const string QMSParameterRuleKValueConfig = "QMS_ParameterRuleKValue_Config"; //质量判异规则配置表
        protected const string QMSParameterRuleConfig = "QMS_ParameterRule_Config"; //质量检验项目上限下限配置表
        protected const string QMSDefaultInfoConfig = "QMS_DefaultInfo_Config";//质量参数基础配置表
        protected const string QMSProductNameConfig = "QMS_ProductName_Config";//质量工位产品对应工序配置表
        protected const string QMSParameterMaintainConfig = "QMS_ParameterMaintain_Config";//质量检验项目参数关系表
        protected const string QMSParameterList = "QMS_ParameterList";//质量参数未配置表
        protected const string QMSYieldFixedConfig = "QMS_YieldFixed_Config";//产量固定配置表
        protected const string TlmToolData = "Tlm_ToolData";//刀具流转刀具状态
        protected const string ApiSuccessHash = "ApiSuccessCounts";
        protected const string ApiFailedHash = "ApiFailedCounts";

        //tool v1.5
        /// <summary>
        /// 报警通讯配置
        /// </summary>
        protected readonly string ToolSendMessageType = "Tool_SendMessageType";

        protected CSRedisClient Client;

        protected RedisRepositoryBase(int companyId, int projectId)
        {
            if (Client != null)
            {
                return;
            }
            var useOneDb = ConfigManager.GetValue("DbSetting", "UseOneDb", true);
            if (useOneDb)
            {
                ConnectSingleRedis(companyId, projectId);
            }
            else
            {
                ConnectClusterRedis();
            }
        }

        private void ConnectClusterRedis()
        {
            var redisHosts = ConfigManager.GetValue("DbClusterSetting", "RedisHost", "");
            if (!string.IsNullOrWhiteSpace(redisHosts))
            {
                var hosts = redisHosts.Split(';').ToArray();
                var connections = new string[hosts.Length];
                for (var i = 0; i < hosts.Length; i++)
                {
                    connections[i] = hosts[i];
                }
                Client = new CSRedisClient(null, connections);
            }
        }

        private void ConnectSingleRedis(int companyId, int projectId)
        {
            var dbConfig = RedisCache.Instance.GetDbName(companyId, projectId);
            if (dbConfig == null)
            {
                throw new Exception($"Get dbName by {companyId}_{projectId} failed.");
            }
            var connectionString = ConfigManager.GetValue("RedisSetting", "ConnectionString", string.Empty);
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new Exception("Redis connection string not found.");
            }

            try
            {
                var connectionStr = connectionString + $",poolsize=1,defaultDatabase={dbConfig.RedisDbName}";
                Client = new CSRedisClient(connectionStr);
            }
            catch (Exception e)
            {
                throw new Exception("connect redis failed:" + e.Message);
            }
        }
    }
}
