using CSRedis;
using HealthMonitor.Model.Cache;
using HealthMonitor.Model.Config;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using TelpoDataService.Util;
using TelpoDataService.Util.Clients;
using TelpoDataService.Util.Entities.GpsCard;
using TelpoDataService.Util.Models;
using TelpoDataService.Util.QueryObjects;

namespace HealthMonitor.Service.Cache
{

    public class PersonCacheManager
    {

        //注意要改用 redis DB7 数据库 ,Prefix=TELPO
        private const string CACHE_HASH_KEY_GPSDEVICEPERSON = "#GPSDEVICE_PERSON_HASH";
        //注意要改用 redis DB7 数据库 ,Prefix=TELPO


        private readonly GpsCardAccessorClient<GpsPerson> _personApiClient;
        private readonly ILogger<PersonCacheManager> _logger;


        public PersonCacheManager(
            GpsCardAccessorClient<GpsPerson> personApiClient,
            ILogger<PersonCacheManager> logger)
        {
            _personApiClient = personApiClient;
            _logger = logger;
        }
        //public async Task<GpsPerson?> GetPersonBySerialNoAsync(string messageId, string sn)
        //{
        //    if (string.IsNullOrWhiteSpace(sn)) return null;
        //    // 切换redis DB7 数据库和前缀 "TELPO"


        //    // 增加容错,防止Redis宕机造成业务中断
        //    try
        //    {

        //        return await csRedisDb7.HGetAsync<GpsPerson>(CACHE_HASH_KEY_GPSDEVICEPERSON, sn);
        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.LogWarning($"Redis发生异常,将直接读取MySQL数据库,构造新实例:{ex.Message}, {ex.StackTrace}");
        //        var param = new GeneralParam
        //        {
        //            Filters = new List<QueryFilterCondition>
        //                {
        //                    new QueryFilterCondition
        //                    {
        //                        Key=nameof(GpsPerson.Serialno),
        //                        Value=sn,
        //                        ValueType=QueryValueTypeEnum.String,
        //                        Operator=QueryOperatorEnum.Equal
        //                    }
        //                }
        //        }!;
        //        return await _personApiClient.GetFirstAsync(param, new RequestHeader { RequestId = messageId }).ConfigureAwait(false);
        //    }
        //}

        /// <summary>
        /// 读取个人信息(血压使用)注意要改用 redis DB7
        /// </summary>
        /// <param name="messageId"></param>
        /// <param name="sn"></param>
        /// <returns></returns>
        public async Task<GpsDevicePerson?> GetDeviceGpsPersonCacheBySerialNoAsync(string messageId, string sn)
        {
            if (string.IsNullOrWhiteSpace(sn)) return null;


            // 增加容错,防止Redis宕机造成业务中断
            try
            {
                var person = await RedisHelperDb7.HGetAsync<GpsDevicePerson>(CACHE_HASH_KEY_GPSDEVICEPERSON, sn).ConfigureAwait(false);
                return person;
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"Redis发生异常,将直接读取MySQL数据库,构造新实例:{ex.Message}, {ex.StackTrace}");
                var param = new GeneralParam
                {
                    Filters = new List<QueryFilterCondition>
                        {
                            new QueryFilterCondition
                            {
                                Key=nameof(GpsPerson.Serialno),
                                Value=sn,
                                ValueType=QueryValueTypeEnum.String,
                                Operator=QueryOperatorEnum.Equal
                            }
                        }
                }!;
                var person = await _personApiClient.GetFirstAsync(param, new RequestHeader { RequestId = messageId }).ConfigureAwait(false);
                // 读取数据库,构造新实例
                return new GpsDevicePerson {
                    Time = DateTime.Now,
                    Person = new Person {
                        DeviceId = person.DeviceId,
                        PersonId = person.PersonId,
                        Remarks = person.Remarks,
                        SerialNo = person.Serialno
                    }
                };
            }


        }
        
        /// <summary>
        /// 获取gps_person缓存
        /// </summary>
        /// <param name="messageId"></param>
        /// <param name="sn"></param>
        /// <returns></returns>
        public async Task<JObject?> GetDeviceGpsPersonCacheObjectBySerialNoAsync(string messageId, string sn)
        {
            if (string.IsNullOrWhiteSpace(sn)) return null;

            try
            {
                var person = await RedisHelperDb7.HGetAsync(CACHE_HASH_KEY_GPSDEVICEPERSON, sn).ConfigureAwait(false);
                return (JObject?)JsonConvert.DeserializeObject(person);
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"Redis发生异常:{ex.Message}, {ex.StackTrace}");
               
            }

            return null;
        }
        /// <summary>
        /// 更新gps_person缓存
        /// </summary>
        /// <param name="person"></param>
        /// <param name="sn"></param>
        /// <returns></returns>
        public async Task<bool> UpdateDeviceGpsPersonCacheObjectBySerialNoAsync(JObject person, string sn)
        {
            var flag = false;
            if (string.IsNullOrWhiteSpace(sn)) return flag;
            try
            {
                // 覆盖 返回false
                 await RedisHelperDb7.HSetAsync(CACHE_HASH_KEY_GPSDEVICEPERSON, sn, person).ConfigureAwait(false);
                flag = true;
               
            }
            catch (Exception ex) 
            {
                _logger.LogWarning($"Redis发生异常:{ex.Message}, {ex.StackTrace}");
            }
            return flag;

        }
    }
}