using HMI.Base;
using HMI.Core.Util;
using HMI.UI.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
namespace HMI.LogViewer
{
///
/// UserControl1.xaml 的交互逻辑
///
public partial class LogViewer : PluginControl
{
private bool autoRfh;
public bool AutoRfh
{
get { return autoRfh; }
set
{
Set(ref autoRfh, value);
if (autoRfhTimer != null) autoRfhTimer.Enabled = value;
}
}
private Timer autoRfhTimer;
private int currentPage = 1;
public int CurrentPage
{
get => currentPage;
set
{
Set(ref currentPage, value);
}
}
private int maxPage = 0;
public int MaxPage
{
get => maxPage;
set
{
Set(ref currentPage, value);
}
}
public LogViewer()
{
DataContext = this;
autoRfhTimer = new Timer
{
Enabled = false,
Interval = 1500,
AutoReset = false
};
autoRfhTimer.Elapsed += AutoRfhTimer_Elapsed;
InitializeComponent();
}
public override void InitFinish()
{
//base.InitFinish();
//string baseFile = Path.Combine(logDir, "log.db");
//try
//{
// if (!File.Exists(baseFile))
// {
// SqliteHelper.CreateDatabase(baseFile);
// }
// SqliteHelper sqliteHelper = new SqliteHelper(baseFile);
// sqliteHelper.ExecuteSql(@"CREATE TABLE IF NOT EXISTS log (
// id INTEGER PRIMARY KEY AUTOINCREMENT,
// level TEXT NOT NULL,
// text TEXT NOT NULL,
// source TEXT,
// time TIME
// );");
//}
//catch (Exception ex)
//{
// log.Error("Create Log File Failed.", ex);
//}
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
Loaded -= UserControl_Loaded;
}
private void AutoRfhTimer_Elapsed(object sender, ElapsedEventArgs e)
{
Refresh100items();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
switch (btn.Name)
{
case "queryBtn":
QueryLog();
break;
case "resetBtn":
QueryReset();
break;
case "exportBtn":
break;
default:
break;
}
}
private void QueryLog()
{
try
{
if (startTimeInput.SelectedDateTime == null && endTimeInput.SelectedDateTime == null)
{
ToastHelper.Error(this.lang("log.timeCantBeNull"));
return;
}
if (endTimeInput.SelectedDateTime != null && startTimeInput.SelectedDateTime != null &&
endTimeInput.SelectedDateTime < startTimeInput.SelectedDateTime)
{
ToastHelper.Error(this.lang("log.timeRangeError"));
return;
}
queryBtn.IsEnabled = false;
autoRfhInput.IsEnabled = false;
Filtrate();
}
catch (Exception ex)
{
log.Error("Log Query Failed.", ex);
this.Error($"查询失败!{ex.Message}");
}
finally
{
queryBtn.IsEnabled = true;
autoRfhInput.IsEnabled = true;
}
}
private void QueryReset()
{
levelInput.Text = null;
startTimeInput.SelectedDateTime = null;
endTimeInput.SelectedDateTime = null;
startTimeInput.Text = null;
table.ItemsSource = null;
}
private void Filtrate()
{
string str = LoadSql();
DataTable dt = new DataTable();
var files = GetOldDbFiles(PathHelper.LogViewerDir, new DateTime?[] { startTimeInput.SelectedDateTime,
endTimeInput.SelectedDateTime });
foreach (string file in files)
{
using (SqliteHelper sql = new SqliteHelper(file))
{
dt.Merge(sql.GetDataTable(str));
}
}
if (dt.Rows.Count > 0)
{
dt.DefaultView.Sort = "time Desc";
}
table.ItemsSource = dt.DefaultView;
}
public static string[] GetOldDbFiles(string folderPath, DateTime?[] range)
{
if (!Directory.Exists(folderPath))
{
return new string[0];
}
// 获取所有.db文件并筛选出7天前更新的文件
var oldFiles = Directory.GetFiles(folderPath, "*.db");
try
{
oldFiles = oldFiles.Where(file =>
{
var lastWriteTime = File.GetLastWriteTime(file);
bool flag = true;
if (range[0] != null) flag &= lastWriteTime >= range[0];
//if (range[1] != null) flag &= lastWriteTime <= range[1];
return flag;
}).OrderByDescending(f => f).ToArray();
return oldFiles;
}
catch (Exception ex)
{
return new string[0];
}
}
///
/// 加载界面判断数据库语句
///
/// str数据库的语句
private string LoadSql()
{
string sql = " select level,time,source,text from log";
List datas = new List();
if (!string.IsNullOrEmpty(levelInput.Text))
{
datas.Add($"level='{levelInput.Text}'");
}
if (!string.IsNullOrEmpty(startTimeInput.Text))
{
datas.Add($"time>='{startTimeInput.Text}'");
}
if (!string.IsNullOrEmpty(endTimeInput.Text))
{
datas.Add($"time<='{endTimeInput.Text}'");
}
if (!string.IsNullOrEmpty(sourceInput.Text))
{
datas.Add($"source='{sourceInput.Text}'");
}
string condition = string.Join(" AND ", datas);
condition = string.IsNullOrEmpty(condition) ? string.Empty : $" WHERE {condition}";
sql = $"{sql}{condition} order by time desc";
return sql;
}
///
/// 刷新100条数据
///
private void Refresh100items()
{
autoRfhTimer.Enabled = false;
Task.Run(() =>
{
try
{
string todayLogFile = Path.Combine(PathHelper.LogViewerDir, $"log_{DateTime.Today:yyyy-MM-dd}.db");
if (!File.Exists(todayLogFile)) return;
string str = "select level,time,source,text from log order by time desc limit 100";
using (SqliteHelper sql = new SqliteHelper(todayLogFile))
{
var dt = sql.GetDataTable(str);
this.Dispatcher.BeginInvoke((Action)delegate ()
{
table.ItemsSource = dt.DefaultView;
});
}
}
catch (Exception ex)
{
log.Error("Log Auto Refresh Failed.", ex);
this.Error($"自动刷新失败!{ex.Message}");
}
finally
{
this.Dispatcher.BeginInvoke((Action)delegate ()
{
autoRfhTimer.Enabled = AutoRfh;
});
}
});
}
}
}