459 lines
13 KiB
C#
459 lines
13 KiB
C#
using BaseFunction;
|
|
using NSAnalysis.DAL;
|
|
using NSAnalysis.Model;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Data;
|
|
using System.Globalization;
|
|
using System.IO;
|
|
|
|
namespace NSAnalysis
|
|
{
|
|
public class FileSorter
|
|
{
|
|
public CjlrDAL _dal = new CjlrDAL();
|
|
|
|
//定义读取的位置
|
|
public int readRowIndex = 2; // 默认读取第3行(从0开始计数)
|
|
|
|
public int readColIndex = 1; // 默认读取第2列(从0开始计数)
|
|
|
|
public event Action<string> OnLog; // 日志事件
|
|
|
|
public event Action<string> OnFileParsed; // 解析完成后通知文件名
|
|
|
|
public FileSorter()
|
|
{
|
|
//SQLHelper.connStr = DatabaseDfn.SqlConnectStr();
|
|
}
|
|
|
|
// 主逻辑处理
|
|
public void ProcessFiles()
|
|
{
|
|
var tasks = GetTaskRecords();
|
|
foreach (DataRow task in tasks.Rows)
|
|
{
|
|
string modelName = task["modelsName"].ToString();
|
|
string modelCode = task["modelsCode"].ToString();
|
|
string position = task["position"].ToString();
|
|
string sourceDir = task["sourceFile"].ToString();
|
|
string targetDir = task["targetFile"].ToString();
|
|
|
|
// 打印信息
|
|
Trace($"Processing Task - Source: {sourceDir}, Target: {targetDir}, ModelCode: {modelCode} Position: {position}");
|
|
if (Directory.Exists(sourceDir))
|
|
{
|
|
ProcessDirectory(sourceDir, targetDir, modelCode, modelName, position);
|
|
}
|
|
else
|
|
{
|
|
Trace($"[ProcessFiles] 源文件地址不存在或错误: {sourceDir}");
|
|
|
|
//记录到数据库
|
|
try
|
|
{
|
|
//插入分发详情
|
|
CjlrTaskReleaseDetailModel detailModel = new CjlrTaskReleaseDetailModel
|
|
{
|
|
ModelsName = modelName, // 这里可以根据需要填写车型名称
|
|
ModelsCode = modelCode,
|
|
Position = position, // 这里可以根据需要填写位置
|
|
SourceFile = "",
|
|
TargetFile = "",
|
|
TaskFileName = "",
|
|
TaskStatus = 2, // 假设1表示已处理, 2表示未处理
|
|
TaskDetail = $"源文件地址不存在或错误: {sourceDir}",
|
|
CreateDate = DateTime.Now
|
|
};
|
|
_dal.InsertTaskDetail(detailModel);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Trace($"[ProcessFiles] 记录错误到数据库失败: {ex.Message}");
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
// 获取任务记录
|
|
private DataTable GetTaskRecords()
|
|
{
|
|
DataTable dt = _dal.SelectTaskByCondition("", "", "start");
|
|
|
|
//打印 dt
|
|
PrintDataTable(dt);
|
|
if (dt == null || dt.Rows.Count == 0)
|
|
{
|
|
Trace("未发现移动任务.");
|
|
return null;
|
|
}
|
|
return dt;
|
|
}
|
|
|
|
// 处理目录中的文件
|
|
private void ProcessDirectory(string sourceDir, string targetDir, string modelCode, string modelName, string position)
|
|
{
|
|
// 匹配信息
|
|
string matchStr = $"{modelCode}_{position}";
|
|
Trace($"匹配文件特征符: {matchStr}");
|
|
|
|
// 判断目标目录是否存在,如果不存在记录到日志
|
|
|
|
// 确保目标目录存在
|
|
if (!Directory.Exists(targetDir))
|
|
{
|
|
Directory.CreateDirectory(targetDir);
|
|
Trace($"创建目标文件夹: {targetDir}");
|
|
}
|
|
|
|
// 遍历源目录中的所有CSV文件
|
|
foreach (string file in Directory.GetFiles(sourceDir, "*.csv"))
|
|
{
|
|
// 打印正在处理的文件
|
|
Trace($"正在处理文件 : {file}");
|
|
|
|
// 解析入库
|
|
AnalysisNxsCSV(file);
|
|
|
|
// 分发逻辑
|
|
if (MatchCsvValue(file, matchStr, readRowIndex, readColIndex))
|
|
{
|
|
string destFile = Path.Combine(targetDir, Path.GetFileName(file));
|
|
File.Move(file, destFile);
|
|
Trace($"移动完成,: {file} -> {destFile}");
|
|
|
|
//插入分发详情
|
|
CjlrTaskReleaseDetailModel detailModel = new CjlrTaskReleaseDetailModel
|
|
{
|
|
ModelsName = modelName, // 这里可以根据需要填写车型名称
|
|
ModelsCode = modelCode,
|
|
Position = position, // 这里可以根据需要填写位置
|
|
SourceFile = file,
|
|
TargetFile = destFile,
|
|
TaskFileName = Path.GetFileName(file),
|
|
TaskStatus = 1, // 假设1表示已处理
|
|
TaskDetail = "文件移动成功",
|
|
CreateDate = DateTime.Now
|
|
};
|
|
_dal.InsertTaskDetail(detailModel);
|
|
}
|
|
else
|
|
{
|
|
Trace($"未匹配到文件: {file}");
|
|
|
|
//记录到数据库
|
|
CjlrTaskReleaseDetailModel detailModel = new CjlrTaskReleaseDetailModel
|
|
{
|
|
ModelsName = modelName, // 这里可以根据需要填写车型名称
|
|
ModelsCode = modelCode,
|
|
Position = position, // 这里可以根据需要填写位置
|
|
SourceFile = file,
|
|
TargetFile = "",
|
|
TaskFileName = Path.GetFileName(file),
|
|
TaskStatus = 2, // 假设2表示未处理
|
|
TaskDetail = "文件未匹配",
|
|
CreateDate = DateTime.Now
|
|
};
|
|
try
|
|
{
|
|
_dal.InsertTaskDetail(detailModel);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Trace($"记录错误到数据库失败: {ex.Message}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 检查CSV文件中指定行列的字符串是否匹配目标值
|
|
/// </summary>
|
|
/// <param name="filePath">CSV文件路径</param>
|
|
/// <param name="targetValue">要匹配的目标字符串</param>
|
|
/// <param name="rowIndex">行索引(从0开始)</param>
|
|
/// <param name="colIndex">列索引(从0开始)</param>
|
|
/// <returns>匹配成功返回true,否则false</returns>
|
|
public static bool MatchCsvValue(string filePath, string targetValue, int rowIndex, int colIndex)
|
|
{
|
|
try
|
|
{
|
|
string[] lines = File.ReadAllLines(filePath);
|
|
|
|
// 检查行索引是否有效
|
|
if (rowIndex < 0 || rowIndex >= lines.Length)
|
|
return false;
|
|
|
|
string[] columns = lines[rowIndex].Split(',');
|
|
|
|
// 检查列索引是否有效
|
|
if (colIndex < 0 || colIndex >= columns.Length)
|
|
return false;
|
|
|
|
return columns[colIndex].Trim().Equals(targetValue);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MyBase.TraceWriteLine($"处理CSV文件时出错: {ex.Message}");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// 编写一个打印 DataTable 对象的方法,输入是对象
|
|
public static void PrintDataTable(DataTable dt)
|
|
{
|
|
if (dt == null || dt.Rows.Count == 0)
|
|
{
|
|
MyBase.TraceWriteLine("[PrintDataTable] DataTable is empty or null.");
|
|
return;
|
|
}
|
|
foreach (DataColumn column in dt.Columns)
|
|
{
|
|
Console.Write($"{column.ColumnName}\t");
|
|
}
|
|
MyBase.TraceWriteLine("");
|
|
foreach (DataRow row in dt.Rows)
|
|
{
|
|
foreach (var item in row.ItemArray)
|
|
{
|
|
Console.Write($"{item}\t");
|
|
}
|
|
MyBase.TraceWriteLine("");
|
|
}
|
|
}
|
|
|
|
// 导入CSV文件到数据库
|
|
public void ImportCsv2Sql(string filePath)
|
|
{
|
|
var records = new List<CJLR_MeaDataModel>();
|
|
var lineNo = 0; // 行号计数器
|
|
|
|
try
|
|
{
|
|
using (var reader = new StreamReader(filePath))
|
|
{
|
|
// Skip header
|
|
reader.ReadLine();
|
|
|
|
lineNo = 1; // 初始化行号计数器
|
|
while (!reader.EndOfStream)
|
|
{
|
|
lineNo++; // 增加行号计数器
|
|
var line = reader.ReadLine();
|
|
var values = line.Split(','); // 假设 CSV 使用制表符分隔
|
|
|
|
// 跳过前两行(如果有标题行或其他非数据行
|
|
if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#") || line.StartsWith("//") || line.StartsWith("MeasPoint.Name"))
|
|
{
|
|
continue; // 跳过空行或注释行
|
|
}
|
|
|
|
// 跳过前两行(如果有标题行或其他非数据行)
|
|
if (values.Length < 22)
|
|
{
|
|
MyBase.TraceWriteLine("CSV行数据不完整,跳过该行:" + line);
|
|
continue; // 跳过不完整的行
|
|
}
|
|
|
|
// 判断 values[2] 是否为 ,如果是则跳过该行
|
|
if (string.IsNullOrEmpty(values[2]))
|
|
{
|
|
MyBase.TraceWriteLine($"第 {lineNo} 行数据为0,跳过该行:" + line);
|
|
continue; // 跳过该行
|
|
}
|
|
|
|
// 创建 MeasurementRecord 对象并填充数据
|
|
var record = new CJLR_MeaDataModel
|
|
{
|
|
PointName = values[0],
|
|
GroupName = values[1],
|
|
ProductNum = values[2],
|
|
Model = values[3],
|
|
Station = values[4],
|
|
Method = values[5],
|
|
Standard = values[6],
|
|
DimensionName = values[7],
|
|
DimensionValue = values[8],
|
|
DimensionUnit = values[9],
|
|
IsManual = bool.Parse(values[10]),
|
|
Classification = values[11],
|
|
ToleranceName0 = values[12],
|
|
ToleranceLower0 = values[13],
|
|
ToleranceUpper0 = values[14],
|
|
ToleranceName1 = values[15],
|
|
ToleranceLower1 = values[16],
|
|
ToleranceUpper1 = values[17],
|
|
NominalValue = values[18],
|
|
MeasureDate = DateTime.ParseExact(values[19], "yyyyMMdd", CultureInfo.InvariantCulture),
|
|
MeasureTime = TimeSpan.ParseExact(values[20], "hhmmss", CultureInfo.InvariantCulture),
|
|
SequenceNum = int.Parse(values[21])
|
|
};
|
|
|
|
records.Add(record);
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MyBase.TraceWriteLine("导入CSV文件时发生错误:" + ex.Message);
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
// 取第一条记录的时间作为测量时间
|
|
if (records.Count > 0)
|
|
{
|
|
var firstRecord = records[0];
|
|
ConfigDfn.strMeasureTime = firstRecord.MeasureDate.ToString("yyyy-MM-dd") + " " + firstRecord.MeasureTime.ToString(@"hh\:mm\:ss");
|
|
|
|
// 获取车号
|
|
MyBase.TraceWriteLine("--------------------------------------------------------");
|
|
|
|
ConfigDfn.strEquipNo = firstRecord.ProductNum;
|
|
MyBase.TraceWriteLine("车号:" + ConfigDfn.strEquipNo);
|
|
//获取车型
|
|
ConfigDfn.strCarModel = firstRecord.Model;
|
|
MyBase.TraceWriteLine("车型:" + ConfigDfn.strCarModel);
|
|
MyBase.TraceWriteLine("测量时间:" + ConfigDfn.strMeasureTime);
|
|
}
|
|
else
|
|
{
|
|
MyBase.TraceWriteLine("没有找到有效的测量记录,无法设置测量时间。");
|
|
|
|
// 将文件移动到 未导入文件夹,如果不存在则新建该文件夹
|
|
//string strNotImportPath = ConfigDfn.strFileFolder + "\\NextSenseCSVNotImport\\";
|
|
//if (!Directory.Exists(strNotImportPath))
|
|
//{
|
|
// Directory.CreateDirectory(strNotImportPath);
|
|
//}
|
|
//string destFilePath = Path.Combine(strNotImportPath, Path.GetFileName(filePath));
|
|
//File.Move(filePath, destFilePath);
|
|
//MyBase.TraceWriteLine("将文件移动到未导入文件夹,路径为:" + destFilePath);
|
|
|
|
return;
|
|
}
|
|
|
|
// 逐条插入数据到数据库
|
|
foreach (var record in records)
|
|
{
|
|
_dal.InsertCJLRMeaData(record);
|
|
}
|
|
|
|
MyBase.TraceWriteLine("CSV文件导入到数据库成功!");
|
|
MyBase.TraceWriteLine("--------------------------------------------------------");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MyBase.TraceWriteLine("导入CSV文件时发生错误:" + ex.Message);
|
|
}
|
|
}
|
|
|
|
//解析EH3 CSV文件函数
|
|
public void AnalysisNxsCSV(string strCSVName)
|
|
{
|
|
// 判断文件是否存在
|
|
if (!File.Exists(strCSVName))
|
|
{
|
|
MyBase.TraceWriteLine("文件不存在:" + strCSVName);
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
// 解析 CSV 文件并导入到数据库
|
|
ImportCsv2Sql(strCSVName);
|
|
|
|
// 解析完成后触发事件
|
|
if (!string.IsNullOrEmpty(ConfigDfn.strEquipNo))
|
|
{
|
|
OnFileParsed?.Invoke(ConfigDfn.strEquipNo);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MyBase.TraceWriteLine("解析 CSV 文件时发生错误:" + ex.Message);
|
|
}
|
|
}
|
|
|
|
private void GenCustomerReport()
|
|
{
|
|
//#region 解析完报告后,重新生成客户模板报告
|
|
|
|
//string filePath = strSaveReprotPath + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + strCarID + ".csv"; //wsp 后期还要再改
|
|
//string strWithoutLCarVin = strCarID.Substring(1);
|
|
//StringBuilder sb = new StringBuilder();
|
|
////添加表头
|
|
//sb.Append("Measurement Info Name");
|
|
//sb.Append(",");
|
|
//sb.Append("Measurement Info");
|
|
//sb.AppendLine();
|
|
//sb.Append("Date_Time");
|
|
//sb.Append(",");
|
|
//sb.Append(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
|
|
//sb.AppendLine();
|
|
//for (int i = 0; i < listCSVTitleInfo.Count; i++)
|
|
//{
|
|
// if (listCSVTitleInfo[i].Contains("prodnum"))
|
|
// {
|
|
// listCSVTitleInfo[i] = listCSVTitleInfo[i].Replace("prodnum", "Part_ident");
|
|
// }
|
|
// if (listCSVTitleInfo[i].Contains(strWithoutLCarVin))
|
|
// {
|
|
// listCSVTitleInfo[i] = listCSVTitleInfo[i].Replace(strWithoutLCarVin, strCarID);
|
|
// }
|
|
// sb.Append(listCSVTitleInfo[i]);
|
|
// sb.AppendLine();
|
|
//}
|
|
//sb.AppendLine();
|
|
//sb.AppendLine();
|
|
//sb.AppendLine();
|
|
//sb.AppendLine();
|
|
//sb.AppendLine();
|
|
////添加测量数据
|
|
//sb.Append("Characteristic");
|
|
//sb.Append(",");
|
|
//sb.Append("Extension");
|
|
//sb.Append(",");
|
|
//sb.Append("Measured_Value");
|
|
//sb.AppendLine();
|
|
//foreach (DataRow row in dtCSVContent.Rows)
|
|
//{
|
|
// sb.Append(row.ItemArray[2]);
|
|
// sb.Append(",");
|
|
// sb.Append(row.ItemArray[3]);
|
|
// sb.Append(",");
|
|
// sb.Append(row.ItemArray[7]);
|
|
// sb.AppendLine();
|
|
//}
|
|
|
|
//sb.Append("POP");
|
|
//sb.Append(",");
|
|
//sb.Append("P");
|
|
//sb.Append(",");
|
|
//sb.Append(Math.Round(FPYPercent * 100.00d, 2).ToString("F2"));
|
|
//sb.AppendLine();
|
|
//// 将数据写入CSV文件
|
|
//File.WriteAllText(filePath, sb.ToString());
|
|
//MyBase.TraceWriteLine("客户csv报告生成完毕,路径为:" + filePath);
|
|
|
|
//#endregion 解析完报告后,重新生成客户模板报告
|
|
}
|
|
|
|
private void Trace(string msg)
|
|
{
|
|
OnLog?.Invoke(msg);
|
|
MyBase.TraceWriteLine(msg); // 保持原有日志
|
|
}
|
|
|
|
// 测试方法
|
|
public void test()
|
|
{
|
|
SQLHelper.connStr = DatabaseDfn.SqlConnectStr();
|
|
//string testPath = @"D:\CJLR\DATA\Input\LLL\K0902906.csv";
|
|
//bool result = MatchCsvValue(testPath, "X540_L", 3, 1);
|
|
//MyBase.TraceWriteLine($"匹配结果: {result}");
|
|
}
|
|
}
|
|
} |