using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Redis.RedisEntities;
using Siger.Middlelayer.Redis.Utility;

namespace Siger.Middlelayer.Redis.Repositories
{
    public class RatedLifeConfigRepository : RedisRepositoryBase
    {
        private readonly bool _dispose;
        public RatedLifeConfigRepository(int companyId, int projectId, bool dispose = true) : base(companyId, projectId)
        {
            _dispose = dispose;
        }

        public void Dispose()
        {
            Client?.Dispose();
        }

       // public void AddRateLifeConfig(string programno, string subprogramno, int ratedlife, string name, int machineId, string spindleName)

        /// <summary>
        /// 同步刀具额定寿命表
        /// </summary>
        /// <param name="proceProgram">加工程序</param>
        /// <param name="ratedlife">额定寿命</param>
        /// <param name="name">刀具</param>
        /// <param name="machineId">设备</param>
        /// <param name="spindleName">主轴</param>
        /// <param name="ratio">寿命系数 默认：1</param>
        public void AddRateLifeConfig(string proceProgram, int ratedlife, string name, int machineId, string spindleName,int type,int toolId,double ratio)
        {
            var key = ConditionHelper.GetRateLifeKey(machineId, proceProgram, spindleName, name);
            var redisEntity = new RatedLifeConfig
            {
                MachineId = machineId,
                //ProgramNo = proceProgram,
                ProgramNo = ProcessProgramHelper.ReplaceProgram(proceProgram),
                RatedLife = ratedlife,
                SpindleName = spindleName,
                ToolName = name,
                Toolid=toolId,
                type= type,
                Ratio=ratio
                // SubProgramNo = string.IsNullOrWhiteSpace(subprogramno) ? "" : subprogramno,
            };
            try
            {
                Client.HSet(HashRatedLifeConfig, key, JsonHelper.SerializerToJsonString(redisEntity));
            }
            catch
            {
                throw;
            }
            finally
            {
                if (_dispose)
                {
                    Dispose();
                }
            }
        }

        public void DeleteRateLifeConfig(int machineId, string processProgramno, string spindleName, string toolName)
        {
            var key = ConditionHelper.GetRateLifeKey(machineId, processProgramno, spindleName, toolName);
            try
            {
                Client.HDel(HashRatedLifeConfig, key);
            }
            catch
            {
                throw;
            }
            finally
            {
                Client?.Dispose();
            }
        }
    }
}
