终端一体化运控平台
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.
 
 
 

408 lines
15 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. //定时上报文件到阿里云
  29. public DispatcherTimer UpDataFileTimer;
  30. //定时清除界面日志
  31. public DispatcherTimer dispatcherTimer;
  32. public string ClientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"].ToString();
  33. public ObservableCollection<LogModel> LogDataGridData { get; set; }
  34. private ObservableCollection<LogModel> _LogModels;public ObservableCollection<LogModel> LogDataGrid
  35. {
  36. get
  37. {
  38. return _LogModels;
  39. }
  40. set
  41. {
  42. if (_LogModels == value)
  43. return;
  44. _LogModels = value;
  45. OnPropertyChanged("LogDataGrid");
  46. }
  47. }
  48. private bool _RealTimeModel = true;public bool RealTimeModel
  49. {
  50. get
  51. {
  52. return _RealTimeModel;
  53. }
  54. set
  55. {
  56. if (_RealTimeModel == value)
  57. return;
  58. _RealTimeModel = value;
  59. OnPropertyChanged("RealTimeModel");
  60. }
  61. }
  62. private bool _TimedClear = true;public bool TimedClear
  63. {
  64. get
  65. {
  66. return _TimedClear;
  67. }
  68. set
  69. {
  70. if (_TimedClear == value)
  71. return;
  72. _TimedClear = value;
  73. OnPropertyChanged("TimedClear");
  74. }
  75. }
  76. private string _SelectedText = "";
  77. public string SelectedText
  78. {
  79. get
  80. {
  81. return _SelectedText;
  82. }
  83. set
  84. {
  85. if (_SelectedText == value)
  86. return;
  87. _SelectedText = value;
  88. OnPropertyChanged("SelectedText");
  89. }
  90. }
  91. public ObservableCollection<BookEx> SelectBookExs { set; get; }
  92. private ObservableCollection<BookEx> _books;
  93. public ObservableCollection<BookEx> BookExs
  94. {
  95. get
  96. {
  97. if (_books == null)
  98. {
  99. _books = new ObservableCollection<BookEx>();
  100. _books.CollectionChanged += (sender, e) =>
  101. {
  102. if (e.OldItems != null)
  103. {
  104. foreach (BookEx bookEx in e.OldItems)
  105. {
  106. bookEx.PropertyChanged -= ItemPropertyChanged;
  107. }
  108. }
  109. if (e.NewItems != null)
  110. {
  111. foreach (BookEx bookEx in e.NewItems)
  112. {
  113. bookEx.PropertyChanged += ItemPropertyChanged;
  114. }
  115. }
  116. };
  117. }
  118. return _books;
  119. }
  120. }
  121. #endregion
  122. #region 单一
  123. private volatile static LogViewModel _Instance;
  124. public static LogViewModel GetInstance() => _Instance ?? (_Instance = new LogViewModel());
  125. private LogViewModel()
  126. {
  127. Init();
  128. }
  129. #endregion
  130. #region 函数
  131. /// <summary>
  132. /// 初始化
  133. /// </summary>
  134. public void Init()
  135. {
  136. logHelper.Fun_InitLog(System.AppDomain.CurrentDomain.BaseDirectory);
  137. if (LogDataGrid == null) LogDataGrid = new ObservableCollection<LogModel>();
  138. if (LogDataGridData == null) LogDataGridData = new ObservableCollection<LogModel>();
  139. BookExs.Add(new BookEx(new Book() { Name = "一般日志", Tag = "Info" }) { IsChecked = true });
  140. BookExs.Add(new BookEx(new Book() { Name = "设备日志", Tag = "DeviceLog" }) { IsChecked = true });
  141. BookExs.Add(new BookEx(new Book() { Name = "错误日志", Tag = "Error" }) { IsChecked = true });
  142. BookExs.Add(new BookEx(new Book() { Name = "告警日志", Tag = "DeviceAlarm" }) { IsChecked = true });
  143. SelectBookExs = new ObservableCollection<BookEx>();
  144. ItemPropertyChanged(new BookEx(new Book()) { IsChecked = true }, new PropertyChangedEventArgs("IsChecked"));
  145. //一般日志
  146. MessageLog.GetInstance.InfoNotify = new Action<string>((s) =>
  147. {
  148. System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
  149. {
  150. LogModel logModel = new LogModel { message = s, type = "Info" };
  151. LogDataGridData.Insert(0, logModel);
  152. AddLog(logModel);
  153. logHelper.GetLogConfigInstance().WriteLog(LogLevel.INFO, s);
  154. }));
  155. });
  156. //设备日志
  157. MessageLog.GetInstance.DeviceProcessLogNotify = new Action<string, string>((id, s) =>
  158. {
  159. System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
  160. {
  161. LogModel logModel = new LogModel { message = s, type = "DeviceLog" };
  162. LogDataGridData.Insert(0, logModel);
  163. AddLog(logModel);
  164. logHelper.GetLogConfigInstance().WriteLog(LogLevel.DEBUG, s);
  165. }));
  166. });
  167. //设备告警日志
  168. MessageLog.GetInstance.DeviceAlarmLogNotify = new Action<string, string>((id, s) =>
  169. {
  170. System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
  171. {
  172. LogModel logModel = new LogModel { message = id, type = "DeviceAlarm" };
  173. LogDataGridData.Insert(0, logModel);
  174. AddLog(logModel);
  175. logHelper.GetLogConfigInstance().WriteLog(LogLevel.WARN, id);
  176. }));
  177. });
  178. //错误日志
  179. MessageLog.GetInstance.ExInfoNotify = new Action<string>((s) =>
  180. {
  181. System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
  182. {
  183. LogModel logModel = new LogModel { message = s, type = "Error" };
  184. LogDataGridData.Insert(0, logModel);
  185. AddLog(logModel);
  186. logHelper.GetLogConfigInstance().WriteLog(LogLevel.ERROR, s);
  187. DataVClient.GetInstance().HttpAddLog(new LogTable
  188. {
  189. ClientId = ClientId,
  190. LogTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  191. LogType = "严重",
  192. LogMessage = s,
  193. LogVla = "错误日志"
  194. });
  195. }));
  196. });
  197. ExcelCommand = new RelayCommand(() =>
  198. {
  199. ExcellOrder();
  200. });
  201. OpenCommand = new RelayCommand(() =>
  202. {
  203. string msg = string.Format("已找到日志文件,是否打开! \n 1.如选中不打开,则弹出日志文件夹目录。\n 2.打开,则弹出日志文件夹目录,并打开文件。");
  204. if (System.Windows.MessageBox.Show(msg, "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
  205. {
  206. System.Diagnostics.Process.Start("Explorer", "/select," + logHelper.GetLogConfigInstance().directRollfileAppender.File);
  207. logHelper.GetLogConfigInstance().OpenFile(logHelper.GetLogConfigInstance().directRollfileAppender.File);
  208. }
  209. else
  210. System.Diagnostics.Process.Start("Explorer", "/select," + logHelper.GetLogConfigInstance().directRollfileAppender.File);
  211. });
  212. dispatcherTimer = new DispatcherTimer();
  213. dispatcherTimer.Tick += delegate
  214. {
  215. System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
  216. {
  217. if (LogDataGridData.Count > 200)
  218. {
  219. LogModel logModel= LogDataGridData.Last();
  220. DeleteLog(logModel);
  221. LogDataGridData.Remove(logModel);
  222. }
  223. }));
  224. };
  225. dispatcherTimer.Interval = TimeSpan.FromSeconds(10);
  226. dispatcherTimer.Start();
  227. UpDataFileTimer = new DispatcherTimer();
  228. UpDataFileTimer.Tick += delegate
  229. {
  230. DataVClient.GetInstance().UpDataFile();
  231. };
  232. UpDataFileTimer.Interval = TimeSpan.FromHours(2);
  233. UpDataFileTimer.Start();
  234. }
  235. /// <summary>
  236. /// 增加日志
  237. /// </summary>
  238. public void AddLog(LogModel logModel)
  239. {
  240. BookEx book= SelectBookExs?.ToList().Find(par => par.IsChecked && par.BookN.Tag == logModel.type);
  241. if (book != null)
  242. {
  243. LogDataGrid.Insert(0, logModel);
  244. }
  245. }
  246. /// <summary>
  247. /// 刷新日志
  248. /// </summary>
  249. /// <param name="logModel"></param>
  250. public void RefreshLog()
  251. {
  252. LogDataGrid.Clear();
  253. LogDataGridData?.ToList().ForEach(b => {
  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 RelayCommand ExcelCommand { get; set; }
  342. public RelayCommand OpenCommand { get; set; }
  343. #endregion
  344. }
  345. public class LogModel : ObservableObject
  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. }