track/src/SJZY.Track.Repository/Queries/TimezoneQueries.cs

101 lines
3.2 KiB
C#

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}";
}
/// <summary>
/// 获取城市时区
/// </summary>
/// <param name="cityEnName">城市英文名称</param>
/// <returns>时区</returns>
public async Task<string> GetCityTimezone(string cityEnName)
{
var key =GetCityKey(cityEnName);
var timezone = RedisHelper.Client.Get<string>(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;
}
/// <summary>
/// 获取港口时区
/// </summary>
/// <param name="airCode">港口三字码</param>
/// <returns>时区</returns>
public async Task<string> GetPortTimezone(string airCode)
{
var key = GetPortKey(airCode);
var timezone = RedisHelper.Client.Get<string>(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<CityTimezoneDto> GetTimezoneByCityName(string cityEnName)
{
return Context.Queryable<VCityEntity>().Where(val => !val.IsDeleted && val.EnName == cityEnName)
.Select(val=>new CityTimezoneDto()
{
CityEnName =val.EnName,
Timezone = val.TimeZone
})
.FirstAsync();
}
private Task<PortTimezoneDto> GetTimezoneByPortCode(string airCode)
{
return Context.Queryable<VCityEntity>()
.InnerJoin<VAirportEntity>((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();
}
}