using System.Collections.Concurrent;
using System.Timers;
using System.Xml;
using Abp.Dependency;
using Abp.Logging;
using Abp.UI;
using VberZero.Configuration;
using VberZero.Tools.StringModel;
using Timer = System.Timers.Timer;
namespace VberZero.DomainService.AppGuids;
public class RecordIdManager : ISingletonDependency
{
public RecordIdManager(IWebHostEnvironment env)
{
var cfg = env.GetAppConfiguration();
Interval = cfg["RecordId:TimerInterval"]?.ValD() ?? 10;
HasChanged = true;
FileName = Path.Combine(env.ContentRootPath, cfg["RecordId:Path"] ?? VzConsts.ResourceBasePath,
"Guids.Vzx");
}
//分钟
private decimal Interval { get; }
private bool HasChanged { get; set; }
private string FileName { get; set; }
///
/// 定时器
///
private Timer _timer;
private static ConcurrentDictionary RecordIddDictionary { get; set; }
///
/// 获取下一记录ID
///
///
///
public int GetNextRecordId(AppGuidType type)
{
HasChanged = true;
if (RecordIddDictionary.TryGetValue(type, out var record))
{
return record.GetNextId();
}
throw new UserFriendlyException("获取下一记录ID失败!");
}
///
/// 加载文件数据
///
public void LoadDictionary(string fileName = null)
{
if (fileName.NotEmpty())
{
FileName = fileName;
}
if (!File.Exists(FileName))
{
//throw new Exception("未查询到Guid文件,请检查配置!");
LogHelper.Logger.Error("【未查询到Guid文件,请检查配置!】");
return;
}
RecordIddDictionary = new ConcurrentDictionary();
try
{
var xDoc = new XmlDocument();
xDoc.Load(FileName ?? throw new InvalidOperationException());
XmlNode xmlNode = xDoc.LastChild;
if (xmlNode is { HasChildNodes: true })
{
foreach (XmlNode node in xmlNode.ChildNodes)
{
var record = new RecordId
{
IdType = (node.Attributes?["type"] != null ? node.Attributes["type"].Value : "")
.GetEnumByName(),
Step = (node.Attributes?["step"] != null ? node.Attributes["step"].Value : "").ValI(),
LastId = (node.Attributes?["last-id"] != null ? node.Attributes["last-id"].Value : "")
.ValI(),
LastDate = (node.Attributes?["last-date"] != null
? node.Attributes["last-date"].Value
: "").StrToDt()
};
if (!RecordIddDictionary.ContainsKey(record.IdType))
{
RecordIddDictionary.TryAdd(record.IdType, record);
}
}
}
//触发定时器执行
ExecuteTimer();
}
catch (Exception e)
{
LogHelper.Logger.Error("Guid文件解析失败,请检查配置!", e);
//LogHelper.LogException(e);
//throw new Exception($"Guid文件解析失败,请检查配置!({e.Message})");
}
}
///
/// 执行定时器
///
private void ExecuteTimer()
{
if (_timer != null)
{
_timer.Stop();
_timer.Close();
_timer = null;
}
//分钟转换成毫秒
var interval = Convert.ToDouble(Interval * 60 * 1000);
_timer = new Timer(interval);
_timer.Elapsed += Save;
_timer.Enabled = true;
_timer.AutoReset = true;
_timer.Start();
}
///
/// 定时保存数据
///
///
///
private void Save(object source, ElapsedEventArgs ev)
{
if (!HasChanged)
return;
if (RecordIddDictionary == null)
return;
var str = "";
foreach (var dic in RecordIddDictionary)
{
var record = dic.Value;
str += $"";
}
str = $"{str}";
try
{
var xDoc = new XmlDocument { InnerXml = str };
xDoc.Save(FileName);
}
catch (Exception e)
{
LogHelper.LogException(e);
}
HasChanged = false;
}
}