using MeterVision.Config;
using MeterVision.db;
using MeterVision.Dlg;
using MeterVision.model;
using MeterVision.Util;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using Ookii.Dialogs.Wpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
//using System.Windows.Shapes;
namespace MeterVision.Stand
{
///
/// UCStand.xaml 的交互逻辑
///
public partial class UCStandMain : UserControl, INotifyPropertyChanged
{
private const int COLUMN_LEFT_WIDTH = 220;
private const int COLUMN_RIGHT_WIDTH = 400;
private bool LeftVisiable = true; //表示左侧的显示状态
private bool RightVisiable = true; //表示右侧的显示状态
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public PageModel StandPage { get; set; }
//定义模板目录数据源
public ObservableCollection StandItemList { get; set; }
// 定义"标准答案编辑"依赖属性
public static readonly DependencyProperty IsResultEditingProperty =
DependencyProperty.Register("IsResultEditing", typeof(bool), typeof(UCStandMain), new PropertyMetadata(false));
public bool IsResultEditing
{
get { return (bool)GetValue(IsResultEditingProperty); }
set { SetValue(IsResultEditingProperty, value); }
}
private StandItem _selectedStandItem;
public StandItem SelectedStandItem
{
get => _selectedStandItem;
set
{
_selectedStandItem = value;
OnPropertyChanged(nameof(SelectedStandItem)); //通知更新
//ucStandGird.CurStandItem = value;
ucStationGrid.ChangeFind(FindStationId,_selectedStandItem.StandId);
Apply_UCStandDetaisl_Title(value);
}
}
private StationItem _selectedStationItem;
public StationItem SelectedStationItem
{
get => _selectedStationItem;
set
{
_selectedStationItem = value;
OnPropertyChanged(nameof(SelectedStationItem));
ucStandGird.CurStationItem = value;
}
}
private int _totalStandRecords;
public int TotalStandRecords
{
get => _totalStandRecords;
set
{
if (_totalStandRecords != value)
{
_totalStandRecords = value;
OnPropertyChanged(nameof(TotalStandRecords));
}
}
}
public CfginiItem mConfigItem { get; set; }
private void Apply_UCStandDetaisl_Title(StandItem standItem)
{
if(standItem == null)
{
//pnlDetailsTitle.Visibility = Visibility.Hidden;
pnlDetailsFunc.Visibility = Visibility.Hidden;
txtStandName.Text = "请选择左侧模板";
}
else
{
//pnlDetailsTitle.Visibility = Visibility.Visible;
pnlDetailsFunc.Visibility = Visibility.Visible;
//txtStandName.Text = $"模板名称: {standItem.Index}. {standItem.StandName}[{standItem.StandCount}]";
txtStandName.Text = $"模板名称: {standItem.Index}. {standItem.StandName}";
}
}
private void InitRightControls(StandDetailItem standDetailsItem)
{
pnlImage.Visibility = txtRightItemIndex.Visibility =
standDetailsItem == null ? Visibility.Collapsed : Visibility.Visible;
//pnlResult.Visibility = Visibility.Hidden;
}
private string _findStationId;
public string FindStationId
{
get => _findStationId;
set
{
if (_findStationId != value)
{
_findStationId = value;
OnPropertyChanged(nameof(FindStationId));
//ucStationGrid.ChangeFindStationId(FindStationId);
}
}
}
public UCStandMain()
{
InitializeComponent();
StandItemList = new ObservableCollection();
dgStand.ItemsSource = StandItemList;
//this.btnStandExport.Click += BtnStandExport_Click;
ucStandGird.OnSelectedStandDetailItemChanged += UcStandGird_OnSelectedStandDetailsItemChanged;
IsResultEditing = false;
Apply_UCStandDetaisl_Title(null);
//SelectedStandItem = null;
txtFindStationId.Text = "";
FindStationId = "";
InitRightControls(null);
mConfigItem = CfginiItem.GetConfigItem();
StandPage = new PageModel
{
//PageSize = mConfigItem.CatalogPageSize,
PageSize = mConfigItem.StandCatalogPageSize,
PageNumber = 1,
};
//LoadStandItemList();
ucStandGird.OnStandItemCountChanged += UcStandGird_OnStandItemCountChanged;
ucStandGird.OnDeleteStandDetailItem += UcStandGird_OnDeleteStandDetailItem;
mConfigItem.OnStandCatalogPageSizeChanged += MConfigItem_OnStandCatalogPageSizeChanged;
this.DataContext = this;
// 启动异步初始化,确保不会阻塞构造函数
LoadStandItemListAsync();
//控制左右2侧栏目的显示
LeftVisiable = true;
ChangeLeftVisiable(LeftVisiable);
RightVisiable = true;
ChangeRightVisiable(RightVisiable);
ucStationGrid.OnStationItemChange += UcStationGrid_OnStationItemChange;
}
private void UcStationGrid_OnStationItemChange(StationItem stationItem)
{
SelectedStationItem = stationItem;
}
private async void MConfigItem_OnStandCatalogPageSizeChanged(int pageSize)
{
//throw new NotImplementedException();
StandPage.InitDefaulValue(pageSize);
bool blLoad = await LoadStandItemList();
if (blLoad)
{
SelectedStandItem = null;
}
}
private async void LoadStandItemListAsync()
{
await LoadStandItemList();
}
private void UcStandGird_OnStandItemCountChanged(object sender, StandItemCountChangedEventArgs e)
{
//Detail的数量发生变化
RefreshStandItemById(e.mStandItem.StandId);
}
private void UcStandGird_OnDeleteStandDetailItem(string standId)
{
RefreshStandItemById(standId);
}
private async void RefreshStandItemById(string standId)
{
if ( string.IsNullOrWhiteSpace(standId) ) return;
VStand vStand = null;
await Task.Run(() =>
{
vStand = DBStand.GetVStandById(standId);
});
if (vStand != null)
{
//var NewStandItem = new StandItem(vStand);
foreach (var standItem in StandItemList)
{
if (standItem.StandId == vStand.StandId)
{
// ObjectHelper.CopyMatchingFields(NewStandItem, standItem);
ObjectHelper.CopyMatchingFields(vStand, standItem);
break;
}
}//foreach
}//if vpatch!=null
}
private async Task LoadStandItemList()
{
StandItemList.Clear();
try
{
var result = await Task.Run(() =>
{
return DBStand.GetPagedVStands(StandPage.PageNumber, StandPage.PageSize);
});
TotalStandRecords = result.Item1;
StandPage.PageCount = result.Item2;
List stands = result.Item3;
int index = 0;
foreach (VStand vStand in stands)
{
index++;
StandItem standItem = new StandItem(vStand);
standItem.Index = index + (StandPage.PageNumber - 1) * StandPage.PageSize;
StandItemList.Add(standItem);
}
if(StandItemList.Count > 0)
{
//dgStand.ScrollIntoView(StandItemList[0]);
}
return true;
}
catch (Exception ex)
{
MessageBox.Show(Application.Current.MainWindow,
$"加载数据时发生错误:{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
}
private void UcStandGird_OnSelectedStandDetailsItemChanged(object sender, StandDetailItemChangedEventArgs e)
{
InitRightControls(e.SelectedDataItem);
txtRightItemIndex.Text = string.Empty;
if (e.SelectedDataItem != null)
{
ucImageSource.ImageSource = e.SelectedDataItem.SrcImage;
ucImageSource.ImageName = "原始图片";
//txtRightResult.Text = e.SelectedDataItem.StandValue;
IsResultEditing = false;
if(SelectedStandItem != null)
{
txtRightItemIndex.Text = $"{SelectedStandItem.Index}. - {e.SelectedDataItem.Index}.";
}
}
}
//导出模板
private void BtnStandExport_Click(object sender, RoutedEventArgs e)
{
//查询所有的数据
if (SelectedStandItem == null) return;
List standDetails = DBStand.GetAllStandDetails(SelectedStandItem.StandId);
if (standDetails.Count <= 0) return;
string fileName = $"{SelectedStandItem.StandName}_{standDetails.Count}.xlsx";
//创建保存文件对话框
VistaSaveFileDialog saveFileDialog = new VistaSaveFileDialog
{
Filter = "Excel 文件 (*.xlsx)|*.xlsx",
FileName = fileName,
Title = "选择模板保存路径"
};
// 如果用户选择了路径并点击保存
if (saveFileDialog.ShowDialog() == true){
string titleInfo = "正在导出模板数据,请稍后...";
WaitWindow waitWindow = new WaitWindow(titleInfo)
{
Owner = Application.Current.MainWindow,
WindowStartupLocation = WindowStartupLocation.CenterOwner
};
waitWindow.Show();
string filePath = saveFileDialog.FileName;
try{
// 创建Excel包
using (ExcelPackage package = new ExcelPackage()){
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
// 表头
worksheet.Cells[1, 1].Value = "图像";
worksheet.Cells[1, 2].Value = "标准答案";
// 设置表头样式
using (var range = worksheet.Cells[1, 1, 1, 2])
{
//range.Style.Font.Bold = false;
range.Style.Font.Name = "等线";
range.Style.Font.Size = 11;
//range.Style.Fill.PatternType = ExcelFillStyle.Solid;
//range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightBlue);
range.AutoFitColumns();
}
// 填充数据
for (int i = 0; i < standDetails.Count; i++)
{
worksheet.Cells[i + 2, 1].Value = standDetails[i].SrcImage;
worksheet.Cells[i + 2, 2].Value = standDetails[i].StandValue;
// 设置行字体
worksheet.Cells[i + 2, 1, i + 2, 2].Style.Font.Name = "等线";
worksheet.Cells[i + 2, 1, i + 2, 2].Style.Font.Size = 11;
//worksheet.Cells[i + 2, 1, i + 2, 2].Style.Font.Color.SetColor(System.Drawing.Color.Black);
}
// 设置列宽
worksheet.Column(1).Width = 50; // 姓名列
worksheet.Column(2).Width = 20; // 年龄列
// 或者自动调整列宽
//worksheet.Cells.AutoFitColumns();
// 保存到用户选择的路径
FileInfo excelFile = new FileInfo(filePath);
package.SaveAs(excelFile);
MessageBox.Show("Excel导出成功!");
}
}
catch (Exception ex){
MessageBox.Show($"导出失败: {ex.Message}");
}
waitWindow.Close();
}
}
private void BtnStandImport_Click(object sender, RoutedEventArgs e)
{
//throw new NotImplementedException();
}
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
// 只允许数字输入
e.Handled = !Regex.IsMatch(e.Text, @"^\d$");
}
private void TxtRightResult_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
// 只允许数字输入
e.Handled = !Regex.IsMatch(e.Text, @"^\d$");
}
private void BtnEditRightResult_Click(object sender, RoutedEventArgs e)
{
IsResultEditing = true;
}
private void BtnSubmitRightResult_Click(object sender, RoutedEventArgs e)
{
IsResultEditing = false;
}
private void BtnCancelRightResult_Click(object sender, RoutedEventArgs e)
{
IsResultEditing = false;
}
private async void BtnStandNextPage_Click(object sender, RoutedEventArgs e)
{
if(StandPage.PageNumber < StandPage.PageCount)
{
StandPage.PageNumber += 1;
bool blLoad = await LoadStandItemList();
if(blLoad && StandItemList.Count > 0)
{
dgStand.ScrollIntoView(StandItemList[0]);
}
}
}
private async void BtnStandPrePage_Click(object sender, RoutedEventArgs e)
{
if(StandPage.PageNumber > 1)
{
StandPage.PageNumber -= 1;
bool blLoad = await LoadStandItemList();
if(blLoad && StandItemList.Count > 0)
{
dgStand.ScrollIntoView(StandItemList[0]);
}
}
}
private void BtnStandDetailFirstPage_Click(object sender, RoutedEventArgs e)
{
ucStandGird.FirstPage();
}
private void BtnStandDetailNextPage_Click(object sender, RoutedEventArgs e)
{
ucStandGird.NextPage();
}
private void BtnStanddetailPrePage_Click(object sender, RoutedEventArgs e)
{
ucStandGird.PrePage();
}
private void BtnStandDetailLastPage_Click(object sender, RoutedEventArgs e)
{
ucStandGird.LastPage();
}
private void BtnStandDetailSpeciPage_Click(object sender, RoutedEventArgs e)
{
try
{
int pageNumber = int.Parse(txtStandDetailPageNumber.Text.ToString());
ucStandGird.SpeciPage(pageNumber);
}
catch
{
}
}
private async void BtnAddStand_Click(object sender, RoutedEventArgs e)
{
//List tableNames = SQLiteHelper.GetAllTables();
var dialog = new AddStandDialog()
{
Owner = Application.Current.MainWindow,
WindowStartupLocation = WindowStartupLocation.CenterOwner
};
if (dialog.ShowDialog() == true)
{
StandPage.InitDefaulValue();
bool blLoad = await LoadStandItemList();
if (blLoad && StandItemList.Count > 0)
{
SelectedStandItem = StandItemList[0];
dgStand.ScrollIntoView(StandItemList[0]);
}
}
}
private async void BtnDelStand_Click(object sender, RoutedEventArgs e)
{
bool blDelete = await DeleteStandItem();
}
private async Task DeleteStandItem()
{
bool blDelete = false;
if (SelectedStandItem == null) return blDelete;
MessageBoxResult result = MessageBox.Show(
$"您确定要删除[{SelectedStandItem.StandName}]任务吗?\n此操作无法撤销。",
"确认删除",
MessageBoxButton.YesNo, // 提供“是”和“否”按钮
MessageBoxImage.Warning // 使用警告图标
);
if (result != MessageBoxResult.Yes)
{
return blDelete;
}
//开始删除操作
string titleInfo = "正在删除,请稍候...";
WaitWindow waitWindow = new WaitWindow(titleInfo)
{
Owner = Application.Current.MainWindow,
WindowStartupLocation = WindowStartupLocation.CenterOwner
};
waitWindow.Show();
try
{
//执行异步删除逻辑
bool deleteSuccess = false;
await Task.Run(() =>
{
deleteSuccess = DBStand.DeleteStandAndDetails(SelectedStandItem.StandId);
//Task.Delay(200).Wait(); // 模拟延迟
});
if (deleteSuccess)
{
//await LoadStandItemList();
// 在 UI 线程上更新 ObservableCollection
Application.Current.Dispatcher.Invoke(() =>
{
StandItemList.Remove(SelectedStandItem);
SelectedStandItem = null;
TotalStandRecords -= 1;
});
blDelete = true;
}
}
catch (Exception ex)
{
MessageBox.Show(Application.Current.MainWindow, $"删除失败:{ex.Message}", "错误",
MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
//关闭等待窗口
waitWindow.Close();
}
return blDelete;
}
private async void BtnRefresh_Click(object sender, RoutedEventArgs e)
{
StandPage.InitDefaulValue();
bool blLoad = await LoadStandItemList();
if (blLoad && StandItemList.Count > 0)
{
dgStand.ScrollIntoView(StandItemList[0]);
}
}
private async void MiDeleteStand_Click(object sender, RoutedEventArgs e)
{
bool blDelete = await DeleteStandItem();
}
private void MiUpdateStandname_Click(object sender, RoutedEventArgs e)
{
if (SelectedStandItem == null) return;
EditNameDlg editNameDlg = new EditNameDlg("模板", SelectedStandItem.StandName)
{
Owner = Application.Current.MainWindow,
WindowStartupLocation = WindowStartupLocation.CenterOwner
};
if (editNameDlg.ShowDialog() == true)
{
UpdateStandName(SelectedStandItem, editNameDlg.EditName);
}
}
private async void UpdateStandName(StandItem standItem,string newStandName)
{
try
{
bool blUpdate = false;
await Task.Run(() =>
{
blUpdate = DBStand.UpdateStandName(standItem.StandId, newStandName);
});
if (blUpdate)
{
standItem.StandName = newStandName;
}
else
{
MessageBox.Show(Application.Current.MainWindow, $"修改模板名称失败。", "警告",
MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
catch(Exception ex)
{
MessageBox.Show(Application.Current.MainWindow, $"修改模板名称:{ex.Message}错误", "错误",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void BtnRefreshDetail_Click(object sender, RoutedEventArgs e)
{
//ucStandGird.CurStandItem = null;
//ucStandGird.CurStandItem = SelectedStandItem;
ucStandGird.CurStationItem = null;
ucStandGird.CurStationItem = SelectedStationItem;
}
//private async void BtnSelectImageFloder_Click(object sender, RoutedEventArgs e)
//{
// // 创建 VistaFolderBrowserDialog 实例
// var dialog = new VistaFolderBrowserDialog();
// dialog.Description = "请选择模板图片文件夹";
// dialog.UseDescriptionForTitle = true; // 使用 Description 作为窗口标题
// // 显示对话框并检查用户是否点击了“确定”
// if (dialog.ShowDialog() == true)
// {
// // 获取用户选择的文件夹路径
// string selectedFolderPath = dialog.SelectedPath;
// await ucStandGird.ImportStandImageFloder(selectedFolderPath);
// }
//}
private void BtnLeftCtl_Click(object sender, RoutedEventArgs e)
{
bool visiable = !LeftVisiable;
ChangeLeftVisiable(visiable);
}
private void BtnRightCtl_Click(object sender, RoutedEventArgs e)
{
bool visiable = !RightVisiable;
ChangeRightVisiable(visiable);
}
private void ChangeLeftVisiable(bool visiable)
{
LeftVisiable = visiable;
colLeft.Width = new GridLength(visiable ? COLUMN_LEFT_WIDTH : 0);
btnLeftCtl.Content = visiable ? "◀️" : "▶️";
btnLeftCtl.ToolTip = visiable ? "点击隐藏左侧栏" : "点击显示左侧栏";
}
private void ChangeRightVisiable(bool visiable)
{
RightVisiable = visiable;
colRight.Width = new GridLength(visiable ? COLUMN_RIGHT_WIDTH : 0);
btnRightCtl.Content = visiable ? "▶️" : "◀️";
btnRightCtl.ToolTip = visiable ? "点击隐藏右侧栏" : "点击显示右侧栏";
}
private void BtnStationFirstPage_Click(object sender, RoutedEventArgs e)
{
ucStationGrid.FirstPage();
}
private void BtnStationPrePage_Click(object sender, RoutedEventArgs e)
{
ucStationGrid.PrePage();
}
private void BtnStationNextPage_Click(object sender, RoutedEventArgs e)
{
ucStationGrid.NextPage();
}
private void BtnStationLastPage_Click(object sender, RoutedEventArgs e)
{
ucStationGrid.LastPage();
}
private void BtnStationSpeciPage_Click(object sender, RoutedEventArgs e)
{
try
{
int pageNumber = int.Parse(txtStationPageNumber.Text.ToString());
ucStationGrid.SpeciPage(pageNumber);
}
catch
{
}
}
private void BtnQuery_Click(object sender, RoutedEventArgs e)
{
FindStationId = txtFindStationId.Text.Trim();
ucStationGrid.ChangeFind(FindStationId, SelectedStandItem.StandId);
Apply_UCStandDetaisl_Title(SelectedStandItem);
}
private void BtnRefreshStation_Click(object sender, RoutedEventArgs e)
{
FindStationId = txtFindStationId.Text.Trim();
ucStationGrid.ChangeFind(FindStationId, SelectedStandItem.StandId);
Apply_UCStandDetaisl_Title(SelectedStandItem);
}
/////////////////////////////////////////////////////////////////////////////
}
}