终端一体化运控平台
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

414 lignes
15 KiB

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