using System;
using System.Collections.Concurrent;
using System.Configuration;
using System.IO;
using System.Timers;
using System.Xml;
using Abp.UI;
using IwbZero.ToolCommon.LogHelpers;
using IwbZero.ToolCommon.StringModel;
using WeApp.BaseInfo;
using WeApp.Configuration;
namespace WeApp.CommonManager.AppGuids
{
public static class RecordIdManager
{
private static readonly decimal Interval = ConfigurationManager.AppSettings["WeApp.RecordId.TimerInterval"]?.ValD() ?? (decimal)1;
private static bool HasChanged = true;
///
/// 定时器
///
private static Timer Timer;
private static string FileName => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, IwbConsts.ResourceBasePath, "Guids.iwbx");
//分钟
private static ConcurrentDictionary RecordIddDictionary { get; set; }
///
/// 获取下一记录ID
///
///
///
public static int GetNextRecordId(AppGuidType type)
{
HasChanged = true;
if (RecordIddDictionary.TryGetValue(type, out var record))
{
return record.GetNextId();
}
throw new UserFriendlyException("获取下一记录ID失败!");
}
///
/// 加载文件数据
///
public static void LoadDictionary()
{
if (!File.Exists(FileName))
{
throw new Exception("未查询到Guid文件,请检查配置!");
}
RecordIddDictionary = new ConcurrentDictionary();
try
{
var xDoc = new XmlDocument();
xDoc.Load(FileName);
XmlNode xmlNode = xDoc.LastChild;
if (xmlNode != null && xmlNode.HasChildNodes)
{
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)
{
typeof(RecordIdManager).LogError(e);
throw new Exception($"Guid文件解析失败,请检查配置!({e.Message})");
}
}
///
/// 执行定时器
///
private static 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();
typeof(RecordIdManager).LogDebug("GUID保存定时器已执行");
}
///
/// 定时保存数据
///
///
///
private static 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
{
typeof(RecordIdManager).LogDebug($"保存GUID文件:{FileName}");
var xDoc = new XmlDocument { InnerXml = str };
xDoc.Save(FileName);
}
catch (Exception e)
{
typeof(RecordIdManager).LogDebug($"保存失败!");
typeof(RecordIdManager).LogError(e);
}
HasChanged = false;
}
}
}