using System.Reflection.Metadata;
using SJZY.Track.Domain.Consts;
using SJZY.Track.Domain.Dtos.Common;
using SJZY.Track.Domain.Queries;
using SJZY.Track.Domain.VEntities;
namespace SJZY.Track.Repository.Queries;
public class TimezoneQueries:ITimezoneQueries, ISugarRepository, ITransientDependency
{
public ISqlSugarClient Context { get; set; }
public TimezoneQueries()
{
Context = SqlsugarScopeBasic.GetContextSafely("default");
}
private string GetCityKey(string cityEnName)
{
return $"{GlobalConst.CityTimezoneKeyPrefix}:{cityEnName}";
}
private string GetPortKey(string airCode)
{
return $"{GlobalConst.PortTimezoneKeyPrefix}:{airCode}";
}
///
/// 获取城市时区
///
/// 城市英文名称
/// 时区
public async Task GetCityTimezone(string cityEnName)
{
var key =GetCityKey(cityEnName);
var timezone = RedisHelper.Client.Get(key);
if (!string.IsNullOrEmpty(timezone))
{
return timezone;
}
var cityTimezone = await GetTimezoneByCityName(cityEnName);
if (cityTimezone == null!)
{
await RedisHelper.Client.SetAsync(key, string.Empty, TimeSpan.FromSeconds(20));
return string.Empty;
}
await RedisHelper.Client.SetAsync(key, cityTimezone.Timezone, TimeSpan.FromHours(6));
return cityTimezone.Timezone;
}
///
/// 获取港口时区
///
/// 港口三字码
/// 时区
public async Task GetPortTimezone(string airCode)
{
var key = GetPortKey(airCode);
var timezone = RedisHelper.Client.Get(key);
if (!string.IsNullOrEmpty(timezone))
{
return timezone;
}
var portTimezone = await GetTimezoneByPortCode(airCode);
if (portTimezone == null!)
{
await RedisHelper.Client.SetAsync(key, string.Empty, TimeSpan.FromSeconds(20));
return string.Empty;
}
await RedisHelper.Client.SetAsync(key, portTimezone.Timezone, TimeSpan.FromHours(6));
return portTimezone.Timezone;
}
private Task GetTimezoneByCityName(string cityEnName)
{
return Context.Queryable().Where(val => !val.IsDeleted && val.EnName == cityEnName)
.Select(val=>new CityTimezoneDto()
{
CityEnName =val.EnName,
Timezone = val.TimeZone
})
.FirstAsync();
}
private Task GetTimezoneByPortCode(string airCode)
{
return Context.Queryable()
.InnerJoin((city, airport) => city.Id == airport.CityId)
.Where((city,airport) => !airport.IsDeleted && !city.IsDeleted && airport.Code == airCode)
.Select((city,airport)=>new PortTimezoneDto()
{
PortCode = airport.Code,
Timezone = city.TimeZone
})
.FirstAsync();
}
}