UCSingleGrid.xaml.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. using MeterVision.Config;
  2. using MeterVision.db;
  3. using MeterVision.Dlg;
  4. using MeterVision.FreeAi;
  5. using MeterVision.model;
  6. using MeterVision.Util;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Collections.ObjectModel;
  10. using System.ComponentModel;
  11. using System.IO;
  12. using System.Net;
  13. using System.Threading.Tasks;
  14. //using System.Linq;
  15. //using System.Text;
  16. //using System.Threading.Tasks;
  17. using System.Windows;
  18. using System.Windows.Controls;
  19. using System.Windows.Data;
  20. //using System.Windows.Data;
  21. //using System.Windows.Documents;
  22. using System.Windows.Input;
  23. using System.Windows.Media;
  24. using System.Windows.Media.Imaging;
  25. //using System.Windows.Media;
  26. //using System.Windows.Media.Imaging;
  27. //using System.Windows.Navigation;
  28. //using System.Windows.Shapes;
  29. namespace MeterVision.Single
  30. {
  31. /// <summary>
  32. /// UCSingleGrid.xaml 的交互逻辑
  33. /// </summary>
  34. public partial class UCSingleGrid : UserControl, INotifyPropertyChanged
  35. {
  36. public event PropertyChangedEventHandler PropertyChanged;
  37. protected void OnPropertyChanged(string propertyName)
  38. {
  39. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  40. }
  41. //定义数据源
  42. public ObservableCollection<SingleDetailItem> SingleDetailItemList { get; set; }
  43. //定义事件,用于通知外部组件选中项已更改(用于其它窗体或用户控件注册)
  44. public event EventHandler<SingleDetailItemChangedEventArgs> OnSelectedSingDetailItemChanged;
  45. private SingleDetailItem _selectedSingleDetailItem;
  46. public SingleDetailItem SelectedSingleDetailItem
  47. {
  48. get => _selectedSingleDetailItem;
  49. set
  50. {
  51. if(_selectedSingleDetailItem != value)
  52. {
  53. _selectedSingleDetailItem = value;
  54. OnPropertyChanged(nameof(SelectedSingleDetailItem));
  55. OnSelectedSingDetailItemChanged?.Invoke(this, new SingleDetailItemChangedEventArgs(value));
  56. }
  57. }
  58. }
  59. public CfginiItem mConfigItem { get; set; }
  60. public PageModel SingleDetailPage { get; set; }
  61. private int _totalRecord;
  62. public int TotalRecords
  63. {
  64. get => _totalRecord;
  65. set
  66. {
  67. if (_totalRecord != value)
  68. {
  69. _totalRecord = value;
  70. OnPropertyChanged(nameof(TotalRecords));
  71. }
  72. }
  73. }
  74. public UCSingleGrid()
  75. {
  76. InitializeComponent();
  77. SingleDetailItemList = new ObservableCollection<SingleDetailItem>();
  78. dgSingle.ItemsSource = SingleDetailItemList;
  79. mConfigItem = CfginiItem.GetConfigItem();
  80. SingleDetailPage = new PageModel
  81. {
  82. PageSize = mConfigItem.SinglePageSize,
  83. PageNumber = 1
  84. };
  85. //mConfigItem.OnSinglePageSizeChanged += MConfigItem_OnSinglePageSizeChanged;
  86. mConfigItem.OnSinglePageSizeChanged += MConfigItem_OnSinglePageSizeChanged1;
  87. InitializeAsync();
  88. //CreateDemoData();
  89. this.DataContext = this;
  90. }
  91. private async void MConfigItem_OnSinglePageSizeChanged1(int pageSize)
  92. {
  93. SingleDetailPage.InitDefaulValue(pageSize);
  94. await LoadSingleDetailItemList();
  95. }
  96. private async void InitializeAsync()
  97. {
  98. await LoadSingleDetailItemList();
  99. }
  100. private async void MConfigItem_OnSinglePageSizeChanged(object sender, PageSizeChangedEventArgs e)
  101. {
  102. SingleDetailPage.InitDefaulValue(e.PageSize);
  103. await LoadSingleDetailItemList();
  104. }
  105. public async void RefreshData()
  106. {
  107. SingleDetailPage.InitDefaulValue();
  108. await LoadSingleDetailItemList();
  109. }
  110. public async Task<bool> LoadSingleDetailItemList()
  111. {
  112. SingleDetailItemList.Clear();
  113. try
  114. {
  115. var result = await Task.Run(() =>
  116. {
  117. return DBSingle.GetPagedSingleDetails(SingleDetailPage.PageNumber, SingleDetailPage.PageSize);
  118. });
  119. TotalRecords = result.Item1;
  120. SingleDetailPage.PageCount = result.Item2;
  121. List<TSingleDetail> singleDetails = result.Item3;
  122. //更新数据需要在主线中进行
  123. Application.Current.Dispatcher.Invoke(() =>
  124. {
  125. int index = 0;
  126. foreach (TSingleDetail singleDetail in singleDetails)
  127. {
  128. index++;
  129. SingleDetailItem item = new SingleDetailItem(singleDetail);
  130. item.Index = index + ((SingleDetailPage.PageNumber - 1) * SingleDetailPage.PageSize);
  131. SingleDetailItemList.Add(item);
  132. }//foreach
  133. SelectedSingleDetailItem = null;
  134. });
  135. return true;
  136. }
  137. catch (Exception ex)
  138. {
  139. MessageBox.Show(Application.Current.MainWindow,
  140. $"加载数据时发生错误:{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
  141. return false;
  142. }
  143. }
  144. //private imgWindow mImgWindow;
  145. private void SrcImage_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  146. {
  147. var image = sender as Image;
  148. if (image == null) return;
  149. var dataContext = image.DataContext as SingleDetailItem;
  150. if (dataContext == null) return;
  151. //var dialog = new ImageViewerWindow(dataContext.SourceImagePath)
  152. if (!File.Exists(dataContext.SrcImage)) return;
  153. //((MainWindow)Application.Current.MainWindow).overlay.Visibility = Visibility.Visible;
  154. imgWindow dialog = new imgWindow(dataContext.SrcImage)
  155. {
  156. Owner = Application.Current.MainWindow
  157. };
  158. //dialog.ShowDialog();
  159. dialog.Show();
  160. //this.PreviewMouseDown += UCSingleGrid_PreviewMouseDown;
  161. // 添加事件监听器来监听鼠标点击事件
  162. //dialog.PreviewMouseDown += Dialog_PreviewMouseDown;
  163. //// 添加事件监听器来监听键盘按键事件
  164. //dialog.PreviewKeyDown += Dialog_PreviewKeyDown;
  165. //// 对话框关闭后隐藏覆盖层
  166. //((MainWindow)Application.Current.MainWindow).overlay.Visibility = Visibility.Visible;
  167. //this.dialog
  168. }
  169. private void UCSingleGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
  170. {
  171. //var dialog = (imgWindow)sender;
  172. //if(mImgWindow != null)
  173. //{
  174. // mImgWindow.Close();
  175. //}
  176. //// 检查点击是否发生在对话框外部
  177. ////if (e.OriginalSource == dialog && !dialog.Content.IsMouseOver)
  178. ////{
  179. //// dialog.Close();
  180. ////}
  181. }
  182. //private void Dialog_PreviewMouseDown(object sender, MouseButtonEventArgs e)
  183. //{
  184. // var dialog = (imgWindow)sender;
  185. // // 检查点击是否发生在对话框外部
  186. // if (e.OriginalSource == dialog && !dialog.Content.IsMouseOver)
  187. // {
  188. // dialog.Close();
  189. // }
  190. //}
  191. //private void Dialog_PreviewKeyDown(object sender, KeyEventArgs e)
  192. //{
  193. // var dialog = (imgWindow)sender;
  194. // // 当按下 Esc 键时关闭对话框
  195. // if (e.Key == Key.Escape)
  196. // {
  197. // dialog.Close();
  198. // }
  199. //}
  200. private void DstImage_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  201. {
  202. var image = sender as Image;
  203. if (image == null) return;
  204. var dataContext = image.DataContext as SingleDetailItem;
  205. if (dataContext == null) return;
  206. //var dialog = new ImageViewerWindow(dataContext.SourceImagePath)
  207. if (!File.Exists(dataContext.DstImage)) return;
  208. var dialog = new imgWindow(dataContext.DstImage)
  209. {
  210. Owner = Application.Current.MainWindow
  211. };
  212. dialog.Show();
  213. }
  214. private void UserControl_DragEnter(object sender, DragEventArgs e)
  215. {
  216. // 处理网页拖拽
  217. //if (e.Data.GetDataPresent(DataFormats.Text) || e.Data.GetDataPresent(DataFormats.Bitmap))
  218. if (e.Data.GetDataPresent(DataFormats.Text))
  219. {
  220. e.Effects = DragDropEffects.Copy;
  221. }
  222. else if (e.Data.GetDataPresent(DataFormats.FileDrop))
  223. {
  224. e.Effects = DragDropEffects.Copy; // 如果是文件拖拽,允许复制
  225. }
  226. else
  227. {
  228. e.Effects = DragDropEffects.None; // 不支持的格式
  229. }
  230. e.Handled = true;
  231. }
  232. private void UserControl_PreviewDragOver(object sender, DragEventArgs e)
  233. {
  234. //if (e.Data.GetDataPresent(DataFormats.FileDrop))
  235. //{
  236. // // 获取拖拽的文件数组
  237. // string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
  238. // // 检查是否只拖拽了一个文件,并且该文件不是文件夹
  239. // if (files.Length == 1 && File.Exists(files[0]))
  240. // {
  241. // e.Effects = DragDropEffects.Copy;
  242. // }
  243. // else
  244. // {
  245. // e.Effects = DragDropEffects.None;
  246. // }
  247. //}
  248. //else
  249. //{
  250. // e.Effects = DragDropEffects.None;
  251. //}
  252. //e.Handled = true;
  253. //if (e.Data.GetDataPresent(DataFormats.Text) || e.Data.GetDataPresent(DataFormats.Bitmap))
  254. if (e.Data.GetDataPresent(DataFormats.Text))
  255. {
  256. e.Effects = DragDropEffects.Copy;
  257. }
  258. else if (e.Data.GetDataPresent(DataFormats.FileDrop))
  259. {
  260. string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
  261. if (files.Length == 1 && File.Exists(files[0]))
  262. {
  263. e.Effects = DragDropEffects.Copy;
  264. }
  265. else
  266. {
  267. e.Effects = DragDropEffects.None;
  268. }
  269. }
  270. else
  271. {
  272. e.Effects = DragDropEffects.None;
  273. }
  274. e.Handled = true;
  275. }
  276. private void UserControl_Drop(object sender, DragEventArgs e)
  277. {
  278. if (e.Data.GetDataPresent(DataFormats.FileDrop))
  279. {
  280. // 获取拖拽的文件数组
  281. string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
  282. // 确保只拖拽了一个文件
  283. if (files.Length != 1)
  284. {
  285. //MessageBox.Show("只能拖拽一个文件。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
  286. MessageBox.Show(Application.Current.MainWindow,
  287. "只能拖拽一个文件。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
  288. return;
  289. }
  290. // 获取单个文件路径
  291. string file = files[0];
  292. // 验证文件是否为有效的 JPG 文件,并且文件大小不超过 100KB
  293. if ( (ThisApp.IsJpgFile(file) || ThisApp.IsBmpFile(file) ) &&
  294. ThisApp.IsFileSizeValid(file) && ThisApp.IsImageDimensionsValid(file))
  295. {
  296. // 调用图像处理方法
  297. //ProcessDragFile(file);
  298. DragRecong(file);
  299. }
  300. else
  301. {
  302. MessageBox.Show(Application.Current.MainWindow,
  303. $"文件 {file} 不符合要求:必须是小于 300KB 的 JPG 文件,且图像尺寸必须为 320x240。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
  304. }
  305. }
  306. else if (e.Data.GetDataPresent(DataFormats.Text))
  307. {
  308. // 处理网页拖拽的图像(URL)
  309. string imageUrl = e.Data.GetData(DataFormats.Text).ToString();
  310. // 如果需要,你可以检查 URL 是否以图像文件类型(例如 .jpg, .png)结尾
  311. if (Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
  312. {
  313. // 处理图像 URL
  314. string localFilePath = ProcessImageFromUrl(imageUrl);
  315. if (localFilePath != null)
  316. {
  317. DragRecong(localFilePath);
  318. }
  319. }
  320. }//else if
  321. }
  322. private string ProcessImageFromUrl(string imageUrl)
  323. {
  324. // 你可以通过 WebRequest 下载并显示图像,或者直接显示 URL
  325. try
  326. {
  327. string saveFilePath = null;
  328. using (var client = new WebClient())
  329. {
  330. byte[] imageData = client.DownloadData(imageUrl);
  331. MemoryStream memoryStream = new MemoryStream(imageData);
  332. BitmapImage bitmapImage = new BitmapImage();
  333. bitmapImage.BeginInit();
  334. bitmapImage.StreamSource = memoryStream;
  335. bitmapImage.EndInit();
  336. // 获取图像的宽度和高度
  337. Console.WriteLine($"Width: {bitmapImage.PixelWidth}");
  338. Console.WriteLine($"Height: {bitmapImage.PixelHeight}");
  339. if(bitmapImage.PixelWidth != ThisApp.RequiredWidth ||
  340. bitmapImage.PixelHeight != ThisApp.RequiredHeight)
  341. {
  342. MessageBox.Show(Application.Current.MainWindow,
  343. "图像尺寸不符合320*240的要求。", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
  344. return null;
  345. }
  346. if(memoryStream.Length > ThisApp.MaxFileSize)
  347. {
  348. MessageBox.Show(Application.Current.MainWindow,
  349. "图像的文件大小不符合要求。", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
  350. return null;
  351. }
  352. //判读文件名称是否符号要求,暂时不管
  353. //获取保存网络图片的路径
  354. string folerPath = Path.Combine(mConfigItem.TransImgPath, "www");
  355. if (!Directory.Exists(folerPath))
  356. {
  357. Directory.CreateDirectory(folerPath);
  358. }
  359. //在这里保存成本地文件,并能保留imageUrl中的文件名
  360. // 提取文件名(从 URL 获取文件名部分)
  361. string fileName = Path.GetFileName(new Uri(imageUrl).LocalPath);
  362. saveFilePath = Path.Combine(folerPath, fileName);
  363. // 保存图像到本地文件
  364. if (!File.Exists(saveFilePath))
  365. {
  366. File.WriteAllBytes(saveFilePath, imageData);
  367. }
  368. // 打印保存路径
  369. Console.WriteLine($"Image saved to: {saveFilePath}");
  370. }
  371. return saveFilePath;
  372. }
  373. catch (Exception ex)
  374. {
  375. MessageBox.Show(Application.Current.MainWindow,
  376. $"加载图像失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
  377. return null;
  378. }
  379. }
  380. public async void DragRecong(string srcImagePath)
  381. {
  382. var singleDetail = new SingleDetailItem()
  383. {
  384. SingleDetailId = Guid.NewGuid().ToString(),
  385. CreateTime = ThisApp.GetNowTime_yyyyMMddHHmmss(),
  386. SrcImage = srcImagePath
  387. };
  388. //DBSingle.InsertTSingleDetail0(singleDetail);
  389. bool blRun = await RunAI(true,singleDetail);
  390. Console.Write($"Run:{blRun}");
  391. if (blRun)
  392. {
  393. SingleDetailPage.PageNumber = 1;
  394. await LoadSingleDetailItemList();
  395. if (SingleDetailItemList.Count > 0)
  396. {
  397. SelectedSingleDetailItem = SingleDetailItemList[0];
  398. dgSingle.ScrollIntoView(dgSingle.Items[0]);
  399. }
  400. //MessageBox.Show(Application.Current.MainWindow, "识别成功!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
  401. //识别成功不提示
  402. }
  403. else
  404. {
  405. MessageBox.Show(Application.Current.MainWindow, "识别失败!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
  406. }
  407. }
  408. //处理拖拽的文件
  409. //private void ProcessDragFile(string filePath)
  410. //{
  411. // //AddNewSingTask(filePath);
  412. // InsertFilesWithProgress(new List<string>() { filePath });
  413. //}
  414. //public async void InsertFilesWithProgress(List<string> filePaths)
  415. //{
  416. // // 弹出一个非模式对话框来显示进度
  417. // ProgressDialog progressDialog = new ProgressDialog()
  418. // {
  419. // Owner = Application.Current.MainWindow
  420. // };
  421. // progressDialog.Show();
  422. // // 任务来异步执行文件插入
  423. // await Task.Run(() => InsertFilesToDatabase(filePaths, progressDialog));
  424. // // 关闭进度对话框
  425. // progressDialog.Close();
  426. // //刷新CurItem
  427. // //OnStandItemCountChanged?.Invoke(this, new StandItemCountChangedEventArgs(CurStandItem));
  428. // //刷新数据(并定位第一条)
  429. // SingleDetailPage.PageNumber = 1;
  430. // LoadSingleDetailItemList();
  431. // SelectedSingleDetailItem = SingleDetailItemList[0];
  432. //}
  433. public void InsertFilesToDatabase(List<string> filePaths, ProgressDialog progressDialog)
  434. {
  435. int totalFiles = filePaths.Count;
  436. int currentFile = 0;
  437. foreach (var filePath in filePaths)
  438. {
  439. // 插入文件路径到数据库
  440. //InsertFileToDatabase(filePath);
  441. TSingleDetail singleDetail = new TSingleDetail()
  442. {
  443. SingleDetailId = Guid.NewGuid().ToString(),
  444. CreateTime = ThisApp.GetNowTime_yyyyMMddHHmmss(),
  445. SrcImage = filePath
  446. };
  447. DBSingle.InsertTSingleDetail0(singleDetail);
  448. // 更新进度条
  449. currentFile++;
  450. UpdateProgress(progressDialog, currentFile, totalFiles);
  451. }
  452. }
  453. public void UpdateProgress(ProgressDialog progressDialog, int currentFile, int totalFiles)
  454. {
  455. // 更新进度条的进度
  456. double progress = (double)currentFile / totalFiles * 100;
  457. progressDialog.UpdateProgress(progress);
  458. }
  459. public async void NextPage()
  460. {
  461. if (SingleDetailPage.PageNumber < SingleDetailPage.PageCount)
  462. {
  463. SingleDetailPage.PageNumber += 1;
  464. await LoadSingleDetailItemList();
  465. }
  466. }
  467. public async void PrePage()
  468. {
  469. if (SingleDetailPage.PageNumber > 1)
  470. {
  471. SingleDetailPage.PageNumber -= 1;
  472. await LoadSingleDetailItemList();
  473. }
  474. }
  475. public async void FirstPage()
  476. {
  477. if (SingleDetailPage.PageNumber > 1)
  478. {
  479. SingleDetailPage.PageNumber = 1;
  480. await LoadSingleDetailItemList();
  481. }
  482. }
  483. public async void LastPage()
  484. {
  485. if (SingleDetailPage.PageNumber < SingleDetailPage.PageCount)
  486. {
  487. SingleDetailPage.PageNumber = SingleDetailPage.PageCount;
  488. await LoadSingleDetailItemList();
  489. }
  490. }
  491. public async void SpeciPage(int pageNumber)
  492. {
  493. if (pageNumber != SingleDetailPage.PageNumber &&
  494. pageNumber > 0 && pageNumber <= SingleDetailPage.PageCount)
  495. {
  496. SingleDetailPage.PageNumber = pageNumber;
  497. await LoadSingleDetailItemList();
  498. }
  499. }
  500. // 辅助方法:查找指定类型的祖先元素
  501. public static T FindAncestor<T>(DependencyObject dependencyObject) where T : DependencyObject
  502. {
  503. var parent = VisualTreeHelper.GetParent(dependencyObject);
  504. if (parent == null) return null;
  505. var parentT = parent as T;
  506. return parentT ?? FindAncestor<T>(parent);
  507. }
  508. private void BtnDelDetailItem_Click(object sender, RoutedEventArgs e)
  509. {
  510. //删除选中项
  511. Button button = sender as Button;
  512. if (button == null) return;
  513. DataGridRow row = FindAncestor<DataGridRow>(button);
  514. if (row == null) return;
  515. //获取当前行绑定的数据项
  516. SingleDetailItem selectedItem = row.Item as SingleDetailItem;
  517. DeleteSelectedItem(selectedItem);
  518. }
  519. private void BtnRecongDetailItem_Click(object sender, RoutedEventArgs e)
  520. {
  521. Button button = sender as Button;
  522. if (button == null) return;
  523. DataGridRow row = FindAncestor<DataGridRow>(button);
  524. if (row == null) return;
  525. //获取当前行绑定的数据项
  526. SingleDetailItem selectedItem = row.Item as SingleDetailItem;
  527. RecongSingleDetail(false, SelectedSingleDetailItem);
  528. }
  529. private void BtnLogViewer_Click(object sender, RoutedEventArgs e)
  530. {
  531. Button button = sender as Button;
  532. if (button == null) return;
  533. DataGridRow row = FindAncestor<DataGridRow>(button);
  534. if (row == null) return;
  535. //获取当前行绑定的数据项
  536. SingleDetailItem selectedItem = row.Item as SingleDetailItem;
  537. ShowLogViewer(selectedItem);
  538. }
  539. private void ShowLogViewer(SingleDetailItem selectedItem)
  540. {
  541. if (selectedItem.LogPath != null && File.Exists(selectedItem.LogPath))
  542. {
  543. //LogViewerWindow dialog = new LogViewerWindow(selectedItem.DstImage, selectedItem.LogPath)
  544. var dialog = new LogViewerWindow(selectedItem)
  545. {
  546. Owner = Application.Current.MainWindow,
  547. WindowStartupLocation = WindowStartupLocation.CenterOwner
  548. };
  549. //dialog.ShowDialog();
  550. dialog.Show();
  551. }
  552. }
  553. private async void DeleteSelectedItem(SingleDetailItem selectedItem)
  554. {
  555. if (selectedItem == null) return;
  556. MessageBoxResult result = MessageBox.Show("确定要删除此条目吗?", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);
  557. if (result != MessageBoxResult.Yes) return;
  558. string titleInfo = "正在删除,请稍后...";
  559. WaitWindow waitWindow = new WaitWindow(titleInfo)
  560. {
  561. Owner = Application.Current.MainWindow,
  562. WindowStartupLocation = WindowStartupLocation.CenterOwner
  563. };
  564. waitWindow.Show();
  565. try
  566. {
  567. bool deleteSuccess = false;
  568. await Task.Run(() =>
  569. {
  570. deleteSuccess = DBSingle.DeleteTSingleDetailById(selectedItem.SingleDetailId);
  571. });
  572. if (deleteSuccess)
  573. {
  574. Application.Current.Dispatcher.Invoke(() =>
  575. {
  576. // 从数据源中移除该条目
  577. SingleDetailItemList.Remove(selectedItem);
  578. SelectedSingleDetailItem = null;
  579. });
  580. }
  581. }
  582. catch (Exception ex)
  583. {
  584. MessageBox.Show(Application.Current.MainWindow, $"删除失败:{ex.Message}", "错误",
  585. MessageBoxButton.OK, MessageBoxImage.Error);
  586. }
  587. finally
  588. {
  589. waitWindow.Close();
  590. }
  591. }
  592. //清空所有的列表数据
  593. public async void ClearAllSingleDetail()
  594. {
  595. //清空提示
  596. MessageBoxResult result = MessageBox.Show("确定要清空所有数据吗?", "确认清空", MessageBoxButton.YesNo, MessageBoxImage.Question);
  597. if (result != MessageBoxResult.Yes) return;
  598. string titleInfo = "正在清空数据,请稍后...";
  599. WaitWindow waitWindow = new WaitWindow(titleInfo)
  600. {
  601. Owner = Application.Current.MainWindow,
  602. WindowStartupLocation = WindowStartupLocation.CenterOwner
  603. };
  604. waitWindow.Show();
  605. try
  606. {
  607. bool blClearAll = false;
  608. await Task.Run(() =>
  609. {
  610. blClearAll = DBSingle.ClearTSingleDetailTable();
  611. });
  612. if (blClearAll)
  613. {
  614. SingleDetailPage.InitDefaulValue();
  615. await LoadSingleDetailItemList();
  616. }
  617. }
  618. catch (Exception ex)
  619. {
  620. MessageBox.Show(Application.Current.MainWindow, $"清空失败:{ex.Message}", "错误",
  621. MessageBoxButton.OK, MessageBoxImage.Error);
  622. }
  623. finally
  624. {
  625. waitWindow.Close();
  626. }
  627. }
  628. private void MiDelete_Click(object sender, RoutedEventArgs e)
  629. {
  630. if (SelectedSingleDetailItem == null) return;
  631. //获取当前行绑定的数据项
  632. DeleteSelectedItem(SelectedSingleDetailItem);
  633. }
  634. private void MiRecong_Click(object sender, RoutedEventArgs e)
  635. {
  636. if (SelectedSingleDetailItem == null) return;
  637. RecongSingleDetail(false, SelectedSingleDetailItem);
  638. }
  639. private async void RecongSingleDetail(bool isAdd, SingleDetailItem singleDetailIte)
  640. {
  641. string jpgFile = singleDetailIte.SrcImage;
  642. if (!File.Exists(jpgFile))
  643. {
  644. MessageBox.Show(Application.Current.MainWindow, $"文件:{jpgFile}不存在!", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
  645. return;
  646. }
  647. bool blRun = await RunAI(isAdd, singleDetailIte);
  648. if (blRun)
  649. {
  650. //MessageBox.Show(Application.Current.MainWindow, "识别成功!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
  651. }
  652. else
  653. {
  654. MessageBox.Show(Application.Current.MainWindow, "识别失败!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
  655. }
  656. }
  657. private async Task<bool> RunAI(bool isAdd,SingleDetailItem singleDetailItem)
  658. {
  659. FaRun faRun = new FaRun();
  660. faRun.OnAiRealLogInfo += FaRun_OnAiRealLogInfo;
  661. string titleInfo = "正在识别,请稍后...";
  662. WaitWindow waitWindow = new WaitWindow(titleInfo)
  663. {
  664. Owner = Application.Current.MainWindow,
  665. WindowStartupLocation = WindowStartupLocation.CenterOwner
  666. };
  667. waitWindow.Show();
  668. try
  669. {
  670. TSingleDetail newSingleDetail = null;
  671. bool blRun = await Task.Run(() =>
  672. {
  673. try
  674. {
  675. ResultModel resultModel = null;
  676. try
  677. {
  678. //Application.Current.Dispatcher.Invoke(() =>
  679. //{
  680. // MessageBox.Show(Application.Current.MainWindow, "start1");
  681. //});
  682. resultModel = faRun.StartRecognition(singleDetailItem.SrcImage);
  683. //Application.Current.Dispatcher.Invoke(() =>
  684. //{
  685. // MessageBox.Show(Application.Current.MainWindow, "end1");
  686. //});
  687. }
  688. catch (Exception ex)
  689. {
  690. Console.WriteLine(ex.Message);
  691. //Application.Current.Dispatcher.Invoke(() =>
  692. //{
  693. // MessageBox.Show(Application.Current.MainWindow, $"{ex.Message}", "错误",
  694. // MessageBoxButton.OK, MessageBoxImage.Error);
  695. //});
  696. }
  697. if (resultModel == null) return false;
  698. newSingleDetail = new TSingleDetail(singleDetailItem, resultModel);
  699. //更新数据
  700. bool blOpration;
  701. if (isAdd)
  702. {
  703. blOpration = DBSingle.InsertSingleDetail(newSingleDetail);
  704. }
  705. else
  706. {
  707. blOpration = DBSingle.UpdateSingleDetailByResult(newSingleDetail);
  708. }
  709. return blOpration;
  710. }
  711. catch(Exception ex)
  712. {
  713. Application.Current.Dispatcher.Invoke(() =>
  714. {
  715. MessageBox.Show(Application.Current.MainWindow, $"{ex.Message}", "错误",
  716. MessageBoxButton.OK, MessageBoxImage.Error);
  717. });
  718. return false;
  719. }
  720. });
  721. //------
  722. //在主线程中更新DataGrid的Row数据
  723. if (blRun && !isAdd && newSingleDetail != null)
  724. {
  725. //singleDetailItem = newSingleDetail;
  726. ObjectHelper.CopyMatchingFields(newSingleDetail, singleDetailItem);
  727. }
  728. return blRun;
  729. }
  730. catch (Exception ex)
  731. {
  732. MessageBox.Show(Application.Current.MainWindow, $"识别[{singleDetailItem.SrcImage}]时出错:{ex.Message}", "错误",
  733. MessageBoxButton.OK, MessageBoxImage.Error);
  734. return false;
  735. }
  736. finally
  737. {
  738. waitWindow.Close();
  739. }
  740. }
  741. private void FaRun_OnAiRealLogInfo(object sender, AiRealLogEventArgs e)
  742. {
  743. Console.Write(e.mLogInfo);
  744. }
  745. private void MiViewLog_Click(object sender, RoutedEventArgs e)
  746. {
  747. if(SelectedSingleDetailItem != null)
  748. {
  749. ShowLogViewer(SelectedSingleDetailItem);
  750. }
  751. }
  752. private void MiAddMemo_Click(object sender, RoutedEventArgs e)
  753. {
  754. if (SelectedSingleDetailItem == null) return;
  755. AddMemo(SelectedSingleDetailItem);
  756. }
  757. private void AddMemo(SingleDetailItem detailItem)
  758. {
  759. if (detailItem == null) return;
  760. EditMemo editMemo = new EditMemo(detailItem.Memo)
  761. {
  762. Owner = Application.Current.MainWindow,
  763. WindowStartupLocation = WindowStartupLocation.CenterOwner
  764. };
  765. if (editMemo.ShowDialog() == true)
  766. {
  767. string memo = editMemo.Memo;
  768. if (DBSingle.UpdateSingleDetailMemo(detailItem.SingleDetailId, memo))
  769. {
  770. detailItem.Memo = memo;
  771. }
  772. }
  773. }
  774. private void Memo_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  775. {
  776. if(e.ClickCount == 2)
  777. {
  778. if (SelectedSingleDetailItem == null) return;
  779. AddMemo(SelectedSingleDetailItem);
  780. }
  781. }
  782. ///////////////////////////////////////////////////////////////////////////
  783. }
  784. //自定义事件参数类
  785. public class SingleDetailItemChangedEventArgs : EventArgs
  786. {
  787. public SingleDetailItem SelectedSingleDetailItem { get; }
  788. public SingleDetailItemChangedEventArgs(SingleDetailItem selectedData)
  789. {
  790. SelectedSingleDetailItem = selectedData;
  791. }
  792. }
  793. }