终端一体化运控平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

397 lines
14 KiB

  1. using BPASmartClient.Helper;
  2. using BPASmartClient.IoT;
  3. using BPASmartClient.Message;
  4. using BPASmartClient.Model;
  5. using Microsoft.Toolkit.Mvvm.ComponentModel;
  6. using Microsoft.Toolkit.Mvvm.Input;
  7. using Microsoft.Win32;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Collections.ObjectModel;
  11. using System.ComponentModel;
  12. using System.Diagnostics;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. using System.Windows;
  18. using System.Windows.Media;
  19. using System.Windows.Threading;
  20. namespace BPASmartClient.ViewModel
  21. {
  22. /// <summary>
  23. /// 日志界面
  24. /// </summary>
  25. public class LogViewModel : ObservableObject
  26. {
  27. #region 变量
  28. public DispatcherTimer dispatcherTimer;
  29. public string ClientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"].ToString();
  30. public ObservableCollection<LogModel> LogDataGridData { get; set; }
  31. private ObservableCollection<LogModel> _LogModels;public ObservableCollection<LogModel> LogDataGrid
  32. {
  33. get
  34. {
  35. return _LogModels;
  36. }
  37. set
  38. {
  39. if (_LogModels == value)
  40. return;
  41. _LogModels = value;
  42. OnPropertyChanged("LogDataGrid");
  43. }
  44. }
  45. private bool _RealTimeModel = true;public bool RealTimeModel
  46. {
  47. get
  48. {
  49. return _RealTimeModel;
  50. }
  51. set
  52. {
  53. if (_RealTimeModel == value)
  54. return;
  55. _RealTimeModel = value;
  56. OnPropertyChanged("RealTimeModel");
  57. }
  58. }
  59. private bool _TimedClear = true;public bool TimedClear
  60. {
  61. get
  62. {
  63. return _TimedClear;
  64. }
  65. set
  66. {
  67. if (_TimedClear == value)
  68. return;
  69. _TimedClear = value;
  70. OnPropertyChanged("TimedClear");
  71. }
  72. }
  73. private string _SelectedText = "";
  74. public string SelectedText
  75. {
  76. get
  77. {
  78. return _SelectedText;
  79. }
  80. set
  81. {
  82. if (_SelectedText == value)
  83. return;
  84. _SelectedText = value;
  85. OnPropertyChanged("SelectedText");
  86. }
  87. }
  88. public ObservableCollection<BookEx> SelectBookExs { set; get; }
  89. private ObservableCollection<BookEx> _books;
  90. public ObservableCollection<BookEx> BookExs
  91. {
  92. get
  93. {
  94. if (_books == null)
  95. {
  96. _books = new ObservableCollection<BookEx>();
  97. _books.CollectionChanged += (sender, e) =>
  98. {
  99. if (e.OldItems != null)
  100. {
  101. foreach (BookEx bookEx in e.OldItems)
  102. {
  103. bookEx.PropertyChanged -= ItemPropertyChanged;
  104. }
  105. }
  106. if (e.NewItems != null)
  107. {
  108. foreach (BookEx bookEx in e.NewItems)
  109. {
  110. bookEx.PropertyChanged += ItemPropertyChanged;
  111. }
  112. }
  113. };
  114. }
  115. return _books;
  116. }
  117. }
  118. #endregion
  119. #region 单一
  120. private volatile static LogViewModel _Instance;
  121. public static LogViewModel GetInstance() => _Instance ?? (_Instance = new LogViewModel());
  122. private LogViewModel()
  123. {
  124. Init();
  125. }
  126. #endregion
  127. #region 函数
  128. /// <summary>
  129. /// 初始化
  130. /// </summary>
  131. public void Init()
  132. {
  133. logHelper.Fun_InitLog(System.AppDomain.CurrentDomain.BaseDirectory);
  134. if (LogDataGrid == null) LogDataGrid = new ObservableCollection<LogModel>();
  135. if (LogDataGridData == null) LogDataGridData = new ObservableCollection<LogModel>();
  136. BookExs.Add(new BookEx(new Book() { Name = "一般日志", Tag = "Info" }) { IsChecked = true });
  137. BookExs.Add(new BookEx(new Book() { Name = "设备日志", Tag = "DeviceLog" }) { IsChecked = true });
  138. BookExs.Add(new BookEx(new Book() { Name = "错误日志", Tag = "Error" }) { IsChecked = true });
  139. BookExs.Add(new BookEx(new Book() { Name = "告警日志", Tag = "DeviceAlarm" }) { IsChecked = true });
  140. SelectBookExs = new ObservableCollection<BookEx>();
  141. ItemPropertyChanged(new BookEx(new Book()) { IsChecked = true }, new PropertyChangedEventArgs("IsChecked"));
  142. //一般日志
  143. MessageLog.GetInstance.InfoNotify = new Action<string>((s) =>
  144. {
  145. System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
  146. {
  147. LogModel logModel = new LogModel { message = s, type = "Info" };
  148. LogDataGridData.Insert(0, logModel);
  149. AddLog(logModel);
  150. logHelper.GetLogConfigInstance().WriteLog(LogLevel.INFO, s);
  151. }));
  152. });
  153. //设备日志
  154. MessageLog.GetInstance.DeviceProcessLogNotify = new Action<string, string>((id, s) =>
  155. {
  156. System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
  157. {
  158. LogModel logModel = new LogModel { message = s, type = "DeviceLog" };
  159. LogDataGridData.Insert(0, logModel);
  160. AddLog(logModel);
  161. logHelper.GetLogConfigInstance().WriteLog(LogLevel.DEBUG, s);
  162. }));
  163. });
  164. //设备告警日志
  165. MessageLog.GetInstance.DeviceAlarmLogNotify = new Action<string, string>((id, s) =>
  166. {
  167. System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
  168. {
  169. LogModel logModel = new LogModel { message = id, type = "DeviceAlarm" };
  170. LogDataGridData.Insert(0, logModel);
  171. AddLog(logModel);
  172. logHelper.GetLogConfigInstance().WriteLog(LogLevel.WARN, id);
  173. }));
  174. });
  175. //错误日志
  176. MessageLog.GetInstance.ExInfoNotify = new Action<string>((s) =>
  177. {
  178. System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
  179. {
  180. LogModel logModel = new LogModel { message = s, type = "Error" };
  181. LogDataGridData.Insert(0, logModel);
  182. AddLog(logModel);
  183. logHelper.GetLogConfigInstance().WriteLog(LogLevel.ERROR, s);
  184. DataVClient.GetInstance().HttpAddLog(new LogTable
  185. {
  186. ClientId = ClientId,
  187. LogTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  188. LogType = "严重",
  189. LogMessage = s,
  190. LogVla = "错误日志"
  191. });
  192. }));
  193. });
  194. ExcelCommand = new RelayCommand(() =>
  195. {
  196. ExcellOrder();
  197. });
  198. OpenCommand = new RelayCommand(() =>
  199. {
  200. string msg = string.Format("已找到日志文件,是否打开! \n 1.如选中不打开,则弹出日志文件夹目录。\n 2.打开,则弹出日志文件夹目录,并打开文件。");
  201. if (System.Windows.MessageBox.Show(msg, "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
  202. {
  203. System.Diagnostics.Process.Start("Explorer", "/select," + logHelper.GetLogConfigInstance().directRollfileAppender.File);
  204. logHelper.GetLogConfigInstance().OpenFile(logHelper.GetLogConfigInstance().directRollfileAppender.File);
  205. }
  206. else
  207. System.Diagnostics.Process.Start("Explorer", "/select," + logHelper.GetLogConfigInstance().directRollfileAppender.File);
  208. });
  209. dispatcherTimer = new DispatcherTimer();
  210. dispatcherTimer.Tick += delegate
  211. {
  212. System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
  213. {
  214. if (LogDataGridData.Count > 200)
  215. {
  216. LogModel logModel= LogDataGridData.Last();
  217. DeleteLog(logModel);
  218. LogDataGridData.Remove(logModel);
  219. }
  220. }));
  221. };
  222. dispatcherTimer.Interval = TimeSpan.FromSeconds(10);
  223. dispatcherTimer.Start();
  224. }
  225. /// <summary>
  226. /// 增加日志
  227. /// </summary>
  228. public void AddLog(LogModel logModel)
  229. {
  230. BookEx book= SelectBookExs?.ToList().Find(par => par.IsChecked && par.BookN.Tag == logModel.type);
  231. if (book != null)
  232. {
  233. LogDataGrid.Insert(0, logModel);
  234. }
  235. }
  236. /// <summary>
  237. /// 刷新日志
  238. /// </summary>
  239. /// <param name="logModel"></param>
  240. public void RefreshLog()
  241. {
  242. LogDataGrid.Clear();
  243. LogDataGridData?.ToList().ForEach(b => {
  244. BookEx book = SelectBookExs?.ToList().Find(par => par.IsChecked && par.BookN.Tag == b.type);
  245. if (book != null)
  246. {
  247. LogDataGrid.Add(b);
  248. }
  249. });
  250. }
  251. /// <summary>
  252. /// 删除日志
  253. /// </summary>
  254. public void DeleteLog(LogModel logModel)
  255. {
  256. LogModel log= LogDataGrid?.ToList().Find(par => par == logModel);
  257. if(log!=null) LogDataGrid.Remove(log);
  258. }
  259. /// <summary>
  260. /// 导出数据
  261. /// </summary>
  262. public void ExcellOrder()
  263. {
  264. if (LogDataGrid.Count > 0)
  265. {
  266. string text = "时间 类型 日志内容\n";
  267. LogDataGrid?.ToList().ForEach(temp =>
  268. {
  269. text = text + temp.time + " " + temp.type + " " + temp.message + "\n";
  270. });
  271. SaveFileDialog openfile = new SaveFileDialog();
  272. openfile.Filter = "Txt文件(*.txt)|*.txt";
  273. if (openfile.ShowDialog() == false)
  274. {
  275. return;
  276. }
  277. string path = openfile.FileName;
  278. if (!System.IO.File.Exists(path))
  279. {
  280. //没有则创建这个文件
  281. FileStream fs1 = new FileStream(path, FileMode.Create, FileAccess.Write);//创建写入文件
  282. StreamWriter sw = new StreamWriter(fs1);
  283. sw.WriteLine(text);//开始写入值
  284. sw.Close();
  285. fs1.Close();
  286. }
  287. else
  288. {
  289. FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write);
  290. StreamWriter sr = new StreamWriter(fs);
  291. sr.WriteLine(text);//开始写入值
  292. sr.Close();
  293. fs.Close();
  294. }
  295. string msg = string.Format("记录导出完成,共导出记录{0}条,是否打开!", LogDataGrid.Count);
  296. if (System.Windows.MessageBox.Show(msg, "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
  297. {
  298. logHelper.GetLogConfigInstance().OpenFile(openfile.FileName);
  299. }
  300. }
  301. else
  302. System.Windows.MessageBox.Show("无数据!");
  303. }
  304. /// <summary>
  305. /// 选中改变
  306. /// </summary>
  307. /// <param name="sender"></param>
  308. /// <param name="e"></param>
  309. private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
  310. {
  311. if (e.PropertyName == "IsChecked")
  312. {
  313. BookEx bookEx = sender as BookEx;
  314. if (bookEx != null)
  315. {
  316. IEnumerable<BookEx> bookExs = BookExs.Where(b => b.IsChecked == true);
  317. StringBuilder builder = new StringBuilder();
  318. SelectBookExs.Clear();
  319. foreach (BookEx item in bookExs)
  320. {
  321. builder.Append(item.BookN.Name.Replace("日志","") + ",");
  322. SelectBookExs.Add((BookEx)item);
  323. }
  324. SelectedText = builder == null ? string.Empty : builder.ToString();
  325. RefreshLog();
  326. }
  327. }
  328. }
  329. #endregion
  330. #region Command
  331. public RelayCommand ExcelCommand { get; set; }
  332. public RelayCommand OpenCommand { get; set; }
  333. #endregion
  334. }
  335. public class LogModel : ObservableObject
  336. {
  337. public string time { get; set; }
  338. private string _type;
  339. public string type
  340. {
  341. get
  342. {
  343. return _type;
  344. }
  345. set
  346. {
  347. if (_type == value)
  348. return;
  349. _type = value;
  350. if (_type == "Error" || _type == "Error".ToUpper() || _type == "DeviceAlarm".ToUpper() || _type == "DeviceAlarm") foreground = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#ed0032"));
  351. OnPropertyChanged("type");
  352. OnPropertyChanged("foreground");
  353. }
  354. }
  355. public string message { get; set; }
  356. private Brush _foreground;
  357. public Brush foreground
  358. {
  359. get
  360. {
  361. return _foreground;
  362. }
  363. set
  364. {
  365. if (_foreground == value)
  366. return;
  367. _foreground = value;
  368. OnPropertyChanged("foreground");
  369. }
  370. }
  371. public LogModel()
  372. {
  373. foreground = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#21bb2e"));
  374. time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  375. }
  376. }
  377. }