终端一体化运控平台
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

409 行
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.InfoNotify = 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.DeviceProcessLogNotify = new Action<string, string>((id, s) =>
  157. {
  158. System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
  159. {
  160. LogModel logModel = new LogModel { message = s, type = "DeviceLog" };
  161. LogDataGridData.Insert(0, logModel);
  162. AddLog(logModel);
  163. logHelper.GetLogConfigInstance().WriteLog(LogLevel.DEBUG, s);
  164. }));
  165. });
  166. //设备告警日志
  167. MessageLog.GetInstance.DeviceAlarmLogNotify = new Action<string, string>((id, s) =>
  168. {
  169. System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
  170. {
  171. LogModel logModel = new LogModel { message = id, type = "DeviceAlarm" };
  172. LogDataGridData.Insert(0, logModel);
  173. AddLog(logModel);
  174. logHelper.GetLogConfigInstance().WriteLog(LogLevel.WARN, id);
  175. }));
  176. });
  177. //错误日志
  178. MessageLog.GetInstance.ExInfoNotify = new Action<string>((s) =>
  179. {
  180. System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
  181. {
  182. LogModel logModel = new LogModel { message = s, type = "Error" };
  183. LogDataGridData.Insert(0, logModel);
  184. AddLog(logModel);
  185. logHelper.GetLogConfigInstance().WriteLog(LogLevel.ERROR, s);
  186. DataVClient.GetInstance().HttpAddLog(new LogTable
  187. {
  188. ClientId = Plugin.GetInstance().GetPlugin<ConfigMgr>().ClientId.ToString(),
  189. LogTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  190. LogType = "严重",
  191. LogMessage = s,
  192. LogVla = "错误日志"
  193. });
  194. }));
  195. });
  196. ExcelCommand = new BPARelayCommand(() =>
  197. {
  198. ExcellOrder();
  199. });
  200. OpenCommand = new BPARelayCommand(() =>
  201. {
  202. string msg = string.Format("已找到日志文件,是否打开! \n 1.如选中不打开,则弹出日志文件夹目录。\n 2.打开,则弹出日志文件夹目录,并打开文件。");
  203. if (System.Windows.MessageBox.Show(msg, "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
  204. {
  205. System.Diagnostics.Process.Start("Explorer", "/select," + logHelper.GetLogConfigInstance().directRollfileAppender.File);
  206. logHelper.GetLogConfigInstance().OpenFile(logHelper.GetLogConfigInstance().directRollfileAppender.File);
  207. }
  208. else
  209. System.Diagnostics.Process.Start("Explorer", "/select," + logHelper.GetLogConfigInstance().directRollfileAppender.File);
  210. });
  211. dispatcherTimer = new DispatcherTimer();
  212. dispatcherTimer.Tick += delegate
  213. {
  214. System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
  215. {
  216. if (LogDataGridData.Count > 200)
  217. {
  218. LogModel logModel = LogDataGridData.Last();
  219. DeleteLog(logModel);
  220. LogDataGridData.Remove(logModel);
  221. }
  222. }));
  223. };
  224. dispatcherTimer.Interval = TimeSpan.FromSeconds(10);
  225. dispatcherTimer.Start();
  226. UpDataFileTimer = new DispatcherTimer();
  227. UpDataFileTimer.Tick += delegate
  228. {
  229. DataVClient.GetInstance().UpDataFile();
  230. };
  231. UpDataFileTimer.Interval = TimeSpan.FromHours(0.5);
  232. UpDataFileTimer.Start();
  233. }
  234. /// <summary>
  235. /// 增加日志
  236. /// </summary>
  237. public void AddLog(LogModel logModel)
  238. {
  239. BookEx book = SelectBookExs?.ToList().Find(par => par.IsChecked && par.BookN.Tag == logModel.type);
  240. if (book != null)
  241. {
  242. LogDataGrid.Insert(0, logModel);
  243. }
  244. }
  245. /// <summary>
  246. /// 刷新日志
  247. /// </summary>
  248. /// <param name="logModel"></param>
  249. public void RefreshLog()
  250. {
  251. LogDataGrid.Clear();
  252. LogDataGridData?.ToList().ForEach(b =>
  253. {
  254. BookEx book = SelectBookExs?.ToList().Find(par => par.IsChecked && par.BookN.Tag == b.type);
  255. if (book != null)
  256. {
  257. LogDataGrid.Add(b);
  258. }
  259. });
  260. }
  261. /// <summary>
  262. /// 删除日志
  263. /// </summary>
  264. public void DeleteLog(LogModel logModel)
  265. {
  266. LogModel log = LogDataGrid?.ToList().Find(par => par == logModel);
  267. if (log != null) LogDataGrid.Remove(log);
  268. }
  269. /// <summary>
  270. /// 导出数据
  271. /// </summary>
  272. public void ExcellOrder()
  273. {
  274. if (LogDataGrid.Count > 0)
  275. {
  276. string text = "时间 类型 日志内容\n";
  277. LogDataGrid?.ToList().ForEach(temp =>
  278. {
  279. text = text + temp.time + " " + temp.type + " " + temp.message + "\n";
  280. });
  281. SaveFileDialog openfile = new SaveFileDialog();
  282. openfile.Filter = "Txt文件(*.txt)|*.txt";
  283. if (openfile.ShowDialog() == false)
  284. {
  285. return;
  286. }
  287. string path = openfile.FileName;
  288. if (!System.IO.File.Exists(path))
  289. {
  290. //没有则创建这个文件
  291. FileStream fs1 = new FileStream(path, FileMode.Create, FileAccess.Write);//创建写入文件
  292. StreamWriter sw = new StreamWriter(fs1);
  293. sw.WriteLine(text);//开始写入值
  294. sw.Close();
  295. fs1.Close();
  296. }
  297. else
  298. {
  299. FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write);
  300. StreamWriter sr = new StreamWriter(fs);
  301. sr.WriteLine(text);//开始写入值
  302. sr.Close();
  303. fs.Close();
  304. }
  305. string msg = string.Format("记录导出完成,共导出记录{0}条,是否打开!", LogDataGrid.Count);
  306. if (System.Windows.MessageBox.Show(msg, "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
  307. {
  308. logHelper.GetLogConfigInstance().OpenFile(openfile.FileName);
  309. }
  310. }
  311. else
  312. System.Windows.MessageBox.Show("无数据!");
  313. }
  314. /// <summary>
  315. /// 选中改变
  316. /// </summary>
  317. /// <param name="sender"></param>
  318. /// <param name="e"></param>
  319. private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
  320. {
  321. if (e.PropertyName == "IsChecked")
  322. {
  323. BookEx bookEx = sender as BookEx;
  324. if (bookEx != null)
  325. {
  326. IEnumerable<BookEx> bookExs = BookExs.Where(b => b.IsChecked == true);
  327. StringBuilder builder = new StringBuilder();
  328. SelectBookExs.Clear();
  329. foreach (BookEx item in bookExs)
  330. {
  331. builder.Append(item.BookN.Name.Replace("日志", "") + ",");
  332. SelectBookExs.Add((BookEx)item);
  333. }
  334. SelectedText = builder == null ? string.Empty : builder.ToString();
  335. RefreshLog();
  336. }
  337. }
  338. }
  339. #endregion
  340. #region Command
  341. public BPARelayCommand ExcelCommand { get; set; }
  342. public BPARelayCommand OpenCommand { get; set; }
  343. #endregion
  344. }
  345. public class LogModel : NotifyBase
  346. {
  347. public string time { get; set; }
  348. private string _type;
  349. public string type
  350. {
  351. get
  352. {
  353. return _type;
  354. }
  355. set
  356. {
  357. if (_type == value)
  358. return;
  359. _type = value;
  360. if (_type == "Error" || _type == "Error".ToUpper() || _type == "DeviceAlarm".ToUpper() || _type == "DeviceAlarm") foreground = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#ed0032"));
  361. OnPropertyChanged("type");
  362. OnPropertyChanged("foreground");
  363. }
  364. }
  365. public string message { get; set; }
  366. private Brush _foreground;
  367. public Brush foreground
  368. {
  369. get
  370. {
  371. return _foreground;
  372. }
  373. set
  374. {
  375. if (_foreground == value)
  376. return;
  377. _foreground = value;
  378. OnPropertyChanged("foreground");
  379. }
  380. }
  381. public LogModel()
  382. {
  383. foreground = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#21bb2e"));
  384. time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  385. }
  386. }
  387. }