using System.Configuration; using System.Data; using System.IO; using System.IO.Ports; using System.Reflection; using System.Windows.Forms; using System.Windows.Input; using Newtonsoft.Json; using BrilliantSightClient.Model.Entity.ApiEntity; using BrilliantSightClient.Model.Helper; using BrilliantSightClient.Views.UserControl.ViewportData; using SaveFileDialog = Microsoft.Win32.SaveFileDialog; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using BrilliantSightClient.Views.Dialog; using Application = System.Windows.Application; using MessageBox = BrilliantSightClient.Views.Dialog.MessageBox; using System.Windows; using BrilliantSightClient.Views.UserControl.ViewportData.Entity; using BrilliantSightClient.ViewModel.Configuration.SettingsPages; using BrilliantSightClient.Views.UserControl.ViewportData.Helper; using log4net; using NPOI.SS.Util; using BrilliantSightClient.Model.Attributes; using BrilliantSightClient.Model.Extension; using BrilliantSightClient.Model.GradeResult.Entity; using BrilliantSightClient.Model.GradeResult.Entity.Enums; using BrilliantSightClient.Model.GradeResult.Helper; using SparkDotNetCore.DetectCore.Entity; using Exception = System.Exception; namespace BrilliantSightClient.ViewModel.Grading; /// /// 检测结果画面VM /// public class GradingResultVM : BaseViewModel { private static readonly ILog Logger = LogManager.GetLogger(typeof(GradingResultVM)); /// /// 钻石编码 /// private string DiamondCode { get; set; } private List _dtResults; // ViewportData private DataTable _dsList; private DataTable _gradeList; private ViewportData _viewportData; private string _standard; private string _shape; private string _crownType; private string _pavType; private string _wight; private string _cutLevelTotal; private string _symLevelTotal; private string _ds; private RowDetail _selRowDataDetail; private bool _isEnabled; public bool _isSaveCsv = false; /// /// 保存按钮状态 /// public bool isSaved = false; public ICommand SaveFileCommand { get; } public ICommand SaveAsCommand { get; } // 热敏标签打印 public ICommand ThermalPrintCommand { get; } private SerialPort _serialPort; /// /// 左侧计算结果展示数据 /// public List DtResults { get { return _dtResults; } set { _dtResults = value; OnPropertyChanged(nameof(DtResults)); } } /// /// 右侧钻石3D模型展示控件 /// public ViewportData ViewportData { get { return _viewportData; } set { _viewportData = value; OnPropertyChanged(nameof(ViewportData)); } } /// /// 画面上方定级标准 /// public string Standard { get { return _standard; } set { _standard = value; OnPropertyChanged(nameof(Standard)); } } /// /// 形状 /// public string Shape { get { return _shape; } set { _shape = value; OnPropertyChanged(nameof(Shape)); } } /// /// 冠面类型 /// public string CrownType { get { return _crownType; } set { _crownType = value; OnPropertyChanged(nameof(CrownType)); } } /// /// 亭面类型 /// public string PavType { get { return _pavType; } set { _pavType = value; OnPropertyChanged(nameof(PavType)); } } /// /// 画面明细展示数据 /// public RowDetail SelRowDataDetail { get { return _selRowDataDetail; } set { _selRowDataDetail = value; OnPropertyChanged(nameof(SelRowDataDetail)); } } /// /// 重量 /// public string Wight { get { return _wight; } set { _wight = value; OnPropertyChanged(nameof(Wight)); } } /// /// 切工等级(整体 画面上部显示) /// public string CutLevelTotal { get { return _cutLevelTotal; } set { _cutLevelTotal = value; OnPropertyChanged(nameof(CutLevelTotal)); } } /// /// 对称性等级(整体 画面上部显示) /// public string SymLevelTotal { get { return _symLevelTotal; } set { _symLevelTotal = value; OnPropertyChanged(nameof(SymLevelTotal)); if (!value.IsNullOrEmpty()) SaveToCsv(); } } /// /// 下拉列表DS /// public DataTable DSList { get { return _dsList; } set { _dsList = value; OnPropertyChanged(nameof(DSList)); } } /// /// 下拉列表DS 选择的值 /// public string DS { get { return _ds; } set { _ds = value; OnPropertyChanged(nameof(DS)); saveTempDS(value); } } /// /// 定级下拉列表 /// public DataTable GradeList { get { return _gradeList; } set { _gradeList = value; OnPropertyChanged(nameof(GradeList)); } } /// /// 保存和导出的按钮可用性 /// public bool IsEnabled { get{ return _isEnabled; } set { _isEnabled = value; OnPropertyChanged(nameof(IsEnabled)); } } /// /// 切工总等级(辅助计算用) /// private int totalCutGrade = 0; /// /// 对称行总等级(辅助计算用) /// private decimal totalSymGrade = 0; /// /// 计算数据 /// private AlgorithmResultEntity algorithmResult; /// /// 用户名 /// private string username = ""; /// /// 机器号 /// private string machine = ""; /// /// 形状id /// private string shapeId = string.Empty; /// /// 规则id /// private string ruleId = string.Empty; /// /// 构造 /// /// 检测结果 public GradingResultVM(object? result) { try { SaveAsCommand = new RelayCommand(SaveAs); SaveFileCommand = new RelayCommand(SaveFile); // 热敏标签打印 ThermalPrintCommand = new RelayCommand(ExecuteThermalPrint); // 初始化 SerialPort // InitializeSerialPort(); if (result != null) { algorithmResult = result as AlgorithmResultEntity?? new AlgorithmResultEntity(); // ViewDataInfoHelper.GenerateDataInfos(algorithmResult); InitView(algorithmResult); machine = algorithmResult.DeviceId; username = Settings.SelectValueById("PERMISSIONS"); IsEnabled = true; if (algorithmResult.Status.Equals(StatusCodes.Recheck)) IsEnabled = false; } DS = ConfigurationHelper.ReadConfigValue("DSSet"); if (shapeId.Equals("ROUND")) { if (IsEnabled) { AutoSave(); } SaveTestResult(SaveStatus.AutoSave); SaveToCsv(); } }catch(IOException) { throw; } catch (Exception ex) { Logger.Error($"全局异常捕获:{ex.Message}", ex); throw ex; } } #region 画面初始化相关操作 [Log] private void InitCombobox() { // DS下拉列表初始化 InitDSlist(); // string sql = $"SELECT GRADE_NAME AS NAME, GRADE_EN_S_NAME AS EN_NAME, GRADE_EN_NAME AS EN_ALL_NAME, GRADE_ORDER FROM GRADE WHERE SHAPE_ID = '{shapeId}' AND RULE_ID LIKE '{ruleId}%' GROUP BY GRADE_NAME,GRADE_EN_NAME,GRADE_ORDER ORDER BY GRADE_ORDER; "; // GradeList = DataBaseHelper.ExecuteQuery(sql); DataTable dt = new DataTable(); dt.TableName = "GRADE"; dt.Columns.Add("NAME"); dt.Columns.Add("EN_NAME"); dt.Columns.Add("EN_ALL_NAME"); dt.Columns.Add("GRADE_ORDER"); if (ViewDataInfoHelper.levelCalculator != null && ViewDataInfoHelper.levelCalculator.IsInitialized) { foreach (var gradeSet in ViewDataInfoHelper.levelCalculator.GradeLevelSymSets) { DataRow dr = dt.NewRow(); dr["NAME"] = gradeSet.Name; dr["EN_NAME"] = gradeSet.AName; dr["EN_ALL_NAME"] = gradeSet.EName; dr["GRADE_ORDER"] = gradeSet.Short; dt.Rows.Add(dr); } } GradeList = dt; } [Log] private void InitViewportData(AlgorithmResultEntity result) { Dictionary colorProperty = new Dictionary(); colorProperty.Add("FACET_COLOR", "MainFacetColor"); colorProperty.Add("BORDER_COLOR", "MainBorderColor"); colorProperty.Add("SELECTED_FACET_COLOR", "SelFacetColor"); colorProperty.Add("SELECTED BORDER COLOR", "SelBorderColor"); colorProperty.Add("SELECTED_TYPE_COLOR", "SelTypeColor"); colorProperty.Add("SELECTED_FONT_COLOR", "SelFontColor"); colorProperty.Add("RULER_COLOR", "SelLineColor"); colorProperty.Add("ARROW_COLOR", "SelFrontColor"); colorProperty.Add("BLEMISH_FACET_COLOR", "ErrFacetColor"); colorProperty.Add("TABLE_FACET_COLOR", "TableFacetColor"); colorProperty.Add("UPPER_MAIN_FACET_COLOR", "UpperMainFacetColor"); colorProperty.Add("STAR_FACET_COLOR", "StarFacetColor"); colorProperty.Add("UPPER_GIRDLE_FACET_COLOR", "UpperGirdleFacetColor"); colorProperty.Add("GIRDLE_FACET_COLOR", "GirdleFacetColor"); colorProperty.Add("PAVILION_MAIN_FACET_COLOR", "PavilionFacetColor"); colorProperty.Add("LOWER_GIRDLE_FACET_COLOR", "LowerGirdleFacetColor"); colorProperty.Add("CULET_COLOR", "CuletFacetColor"); ColorConfigEntity colorConfigEntity = new ColorConfigEntity(); Type type = colorConfigEntity.GetType(); foreach (var property in colorProperty) { var value = Settings.SelectValueById(property.Key); PropertyInfo? p = type.GetProperty(property.Value); if (p != null && !string.IsNullOrEmpty(value)) { p.SetValue(colorConfigEntity, CommonHelper.HexToColor4(value)); } } string data = JsonConvert.SerializeObject(result); ViewportData = new ViewportData(result.DiamondCode, data,colorConfigEntity); ViewportData.LoadData(); } [Log] private void InitDSlist() { DSList = new DataTable(); DSList.Columns.Add("Key"); DSList.Columns.Add("Value"); DSList.Rows.Add("N/A", "NA"); DSList.Rows.Add("pass", "pass"); DSList.Rows.Add("refer", "refer"); } [Log] public void SaveToCsv() { try { if (_isSaveCsv) { return; } string strBaseUrl = AppDomain.CurrentDomain.BaseDirectory; string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "csv", "histroy.csv"); var info = algorithmResult.Measurements; string line = $"{DiamondCode}," + $"{Wight}," + $"{DoubleDataFormatHelper.FormatDouble_A2(info.M1)}," + $"{DoubleDataFormatHelper.FormatDouble_A2(info.M2)}," + $"{DoubleDataFormatHelper.FormatDouble_A2(info.M3)}," + $"{DoubleDataFormatHelper.FormatDouble_P2(info.TABLE)}," + $"{DoubleDataFormatHelper.FormatDouble_P2(info.CROWN_HEIGHT)}," + $"{DoubleDataFormatHelper.FormatDouble_P2(info.PAV_DEPTH)}," + $"{DoubleDataFormatHelper.FormatDouble_P2(info.TOTAL_DEPTH)}," + $"{DoubleDataFormatHelper.FormatDouble_A2(info.CROWN_ANGLE)}," + $"{DoubleDataFormatHelper.FormatDouble_A2(info.PAV_ANGLE)}," + $"{DoubleDataFormatHelper.FormatDouble_A2(info.CULET_SIZE)}," + $"{DoubleDataFormatHelper.FormatDouble_P2(info.GIRDLE)}," + $"{calGirdleName(info)}," + $"," + $"{GetGradeEnName(GetGradeOrder(SymLevelTotal))}," + $"{GetGradeEnName(GetGradeOrder(CutLevelTotal))}"; if (File.Exists(filePath)) { using (var writer = new StreamWriter(filePath, true)) { writer.WriteLine(line); } } else { File.Create(filePath).Close(); string header = string.Empty; if ("en".Equals(MultilingualHelper.getLangType())) { header = "Diamond Code,Wight(ct),Measurement1(mm), Measurement2(mm), Measurement3(mm), Table(%), Crown Height(%),Pavilion Depth(%), Total Depth(%),Crown Angle(°), Pavilion Angle(°),Culet Size(mm), Girdle Percent(%),Girdle Name, POL or Pol/ Sym,SYM,CUT - PROP"; } else { header = "钻石编码,预估重量(克拉),长(毫米), 宽(毫米), 高(毫米), 台宽比(%), 冠高比(%),亭深比(%), 全深比(%),冠角(°), 亭角(°),底尖偏心(mm), 腰厚比(%),腰厚分级, 修饰度,对称性,切工比例"; } // string header = // "Diamond Code,Wight,Measurement1, Measurement2, Measurement3, Table, Crown Height,Pavilion Depth, Total Depth,Crown Angle, Pavilion Angle,Culet Size, Girdle Percent,Girdle Name, POL or Pol/ Sym,SYM,CUT - PROP"; using (var writer = new StreamWriter(filePath, true)) { writer.WriteLine(header); writer.WriteLine(line); } } _isSaveCsv = true; } catch (Exception ex) { Logger.Error($"Auto Save Error: {ex.Message}"); } } [Log] private void saveTempDS(string selValue) { ConfigurationHelper.SetConfigValue("DSSet",selValue); } [Log] private void InitView(AlgorithmResultEntity result) { try { InitViewportData(result); totalCutGrade = 0; totalSymGrade = 0; ruleId = getRuleId(); Standard = result.Standard; shapeId = result.Shape; Shape = GetName(result.Shape); CrownType = result.CrownType; PavType = result.PavType; DiamondCode = result.DiamondCode; CalWight(result); if (shapeId.Equals("ROUND")) { var data = ViewDataInfoHelper.GenerateDataInfos(result); InitCombobox(); DtResults = data; // CutLevelTotal = GetGradeName(totalCutGrade); var totalCutLevel = ViewDataInfoHelper.levelCalculator.GetCutTotalGradeLevelSet(data); CutLevelTotal = ViewDataInfoHelper.MultilingualLevelSet(totalCutLevel); }else if (shapeId.Equals("OVAL")) { var data = ViewDataInfoHelper.GenerateDataInfos(result); InitDSlist(); DtResults = data; } } catch (Exception ex) { new MessageBox().Show($"{MultilingualHelper.getString("ApplicationError")}{ex.Message}"); Logger.Error($"全局异常捕获:{ex.Message}", ex); } } [Log] private string getRuleId() { return Settings.SelectValueById("RuleId"); } #endregion #region 定级计算 [Log] private string getActualRuleId() { string ruleIdForSelect = ""; if (ruleId.StartsWith("IGI")) { ruleIdForSelect = ruleId; } else if (ruleId.StartsWith("GB")) { double ta = algorithmResult.Measurements.TABLE * 100; ta = (DoubleDataFormatHelper.RoundFiveDownSixUp(ta * 2) / 2); if (ta < 49) { ruleIdForSelect = ruleId + "_TA_49"; } else if (ta > 71) { ruleIdForSelect = ruleId + "_TA_71"; } else { ruleIdForSelect = ruleId + "_TA_" + Math.Floor(ta); } } else { ruleIdForSelect = ruleId; } return ruleIdForSelect; } [Log] private List GetCalGradeInfos(string item) { string ruleIdForSelect = getActualRuleId(); string sql = $"Select GRADE_ORDER as gradeOrder,CAST(STANDARD_MIN AS NUMERIC) Min, CAST(STANDARD_MAX AS NUMERIC) Max,IS_MAX_EXIST as isMaxExist,IS_MIN_EXIST as isMinExist from STANDARD where TEST_ITEM_ID = '{item}' AND SHAPE_ID = UPPER('{shapeId}') AND RULE_ID = '{ruleIdForSelect}' "; List calGrades = DataBaseHelper.ExecuteQuery(sql); return calGrades; } [Log] private List GetCalGradeInfos_SYM(string item) { string ruleIdForSelect = getActualRuleId(); string sql = $"Select GRADE_ORDER as gradeOrder,CAST(STANDARD_MIN AS NUMERIC) Min, CAST(STANDARD_MAX AS NUMERIC) Max,IS_MAX_EXIST as isMaxExist,IS_MIN_EXIST as isMinExist from SYM_STANDARD where TEST_ITEM_ID = '{item}' AND SHAPE_ID = UPPER('{shapeId}') AND RULE_ID = '{ruleIdForSelect}' "; List calGrades = DataBaseHelper.ExecuteQuery(sql); return calGrades; } #endregion [Log] private double CalWight(AlgorithmResultEntity result) { // var M1 = result.Measurements.M1; // var M2 = result.Measurements.M2; // var M3 = result.Measurements.M3; // var wight = Square((M1+M2)/2)*M3*0.0061; var VOLUME = result.Measurements.VOLUME; var wight = VOLUME/57; Wight = wight.ToString("f3"); return wight; } [Log] private void AutoSave() { if (!Directory.Exists(getFilePath())) { //new MessageBox().Show(MultilingualHelper.getString("SavePathIsnotExists")); //return; throw new DirectoryNotFoundException(getFilePath()); } string fullPath = Path.Combine(getFilePath(), string.IsNullOrEmpty(DiamondCode)?"temp":DiamondCode); if (FileSaveEnabled("Txt")) { TxtFile(fullPath); } if (FileSaveEnabled("Excel")) { ExcelFile(fullPath); } } [Log] public void SaveFile(object param) { if (string.IsNullOrEmpty(DiamondCode)) { MessageBox messageBox = new MessageBox(); MessageBoxResult boxResult = messageBox.ShowInput(MultilingualHelper.getString("UpdateDiamondCode"), out string inputStr, MultilingualHelper.getString("ok"), MultilingualHelper.getString("Cancel") ); if (boxResult == MessageBoxResult.OK && inputStr.Length > 0) { this.DiamondCode = inputStr; } else { return; } } if (!Directory.Exists(getFilePath())) { new MessageBox().Show(MultilingualHelper.getString("FilePathNotExists")); return; } string fullPath = Path.Combine(getFilePath(), this.DiamondCode); ExportFile(fullPath); SaveTestResult(SaveStatus.Save); isSaved = true; } [Log] private string getFilePath() { string defultFilePath = ""; string sql = $"SELECT SETTING_P FROM SETTING WHERE SETTING_ID = 'FilePath'"; DataTable data = DataBaseHelper.ExecuteQuery(sql); if (data!= null && data.Rows.Count>0) { defultFilePath = data.Rows[0]["SETTING_P"].ToString(); } if(File.Exists(defultFilePath)){ return defultFilePath; } else { try { Directory.CreateDirectory(defultFilePath); } catch (Exception ex) { Logger.Error($"全局异常捕获:{ex.Message}", ex); } return defultFilePath; } } #region 文件导出相关 [Log] public void SaveAs(object param) { try { if (string.IsNullOrEmpty(DiamondCode)) { MessageBox messageBox = new MessageBox(); MessageBoxResult boxResult = messageBox.ShowInput(MultilingualHelper.getString("UpdateDiamondCode"), out string inputStr, MultilingualHelper.getString("ok"), MultilingualHelper.getString("Cancel") ); if (boxResult == MessageBoxResult.OK && inputStr.Length > 0) { this.DiamondCode = inputStr; } else { return; } } using (var folderBrowserDlg = new FolderBrowserDialog()) { // 创建SaveFileDialog实例 SaveFileDialog saveFileDialog = new() { Filter = "所有文件 (*.*)|*.*", // 文件类型过滤器 FileName = this.DiamondCode // 默认文件名 }; // 显示对话框并检查结果 bool? result = saveFileDialog.ShowDialog(); if (result == true) { // 获取用户选择的文件路径 string filePath = saveFileDialog.FileName; if (!saveFileDialog.CheckPathExists) { new MessageBox().Show(MultilingualHelper.getString("FilePathNotExists")); return; } //ExportFile(filePath); if (filePath.ToLower().EndsWith(".txt")) { filePath = filePath.Substring(0,filePath.Length-4); } TxtFile(filePath); } } SaveTestResult(SaveStatus.SaveAs); //PrintLabel(); } catch (Exception ex) { new MessageBox().Show($"{MultilingualHelper.getString("ApplicationError")}{ex.Message}"); Logger.Error($"全局异常捕获:{ex.Message}", ex); } } [Log] private async void ExportFile(string filePath) { ExportDialog exportDialog = new ExportDialog(); try { var tcs = new TaskCompletionSource(); var progressTask = Task.Run(() => Application.Current.Dispatcher.Invoke(() => { exportDialog.Closed += (s, e) => tcs.SetResult(true); exportDialog.ShowDialog(); } )); await Task.Run(async () => { int count = saveFileCount(); int index = 1; if (FileSaveEnabled("Txt")) { exportDialog.Dispatcher.Invoke(() => { exportDialog.setValue($"Txt File({index++}/{count})"); }); TxtFile(filePath); } if (FileSaveEnabled("Excel")) { exportDialog.Dispatcher.Invoke(() => { exportDialog.setValue($"Excel File({index++}/{count})"); }); ExcelFile(filePath); } if (FileSaveEnabled("Stl")) { exportDialog.Dispatcher.Invoke(() => { exportDialog.setValue($"STL File({index++}/{count})"); }); await Task.Delay(100); STLFile(filePath); } if (FileSaveEnabled("Dat")) { exportDialog.Dispatcher.Invoke(() => { exportDialog.setValue($"DAT File({index++}/{count})"); }); await DatFile(filePath); } exportDialog.Dispatcher.Invoke(() => { exportDialog.setValue("Success"); }); //DataConver(filePath); // exportDialog.Dispatcher.Invoke(() => // { // exportDialog.setValue("Success"); // }); }); await Task.Delay(500); } catch (IOException ex) { new MessageBox().Show($"{MultilingualHelper.getString("FileOpened")}:{ex.Message}"); } catch(Exception ex) { new MessageBox().Show($"{MultilingualHelper.getString("ApplicationError")}{ex.Message}"); Logger.Error($"全局异常捕获:{ex.Message}", ex); } finally { exportDialog.Close(); } } [Log] private bool FileSaveEnabled(string Key) { bool result = false; string sql = $"SELECT SETTING_P FROM SETTING WHERE SETTING_ID = '{Key}FileChecked'"; DataTable data = DataBaseHelper.ExecuteQuery(sql); if (data != null && data.Rows.Count>0) { bool.TryParse(data.Rows[0]["SETTING_P"].ToString(),out result); } return result; } [Log] private int saveFileCount() { int result = 0; string sql = $"SELECT SETTING_P FROM SETTING WHERE SETTING_ID LIKE '%FileChecked'"; DataTable data = DataBaseHelper.ExecuteQuery(sql); if (data != null) { result = data.Rows.Count; } return result; } /// /// txt文件导出 /// /// [Log] private void TxtFile(string filePath) { try { string fileName = filePath + ".txt"; using (var file = File.Create(fileName)) { Measurements info = algorithmResult.Measurements; StreamWriter stream = new StreamWriter(file); stream.WriteLine($"IGI REPORT NUMBER={DiamondCode}"); stream.WriteLine($"SARIN WEIGHT={Double.Parse(Wight).ToString("f3")}"); stream.WriteLine($"M1={info.M1.ToString("f2")}"); stream.WriteLine($"M2={info.M2.ToString("f2")}"); stream.WriteLine($"M3={info.M3.ToString("f2")}"); stream.WriteLine($"TABLE={(info.TABLE * 100).ToString("F1")}"); stream.WriteLine($"TABLE MIN={(info.TABLE_MIN * 100).ToString("F1")}"); stream.WriteLine($"TABLE MAX={(info.TABLE_MAX * 100).ToString("F1")}"); stream.WriteLine($"CROWN HEIGHT={(info.CROWN_HEIGHT * 100).ToString("F1")}"); stream.WriteLine($"CROWN H MIN={(info.CROWN_H_MIN * 100).ToString("F1")}"); stream.WriteLine($"CROWN H MAX={(info.CROWN_H_MAX * 100).ToString("F1")}"); stream.WriteLine($"CROWN ANGLE={(info.CROWN_ANGLE).ToString("F1")}"); stream.WriteLine($"CROWN ANGLE MIN={(info.CROWN_ANGLE_MIN).ToString("F1")}"); stream.WriteLine($"CROWN ANGLE MAX={(info.CROWN_ANGLE_MAX).ToString("F1")}"); stream.WriteLine($"PAV DEPTH={(info.PAV_DEPTH * 100).ToString("F1")}"); stream.WriteLine($"PAV DEPTH MIN={(info.PAV_DEPTH_MIN * 100).ToString("F1")}"); stream.WriteLine($"PAV DEPTH MAX={(info.PAV_DEPTH_MAX * 100).ToString("F1")}"); stream.WriteLine($"PAV ANGLE={(info.PAV_ANGLE).ToString("F1")}"); stream.WriteLine($"PAV ANGLE MIN={(info.PAV_ANGLE_MIN).ToString("F1")}"); stream.WriteLine($"PAV ANGLE MAX={(info.PAV_ANGLE_MAX).ToString("F1")}"); //部署值修改 stream.WriteLine($"GIRDLE={(info.GIRDLE_BEZEL * 100).ToString("F1")}"); stream.WriteLine($"GIRDLE MIN={(info.GIRDLE_BEZEL_MIN * 100).ToString("F1")}"); stream.WriteLine($"GIRDLE MAX={(info.GIRDLE_BEZEL_MAX * 100).ToString("F1")}"); stream.WriteLine($"TOTAL DEPTH={(info.TOTAL_DEPTH * 100).ToString("F1")}"); stream.WriteLine($"CULET={(info.CULET*100).ToString("F1")}"); stream.WriteLine($"MACHINE={machine}"); stream.WriteLine($"CUTGRADE={GetGradeEnName(totalCutGrade.ToString())}"); stream.WriteLine($"LW RATIO={info.LW_RATIO}"); stream.WriteLine($"DS={DS}"); stream.WriteLine($"COC={(info.COC * 100).ToString("F1")}"); stream.WriteLine($"USER={username}"); string TABLE_GRADE = DtResults.Where(x => "TABLE".Equals(x.TestItemId)).Select(x=>x.CutLevel).First()??""; stream.WriteLine($"TABLE GRADE={GetGradeEnName(GetGradeOrder(TABLE_GRADE))}"); string CROWN_H_GRADE = DtResults.Where(x => "CROWN_HEIGHT".Equals(x.TestItemId)).Select(x => x.CutLevel).First() ?? ""; stream.WriteLine($"CROWN H GRADE={GetGradeEnName(GetGradeOrder(CROWN_H_GRADE))}"); string CROWN_ANGLE_GRADE = DtResults.Where(x => "CROWN_ANGLE".Equals(x.TestItemId)).Select(x => x.CutLevel).First() ?? ""; stream.WriteLine($"CROWN ANGLE GRADE={GetGradeEnName(GetGradeOrder(CROWN_ANGLE_GRADE))}"); string PAV_DEPTH_GRADE = DtResults.Where(x => "PAV_DEPTH".Equals(x.TestItemId)).Select(x => x.CutLevel).First() ?? ""; stream.WriteLine($"PAV DEPTH GRADE={GetGradeEnName(GetGradeOrder(PAV_DEPTH_GRADE))}"); string PAV_ANGLE_GRADE = DtResults.Where(x => "PAV_ANGLE".Equals(x.TestItemId)).Select(x => x.CutLevel).First() ?? ""; stream.WriteLine($"PAV ANGLE GRADE={GetGradeEnName(GetGradeOrder(PAV_ANGLE_GRADE))}"); string TD_GRADE = DtResults.Where(x => "TOTAL_DEPTH".Equals(x.TestItemId)).Select(x => x.CutLevel).First() ?? ""; stream.WriteLine($"TD GRADE={GetGradeEnName(GetGradeOrder(TD_GRADE))}"); stream.WriteLine($"TA={info.TA.ToString("F1")}"); stream.WriteLine($"LGF={(info.LGF * 100).ToString("F1")}"); stream.WriteLine($"STAR={(info.STAR * 100).ToString("F1")}"); stream.Close(); } } catch (Exception ex) { new MessageBox().Show($"{MultilingualHelper.getString("ApplicationError")}{ex.Message}"); Logger.Error($"全局异常捕获:{ex.Message}", ex); } } /// /// excel文件导出 /// /// [Log] private void ExcelFile(string filePath) { string fileName = filePath + ".xlsx"; try { IWorkbook workbook = new XSSFWorkbook(); ISheet sheet = workbook.CreateSheet("Sheet1"); int col = 0; int row = 0; var dataRow = sheet.CreateRow(row); dataRow.CreateCell(col++).SetCellValue("Measurement1"); dataRow.CreateCell(col++).SetCellValue("Measurement2"); dataRow.CreateCell(col++).SetCellValue("Measurement3"); dataRow.CreateCell(col++).SetCellValue("Table"); dataRow.CreateCell(col++).SetCellValue("Crown Height"); dataRow.CreateCell(col++).SetCellValue("Pavilion Depth"); dataRow.CreateCell(col++).SetCellValue("Total Depth"); dataRow.CreateCell(col++).SetCellValue("Crown Angle"); dataRow.CreateCell(col++).SetCellValue("Pavilion Angle"); dataRow.CreateCell(col++).SetCellValue("Culet Size"); dataRow.CreateCell(col++).SetCellValue("Girdle Percent"); dataRow.CreateCell(col++).SetCellValue("Girdle Name"); dataRow.CreateCell(col++).SetCellValue("POL or Pol/Sym"); dataRow.CreateCell(col++).SetCellValue("SYM"); dataRow.CreateCell(col++).SetCellValue("CUT-PROP"); row++; col = 0; dataRow = sheet.CreateRow(row); Measurements info = algorithmResult.Measurements; dataRow.CreateCell(col++).SetCellValue($"{DoubleDataFormatHelper.FormatDouble_A2(info.M1)}(mm)"); dataRow.CreateCell(col++).SetCellValue($"{DoubleDataFormatHelper.FormatDouble_A2(info.M2)}(mm)"); dataRow.CreateCell(col++).SetCellValue($"{DoubleDataFormatHelper.FormatDouble_A2(info.M3)}(mm)"); dataRow.CreateCell(col++).SetCellValue($"{DoubleDataFormatHelper.FormatDouble_P2(info.TABLE)}%"); dataRow.CreateCell(col++).SetCellValue($"{DoubleDataFormatHelper.FormatDouble_P2(info.CROWN_HEIGHT)}%"); dataRow.CreateCell(col++).SetCellValue($"{DoubleDataFormatHelper.FormatDouble_P2(info.PAV_DEPTH)}%"); dataRow.CreateCell(col++).SetCellValue($"{DoubleDataFormatHelper.FormatDouble_P2(info.TOTAL_DEPTH)}%"); dataRow.CreateCell(col++).SetCellValue($"{DoubleDataFormatHelper.FormatDouble_A2(info.CROWN_ANGLE)}°"); dataRow.CreateCell(col++).SetCellValue($"{DoubleDataFormatHelper.FormatDouble_A2(info.PAV_ANGLE)}°"); dataRow.CreateCell(col++).SetCellValue($"{DoubleDataFormatHelper.FormatDouble_A2(info.CULET_SIZE)}(mm)"); dataRow.CreateCell(col++).SetCellValue($"{DoubleDataFormatHelper.FormatDouble_P2(info.GIRDLE)}%"); // 腰部厚度英文 dataRow.CreateCell(col++).SetCellValue($"{calGirdleName(info)}"); dataRow.CreateCell(col++).SetCellValue($""); string sysmlevel = ""; if (!string.IsNullOrEmpty(SymLevelTotal)) { sysmlevel = GetGradeEnName(GetGradeOrder(SymLevelTotal ?? "")); } dataRow.CreateCell(col++).SetCellValue($"{sysmlevel}"); dataRow.CreateCell(col++).SetCellValue($"{GetGradeEnNameByAName(CutLevelTotal)}"); // 保存Excel文件 using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { workbook.Write(stream); } } catch (IOException) { throw new IOException($"{fileName}"); } catch (Exception ex) { Logger.Error($"全局异常捕获:{ex.Message}", ex); throw; } } [Log] private string calGirdleName(Measurements info) { string girdleName = ""; // 有问题 问题1 1.6时为thin to slight thick,那么 thin为什么时刻出现 // 问题2 假如最小值为very thin,最大值为thick时用哪个 decimal min = Convert.ToDecimal(info.GIRDLE_MIN * 100); girdleName += calGirdleName(min,true); girdleName += " to "; decimal max = Convert.ToDecimal(info.GIRDLE_MAX * 100); girdleName += calGirdleName(max,false); return girdleName; } [Log] private string calGirdleName(decimal cValue,bool isMin) { string girdleName = ""; List calGrades = GetCalGradeInfos("GIRDLE"); int order = 1; bool isthin = false; bool isthick = false; foreach (CalGradeInfo gradeInfo in calGrades) { bool isThisGrade = true; if (gradeInfo.Max != null) { if (gradeInfo.isMaxExist == 1 && cValue.CompareTo(gradeInfo.Max) <= 0) { } else if (gradeInfo.isMaxExist == 0 && cValue.CompareTo(gradeInfo.Max) < 0) { } else { isthick = true; isThisGrade = false; } } if (gradeInfo.Min != null) { if (gradeInfo.isMinExist == 1 && cValue.CompareTo(gradeInfo.Min) >= 0) { } else if (gradeInfo.isMinExist == 0 && cValue.CompareTo(gradeInfo.Min) > 0) { } else { isthin = true; isThisGrade = false; } } if (isThisGrade) { break; } else { order++; } } Dictionary thinDic = new Dictionary(); thinDic.Add(1, "Thin"); thinDic.Add(2,"Thin"); thinDic.Add(3, "Very Thin"); thinDic.Add(4, "Extremely Thin"); Dictionary thickDic = new Dictionary(); thickDic.Add(1, "Slightly Thick"); thickDic.Add(2, "Slightly Thick"); thickDic.Add(3, "Thick"); thickDic.Add(4, "VeryThick"); if (order == 1) { if (isMin) { girdleName = thinDic[order]; } else { girdleName = thickDic[order]; } } else if (isthin) { if (order > 4) { girdleName = "Extremely Thin"; } else { girdleName = thinDic[order]; } } else if (isthick) { if (order > 4) { girdleName = "VeryThick"; } else { girdleName = thickDic[order]; } } return girdleName; } [Log] private async Task DatFile(string filePath) { //File.Create(filePath + ".dat").Close(); await ViewportData.SaveAsToVedioFile(filePath + ".mp4"); } [Log] private async Task STLFile(string filePath) { //File.Create(filePath + ".stl").Close(); await ViewportData.SaveAsToStlFile(filePath + ".stl"); } [Log] private void DataConver(string filePath) { //File.Create(filePath + ".stl").Close(); ViewportData.ConvertMp4ToDat(filePath + ".mp4",filePath + ".dat"); } #endregion #region 各类名称取得 [Log] private string GetName(string id) { return Name.getNameById(id).Trim(); } [Log] private string GetGradeName(decimal order) { string name = GradeList.AsEnumerable().Where(x => order.ToString().Equals(x["GRADE_ORDER"].ToString())) .Select(x=>x[MultilingualHelper.getString("NameType")].ToString()).FirstOrDefault(""); // DB没关联 // Dictionary dictionary = new(); // dictionary.Add(0, ""); // dictionary.Add(1,"极好"); // dictionary.Add(2, "很好"); // dictionary.Add(3, "好"); // dictionary.Add(4, "一般"); // dictionary.Add(5, "差"); // return dictionary[order]; return name; } [Log] private string GetGradeOrder(string Grade) { string order = GradeList.AsEnumerable().Where(x => Grade.Equals(x[MultilingualHelper.getString("NameType")].ToString())) .Select(x=>x["GRADE_ORDER"].ToString()).FirstOrDefault(""); // DB没关联 // Dictionary dictionary = new(); // dictionary.Add("极好", 1); // dictionary.Add("很好", 2); // dictionary.Add("好", 3); // dictionary.Add("一般", 4); // dictionary.Add("差", 5); // return dictionary[Grade]; return order; } [Log] private string GetGradeEnName(string order) { try { string name = GradeList.AsEnumerable().Where(x => order.Equals(x["GRADE_ORDER"].ToString())) .Select(x => x["EN_ALL_NAME"].ToString()).FirstOrDefault(""); return name ?? string.Empty; } catch (Exception ex) { return string.Empty; } } private string GetGradeEnNameByAName(string order) { var data = ViewDataInfoHelper.levelCalculator.GradeLevelCutSets.FirstOrDefault(x => x.AName.Equals(order)); if(data==null) data = ViewDataInfoHelper.levelCalculator.GradeLevelCutSets.FirstOrDefault(x => x.Name.Equals(order)); return data==null?string.Empty:data.EName; } #endregion /// /// 修改对称性等级 /// /// [Log] public void ChangeSym(object norm) { //&& x.TestItemId != "GIRDLE_BEZEL" && x.TestItemId != "GIRDLE_BONE" && x.TestItemId != "GIRDLE" try { decimal? order = this.DtResults.Where(x => x.TestItemId != "TWIST" && x.TestItemId != "GIRDLE_BEZEL" && x.TestItemId != "GIRDLE_BONE" && x.TestItemId != "GIRDLE") .Select(x => x.SymLevel).Max(); if (order.HasValue) { totalSymGrade = order.Value; SymLevelTotal = GetGradeName((decimal)order.Value); } else { SymLevelTotal = string.Empty; } } catch (Exception ex) { SymLevelTotal = string.Empty; } } [Log] public RowDetail getSelectData(string testItemId) { try { RowDetail row = new RowDetail(); row.itemName = GetName(testItemId); ViewportData.mockSel(testItemId); var data = DtResults.Where(x => x.TestItemId == testItemId).FirstOrDefault(); row.Avg = data != null ? data.Avg : ""; row.Dev = data != null ? data.Dev : ""; row.Max = data != null ? data.Max : ""; row.Min = data != null ? data.Min : ""; row.CutLevel = data != null ? data.CutLevel : ""; row.SymLevel = GetGradeName(data != null ? data.SymLevel ?? 0 : 0); setDetailItems(row, testItemId); this.SelRowDataDetail = row; return row; } catch (Exception ex) { Logger.Error($"虾集霸点:{ex.Message}"); return null; } } [Log] private void setDetailItems(RowDetail row,string TestItemId) { if ("DIAMETER".Equals(TestItemId)) { setDIAMETER_DETAIL(row); } else if ("TABLE".Equals(TestItemId)) { setTABLE_DETAIL(row); } else if ("CROWN_HEIGHT".Equals(TestItemId)) { setCROWN_HEIGHT_DETAIL(row); } else if ("CROWN_ANGLE".Equals(TestItemId)) { setCROWN_ANGLE_DETAIL(row); } else if ("PAV_DEPTH".Equals(TestItemId)) { setPAV_DEPTH_DETAIL(row); } else if ("PAV_ANGLE".Equals(TestItemId)) { setPAV_ANGLE_DETAIL(row); } else if ("GIRDLE_BEZEL".Equals(TestItemId)) { setGIRDLE_BEZEL_DETAIL(row); } else if ("GIRDLE_BONE".Equals(TestItemId)) { setGIRDLE_BONE_DETAIL(row); } else if ("GIRDLE".Equals(TestItemId)) { setGIRDLE_VALLEY_DETAIL(row); } else if ("STAR".Equals(TestItemId)) { setSTAR_DETAIL(row); } else if ("LOWER_HALVES_RATIO".Equals(TestItemId)) { setLOWER_HALVES_RATIO_DETAIL(row); } else if ("TWIST".Equals(TestItemId)) { setTWIST_DETAIL(row); } } [Log] private void calIndex(RowDetail row) { // 最大值的Index计算 if (row.Max.Equals(row.item1)) { row.MaxIndex = 0; } else if(row.Max.Equals(row.item2)) { row.MaxIndex = 1; } else if (row.Max.Equals(row.item3)) { row.MaxIndex = 2; } else if (row.Max.Equals(row.item4)) { row.MaxIndex = 3; } else if (row.Max.Equals(row.item5)) { row.MaxIndex = 4; } else if (row.Max.Equals(row.item6)) { row.MaxIndex = 5; } else if (row.Max.Equals(row.item7)) { row.MaxIndex = 6; } else if (row.Max.Equals(row.item8)) { row.MaxIndex = 7; } // 最小值的Index计算 if (row.Min.Equals(row.item1)) { row.MinIndex = 0; } else if (row.Min.Equals(row.item2)) { row.MinIndex = 1; } else if (row.Min.Equals(row.item3)) { row.MinIndex = 2; } else if (row.Min.Equals(row.item4)) { row.MinIndex = 3; } else if (row.Min.Equals(row.item5)) { row.MinIndex = 4; } else if (row.Min.Equals(row.item6)) { row.MinIndex = 5; } else if (row.Min.Equals(row.item7)) { row.MinIndex = 6; } else if (row.Min.Equals(row.item8)) { row.MinIndex = 7; } } [Log] private void setDIAMETER_DETAIL(RowDetail row) { DiameterDetail diameterDetail = algorithmResult.Measurements.DIAMETER_DETAIL; row.item1 = DoubleDataFormatHelper. FormatDouble_D(diameterDetail.DIAMETER_1); row.item2 = DoubleDataFormatHelper. FormatDouble_D(diameterDetail.DIAMETER_2); row.item3 = DoubleDataFormatHelper. FormatDouble_D(diameterDetail.DIAMETER_3); row.item4 = DoubleDataFormatHelper. FormatDouble_D(diameterDetail.DIAMETER_4); row.item5 = DoubleDataFormatHelper. FormatDouble_D(diameterDetail.DIAMETER_5); row.item6 = DoubleDataFormatHelper. FormatDouble_D(diameterDetail.DIAMETER_6); row.item7 = DoubleDataFormatHelper. FormatDouble_D(diameterDetail.DIAMETER_7); row.item8 = DoubleDataFormatHelper. FormatDouble_D(diameterDetail.DIAMETER_8); calIndex(row); } [Log] private void setTABLE_DETAIL(RowDetail row) { TableDetail diameterDetail = algorithmResult.Measurements.TABLE_DETAIL; row.item1 = DoubleDataFormatHelper.FormatDouble_P(diameterDetail.TABLE_1); row.item2 = DoubleDataFormatHelper.FormatDouble_P(diameterDetail.TABLE_2); row.item3 = DoubleDataFormatHelper.FormatDouble_P(diameterDetail.TABLE_3); row.item4 = DoubleDataFormatHelper.FormatDouble_P(diameterDetail.TABLE_4); calIndex(row); } [Log] private void setCROWN_HEIGHT_DETAIL(RowDetail row) { CrownHeightDetail crownHeightDetail = algorithmResult.Measurements.CROWN_HEIGHT_DETAIL; row.item1 = DoubleDataFormatHelper.FormatDouble_P(crownHeightDetail.CROWN_HEIGHT_1); row.item2 = DoubleDataFormatHelper.FormatDouble_P(crownHeightDetail.CROWN_HEIGHT_2); row.item3 = DoubleDataFormatHelper.FormatDouble_P(crownHeightDetail.CROWN_HEIGHT_3); row.item4 = DoubleDataFormatHelper.FormatDouble_P(crownHeightDetail.CROWN_HEIGHT_4); row.item5 = DoubleDataFormatHelper.FormatDouble_P(crownHeightDetail.CROWN_HEIGHT_5); row.item6 = DoubleDataFormatHelper.FormatDouble_P(crownHeightDetail.CROWN_HEIGHT_6); row.item7 = DoubleDataFormatHelper.FormatDouble_P(crownHeightDetail.CROWN_HEIGHT_7); row.item8 = DoubleDataFormatHelper.FormatDouble_P(crownHeightDetail.CROWN_HEIGHT_8); calIndex(row); } [Log] private void setCROWN_ANGLE_DETAIL(RowDetail row) { CrownAngleDetail crownAngleDetail = algorithmResult.Measurements.CROWN_ANGLE_DETAIL; row.item1 = DoubleDataFormatHelper.FormatDouble_A(crownAngleDetail.CROWN_ANGLE_1); row.item2 = DoubleDataFormatHelper.FormatDouble_A(crownAngleDetail.CROWN_ANGLE_2); row.item3 = DoubleDataFormatHelper.FormatDouble_A(crownAngleDetail.CROWN_ANGLE_3); row.item4 = DoubleDataFormatHelper.FormatDouble_A(crownAngleDetail.CROWN_ANGLE_4); row.item5 = DoubleDataFormatHelper.FormatDouble_A(crownAngleDetail.CROWN_ANGLE_5); row.item6 = DoubleDataFormatHelper.FormatDouble_A(crownAngleDetail.CROWN_ANGLE_6); row.item7 = DoubleDataFormatHelper.FormatDouble_A(crownAngleDetail.CROWN_ANGLE_7); row.item8 = DoubleDataFormatHelper.FormatDouble_A(crownAngleDetail.CROWN_ANGLE_8); calIndex(row); } [Log] private void setPAV_DEPTH_DETAIL(RowDetail row) { PavDepthDetail pavDepthDetail = algorithmResult.Measurements.PAV_DEPTH_DETAIL; row.item1 = DoubleDataFormatHelper.FormatDouble_P(pavDepthDetail.PAV_DEPTH_1); row.item2 = DoubleDataFormatHelper.FormatDouble_P(pavDepthDetail.PAV_DEPTH_2); row.item3 = DoubleDataFormatHelper.FormatDouble_P(pavDepthDetail.PAV_DEPTH_3); row.item4 = DoubleDataFormatHelper.FormatDouble_P(pavDepthDetail.PAV_DEPTH_4); row.item5 = DoubleDataFormatHelper.FormatDouble_P(pavDepthDetail.PAV_DEPTH_5); row.item6 = DoubleDataFormatHelper.FormatDouble_P(pavDepthDetail.PAV_DEPTH_6); row.item7 = DoubleDataFormatHelper.FormatDouble_P(pavDepthDetail.PAV_DEPTH_7); row.item8 = DoubleDataFormatHelper.FormatDouble_P(pavDepthDetail.PAV_DEPTH_8); calIndex(row); } [Log] private void setPAV_ANGLE_DETAIL(RowDetail row) { PavAngleDetail pavAngleDetail = algorithmResult.Measurements.PAV_ANGLE_DETAIL; row.item1 = DoubleDataFormatHelper.FormatDouble_A(pavAngleDetail.PAV_ANGLE_1); row.item2 = DoubleDataFormatHelper.FormatDouble_A(pavAngleDetail.PAV_ANGLE_2); row.item3 = DoubleDataFormatHelper.FormatDouble_A(pavAngleDetail.PAV_ANGLE_3); row.item4 = DoubleDataFormatHelper.FormatDouble_A(pavAngleDetail.PAV_ANGLE_4); row.item5 = DoubleDataFormatHelper.FormatDouble_A(pavAngleDetail.PAV_ANGLE_5); row.item6 = DoubleDataFormatHelper.FormatDouble_A(pavAngleDetail.PAV_ANGLE_6); row.item7 = DoubleDataFormatHelper.FormatDouble_A(pavAngleDetail.PAV_ANGLE_7); row.item8 = DoubleDataFormatHelper.FormatDouble_A(pavAngleDetail.PAV_ANGLE_8); calIndex(row); } [Log] private void setGIRDLE_BEZEL_DETAIL(RowDetail row) { GirdleBezelDetail girdleBezelDetail = algorithmResult.Measurements.GIRDLE_BEZEL_DETAIL; row.item1 = DoubleDataFormatHelper.FormatDouble_P(girdleBezelDetail.GIRDLE_BEZEL_1); row.item2 = DoubleDataFormatHelper.FormatDouble_P(girdleBezelDetail.GIRDLE_BEZEL_2); row.item3 = DoubleDataFormatHelper.FormatDouble_P(girdleBezelDetail.GIRDLE_BEZEL_3); row.item4 = DoubleDataFormatHelper.FormatDouble_P(girdleBezelDetail.GIRDLE_BEZEL_4); row.item5 = DoubleDataFormatHelper.FormatDouble_P(girdleBezelDetail.GIRDLE_BEZEL_5); row.item6 = DoubleDataFormatHelper.FormatDouble_P(girdleBezelDetail.GIRDLE_BEZEL_6); row.item7 = DoubleDataFormatHelper.FormatDouble_P(girdleBezelDetail.GIRDLE_BEZEL_7); row.item8 = DoubleDataFormatHelper.FormatDouble_P(girdleBezelDetail.GIRDLE_BEZEL_8); calIndex(row); } [Log] private void setGIRDLE_BONE_DETAIL(RowDetail row) { GirdleBoneDetail girdleBoneDetail = algorithmResult.Measurements.GIRDLE_BONE_DETAIL; row.item1 = DoubleDataFormatHelper.FormatDouble_P(girdleBoneDetail.GIRDLE_BONE_1); row.item2 = DoubleDataFormatHelper.FormatDouble_P(girdleBoneDetail.GIRDLE_BONE_2); row.item3 = DoubleDataFormatHelper.FormatDouble_P(girdleBoneDetail.GIRDLE_BONE_3); row.item4 = DoubleDataFormatHelper.FormatDouble_P(girdleBoneDetail.GIRDLE_BONE_4); row.item5 = DoubleDataFormatHelper.FormatDouble_P(girdleBoneDetail.GIRDLE_BONE_5); row.item6 = DoubleDataFormatHelper.FormatDouble_P(girdleBoneDetail.GIRDLE_BONE_6); row.item7 = DoubleDataFormatHelper.FormatDouble_P(girdleBoneDetail.GIRDLE_BONE_7); row.item8 = DoubleDataFormatHelper.FormatDouble_P(girdleBoneDetail.GIRDLE_BONE_8); calIndex(row); } [Log] private void setGIRDLE_VALLEY_DETAIL(RowDetail row) { GirdleValleyDetail girdleValleyDetail = algorithmResult.Measurements.GIRDLE_VALLEY_DETAIL; List doubles = new List(); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_1); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_2); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_3); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_4); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_5); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_6); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_7); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_8); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_9); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_10); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_11); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_12); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_13); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_14); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_15); doubles.Add(girdleValleyDetail.GIRDLE_VALLEY_16); doubles.Sort(); row.item1 = DoubleDataFormatHelper.FormatDouble_P2(doubles[0]); row.item2 = DoubleDataFormatHelper.FormatDouble_P2(doubles[1]); row.item3 = DoubleDataFormatHelper.FormatDouble_P2(doubles[2]); row.item4 = DoubleDataFormatHelper.FormatDouble_P2(doubles[3]); row.item5 = DoubleDataFormatHelper.FormatDouble_P2(doubles[12]); row.item6 = DoubleDataFormatHelper.FormatDouble_P2(doubles[13]); row.item7 = DoubleDataFormatHelper.FormatDouble_P2(doubles[14]); row.item8 = DoubleDataFormatHelper.FormatDouble_P2(doubles[15]); calIndex(row); } [Log] private void setSTAR_DETAIL(RowDetail row) { StarDetail starDetail = algorithmResult.Measurements.STAR_DETAIL; row.item1 = DoubleDataFormatHelper.FormatDouble_P(starDetail.STAR_1); row.item2 = DoubleDataFormatHelper.FormatDouble_P(starDetail.STAR_2); row.item3 = DoubleDataFormatHelper.FormatDouble_P(starDetail.STAR_3); row.item4 = DoubleDataFormatHelper.FormatDouble_P(starDetail.STAR_4); row.item5 = DoubleDataFormatHelper.FormatDouble_P(starDetail.STAR_5); row.item6 = DoubleDataFormatHelper.FormatDouble_P(starDetail.STAR_6); row.item7 = DoubleDataFormatHelper.FormatDouble_P(starDetail.STAR_7); row.item8 = DoubleDataFormatHelper.FormatDouble_P(starDetail.STAR_8); calIndex(row); } [Log] private void setLOWER_HALVES_RATIO_DETAIL(RowDetail row) { LowerHalvesRatioDetail lowerHalvesRatioDetail = algorithmResult.Measurements.LOWER_HALVES_RATIO_DETAIL; row.item1 = DoubleDataFormatHelper.FormatDouble_P(lowerHalvesRatioDetail.LOWER_HALVES_RATIO_1); row.item2 = DoubleDataFormatHelper.FormatDouble_P(lowerHalvesRatioDetail.LOWER_HALVES_RATIO_2); row.item3 = DoubleDataFormatHelper.FormatDouble_P(lowerHalvesRatioDetail.LOWER_HALVES_RATIO_3); row.item4 = DoubleDataFormatHelper.FormatDouble_P(lowerHalvesRatioDetail.LOWER_HALVES_RATIO_4); row.item5 = DoubleDataFormatHelper.FormatDouble_P(lowerHalvesRatioDetail.LOWER_HALVES_RATIO_5); row.item6 = DoubleDataFormatHelper.FormatDouble_P(lowerHalvesRatioDetail.LOWER_HALVES_RATIO_6); row.item7 = DoubleDataFormatHelper.FormatDouble_P(lowerHalvesRatioDetail.LOWER_HALVES_RATIO_7); row.item8 = DoubleDataFormatHelper.FormatDouble_P(lowerHalvesRatioDetail.LOWER_HALVES_RATIO_8); calIndex(row); } [Log] private void setTWIST_DETAIL(RowDetail row) { TwistDetail twistDetail = algorithmResult.Measurements.TWIST_DETAIL; row.item1 = DoubleDataFormatHelper.FormatDouble_A(twistDetail.TWIST_1); row.item2 = DoubleDataFormatHelper.FormatDouble_A(twistDetail.TWIST_2); row.item3 = DoubleDataFormatHelper.FormatDouble_A(twistDetail.TWIST_3); row.item4 = DoubleDataFormatHelper.FormatDouble_A(twistDetail.TWIST_4); row.item5 = DoubleDataFormatHelper.FormatDouble_A(twistDetail.TWIST_5); row.item6 = DoubleDataFormatHelper.FormatDouble_A(twistDetail.TWIST_6); row.item7 = DoubleDataFormatHelper.FormatDouble_A(twistDetail.TWIST_7); row.item8 = DoubleDataFormatHelper.FormatDouble_A(twistDetail.TWIST_8); calIndex(row); } #region 履历保存 [Log] private void SaveTestResult(SaveStatus saveStatus) { string ALGORITHM_RESULT = JsonConvert.SerializeObject(algorithmResult); string DATA_RESULT = JsonConvert.SerializeObject(DtResults); string STATUS = saveStatus.ToString(); string STONE_ID = DiamondCode; string TIMESTAMPVALUE = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:fff"); string sql = $"INSERT INTO TEST_RESULT (GUID,ALGORITHM_RESULT,DATA_RESULT,STATUS,STONE_ID,TIMESTAMPVALUE)VALUES" + $"('{Guid.NewGuid()}','{ALGORITHM_RESULT}','{DATA_RESULT}','{STATUS}','{STONE_ID}','{TIMESTAMPVALUE}');"; DataBaseHelper.ExecuteNonQuery(sql); } #endregion // 执行热敏打印的方法 [Log] private void ExecuteThermalPrint(object parameter) { if (Common.RunMode == 1) { new MessageBox().Show("打印功能不可用"); return; } Microsoft.Office.Interop.Excel.Application excelApp = null; string tempFilePath = string.Empty; try { MessageBox messageBox = new MessageBox(); MessageBoxResult boxResult = messageBox.ShowAsk(MultilingualHelper.getString("YesOrNo")); if (boxResult != MessageBoxResult.OK) { return; } // 步骤2:加载模板并填充数据 tempFilePath = GenerateTempExcelFile(); // 步骤3:使用Excel Interop静默打印 excelApp = new Microsoft.Office.Interop.Excel.Application(); excelApp.Visible = false; // 不显示Excel窗口 excelApp.DisplayAlerts = false; // 禁用警告提示 Microsoft.Office.Interop.Excel.Workbook workbook = excelApp.Workbooks.Open(tempFilePath); string printName = ConfigurationHelper.ReadConfigValue("PrintName"); string? targetPrinter = System.Drawing.Printing.PrinterSettings.InstalledPrinters .Cast() .FirstOrDefault(p => p.Contains(printName)); if (targetPrinter == null) { throw new Exception($"未找到打印机{printName}"); } // 打印配置 workbook.PrintOut( Copies: 1, Preview: false, ActivePrinter: targetPrinter ); // 关闭工作簿(不保存修改) workbook.Close(SaveChanges: false); } catch (Exception ex) { new MessageBox().Show($"打印失败: {ex.Message}"); } finally { // 步骤4:清理资源 if (excelApp != null) { excelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); } // 删除临时文件 if (File.Exists(tempFilePath)) { File.Delete(tempFilePath); } } } [Log] private string GenerateTempExcelFile() { try { string TemplatePath = @"Resource\ResultReport.xlsx"; using (FileStream templateStream = new FileStream(TemplatePath, FileMode.Open, FileAccess.Read)) { IWorkbook workbook = new XSSFWorkbook(templateStream); ISheet sheet = workbook.GetSheetAt(0); //Row 1 SetCellValue(sheet, "A1", $"{MultilingualHelper.getString("Organization")}:{Standard}"); SetCellValue(sheet, "B1", $"{MultilingualHelper.getString("DiamondResultShape")}:{Shape}"); SetCellValue(sheet, "C1", $"{MultilingualHelper.getString("Code")}:{DiamondCode}"); SetCellValue(sheet, "E1", $"{MultilingualHelper.getString("Wight")}:{Wight}ct."); //Row 2 SetCellValue(sheet, "A2", $"{MultilingualHelper.getString("Parameters")}"); SetCellValue(sheet, "B2", $"{MultilingualHelper.getString("DiamondResultGridAvgValue")}"); SetCellValue(sheet, "C2", $"{MultilingualHelper.getString("Interval")}(Min~Max)"); SetCellValue(sheet, "D2", $"{MultilingualHelper.getString("DiamondResultGridCutLevel")}"); SetCellValue(sheet, "E2", $"{MultilingualHelper.getString("DiamondResultSymmetryGrade")}"); //Row 3 var row3 = getSelectData("DIAMETER"); SetCellValue(sheet, "A3", $"{GetName("DIAMETER")}(mm)"); SetCellValue(sheet, "B3", $"{row3.Avg}"); SetCellValue(sheet, "C3", $"({row3.Min}~{row3.Max})"); SetCellValue(sheet, "D3", "--"); SetCellValue(sheet, "E3", $"{row3.SymLevel}"); //Row 4 var row4 = getSelectData("TOTAL_DEPTH"); SetCellValue(sheet, "A4", $"{GetName("TOTAL_DEPTH")}(%)"); SetCellValue(sheet, "B4", $"{row4.Avg}"); SetCellValue(sheet, "C4", "--"); SetCellValue(sheet, "D4", $"{row4.CutLevel}"); SetCellValue(sheet, "E4", "--"); // Row 5 var row5 = getSelectData("TABLE"); SetCellValue(sheet, "A5", $"{GetName("TABLE")}(%)"); SetCellValue(sheet, "B5", $"{row5.Avg}"); SetCellValue(sheet, "C5", $"({row5.Min}~{row5.Max})"); SetCellValue(sheet, "D5", $"{row5.CutLevel}"); SetCellValue(sheet, "E5", "--"); var row6 = getSelectData("CROWN_ANGLE"); SetCellValue(sheet, "A6", $"{GetName("CROWN_ANGLE")}(°)"); SetCellValue(sheet, "B6", $"{row6.Avg}"); SetCellValue(sheet, "C6", $"({row6.Min}~{row6.Max})"); SetCellValue(sheet, "D6", $"{row6.CutLevel}"); SetCellValue(sheet, "E6", $"{row6.SymLevel}"); var row7 = getSelectData("CROWN_HEIGHT"); SetCellValue(sheet, "A7", $"{GetName("CROWN_HEIGHT")}(%)"); SetCellValue(sheet, "B7", $"{row7.Avg}"); SetCellValue(sheet, "C7", $"({row7.Min}~{row7.Max})"); SetCellValue(sheet, "D7", $"{row7.CutLevel}"); SetCellValue(sheet, "E7", $"{row7.SymLevel}"); var row8 = getSelectData("GIRDLE"); SetCellValue(sheet, "A8", $"{GetName("GIRDLE")}(%)"); SetCellValue(sheet, "B8", $"{row8.Avg}"); SetCellValue(sheet, "C8", $"({row8.Min}~{row8.Max})"); SetCellValue(sheet, "D8", $"{row8.CutLevel}"); SetCellValue(sheet, "E8", $"{row8.SymLevel}"); var row9 = getSelectData("PAV_DEPTH"); SetCellValue(sheet, "A9", $"{GetName("PAV_DEPTH")}(%)"); SetCellValue(sheet, "B9", $"{row9.Avg}"); SetCellValue(sheet, "C9", $"({row9.Min}~{row9.Max})"); SetCellValue(sheet, "D9", $"{row9.CutLevel}"); SetCellValue(sheet, "E9", $"{row9.SymLevel}"); //row 10 //Row 11 SetCellValue(sheet, "A11", $"{MultilingualHelper.getString("CuttingGrade")}"); SetCellValue(sheet, "B11", $"{CutLevelTotal}"); //Row 12 SetCellValue(sheet, "A12", $"{MultilingualHelper.getString("SymmetryLevel")}"); SetCellValue(sheet, "B12", $"{SymLevelTotal}"); SetCellValue(sheet, "C12", $"{MultilingualHelper.getString("DateOfIssue")}: {DateTime.Now:yyyy/M/d}"); // 生成临时文件路径 string tempFile = Path.Combine( Path.GetTempPath(), $"DiamondReport_{DateTime.Now:yyyyMMddHHmmss}.xlsx"); using (FileStream fs = new FileStream(tempFile, FileMode.Create)) { workbook.Write(fs); } return tempFile; } } catch (Exception e) { throw e; } } [Log] private void SetCellValue(ISheet sheet, string cellAddress, object value) { var cellRef = new CellReference(cellAddress); IRow row = sheet.GetRow(cellRef.Row) ?? sheet.CreateRow(cellRef.Row); ICell cell = row.GetCell(cellRef.Col) ?? row.CreateCell(cellRef.Col); cell.SetCellValue(value?.ToString() ?? ""); } }