using DevExpress.Utils.OAuth; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Sockets; using System.Security.Policy; using System.ServiceModel; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using UAS_MES_NEW.DataOperate; using UAS_MES_NEW.Entity; using UAS_MES_NEW.PublicMethod; namespace UAS_MES_NEW.Make { public partial class Make_FirstInspect : Form { public Make_FirstInspect() { InitializeComponent(); } DataHelper dh; DataTable dt; FileSystemWatcher watcher; string currFileType , equiType ; List fileList = new List(); string workOrder,line,sideType,sn; private void Make_ParseLog_Load(object sender, EventArgs e) { dh = SystemInf.dh; fileList.Add("E:\\4_奥维精密\\首件检测仪"); txtPath.Text = fileList[0]; currFileType = "txt"; equiType = "首件测试仪"; watcher = new FileSystemWatcher(); watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite; watcher.Created += OnFileCreated; /*watcher.Changed += OnFileChanged; watcher.Deleted += OnFileChanged; watcher.Renamed += OnFileChanged;*/ } private void Choose_Click(object sender, EventArgs e) { using (var dialog = new FolderBrowserDialog()) { if (dialog.ShowDialog() == DialogResult.OK) { txtPath.Text = dialog.SelectedPath; txtPath.Enabled = false; watcher.EnableRaisingEvents = false; } } } private void claerBtn_Click(object sender, EventArgs e) { lstFiles.Items.Clear(); } private async void allParse_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(txtPath.Text)) { txtPath.Focus(); txtPath.SelectAll(); MessageBox.Show(this.ParentForm, "请选择解析路径", "提示"); return; } string[] txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}"); if (txtFiles.Length == 0) { LogMessage(0, $"当前{txtPath.Text},没有{equiType}设备输出的{currFileType.ToLower()}文件"); return; } txtPath.Enabled = false; Choose.Enabled = false; generateRadio.Enabled = false; try { await Task.Run(() => RefreshFileList()); } catch (Exception ex) { LogMessage(0, $"处理失败: {ex.Message}"); } finally { txtPath.Enabled = true; Choose.Enabled = true; generateRadio.Enabled = true; } } private void onWatch_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(txtPath.Text)) { txtPath.Focus(); txtPath.SelectAll(); MessageBox.Show(this.ParentForm, "请选择监控路径", "提示"); return; } try { watcher.Path = txtPath.Text; watcher.Filter = $"*.{currFileType}"; if (onWatch.Text == "开启监控") { onWatch.Text = "关闭监控"; txtPath.Enabled = false; Choose.Enabled = false; generateRadio.Enabled = false; watcher.EnableRaisingEvents = true; } else { onWatch.Text = "开启监控"; txtPath.Enabled = true; Choose.Enabled = true; generateRadio.Enabled = true; watcher.EnableRaisingEvents = false; } } catch (Exception ex) { MessageBox.Show(this.ParentForm, ex.Message, "警告"); } } private async void OnFileCreated(object sender, FileSystemEventArgs e) { try { await Task.Delay(500); await Task.Run(() => RefreshFileList()); } catch (Exception ex) { LogMessage(0, $"监控文件处理失败: {ex.Message}"); } } private async void OnFileChanged(object sender, FileSystemEventArgs e) { if (e.ChangeType == WatcherChangeTypes.Changed) { try { await Task.Delay(500); await Task.Run(() => RefreshFileList()); } catch (Exception ex) { LogMessage(0, $"监控文件变更处理失败: {ex.Message}"); } } } private async Task RefreshFileList() { if (lstFiles.InvokeRequired) { await Task.Run(() => { lstFiles.Invoke(new Action(async () => await RefreshFileList())); }); return; } try { if (!Directory.Exists(txtPath.Text)) { LogMessage(0, $"NG,目录不存在: {txtPath.Text}"); return; } string[] txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}"); if (txtFiles.Length == 0) { return; } List itemFileList = new List(); foreach (string file in txtFiles) { itemFileList.Clear(); itemFileList.Add(file); byte[] bytes = File.ReadAllBytes(file); Encoding encoding = Encoding.GetEncoding("GB2312"); string[] lines = File.ReadAllLines(file, encoding); foreach (string rowLine in lines) { if (rowLine.Contains("工单号")) { workOrder = rowLine.Replace("工单号:", ""); } if (rowLine.Contains("生产线")) { line = rowLine.Replace("生产线:", "") ; } if (rowLine.Contains("样品条码")) { sn = rowLine.Replace("样品条码:", ""); } if (rowLine.Contains("板面")) { sideType = rowLine.Replace("板面:", ""); } } string pdFile = Regex.Replace(file, ".{7}$", $"{sideType}.pdf"); itemFileList.Add(pdFile); } await InsertDb(itemFileList); } catch (Exception ex) { LogMessage(0, $"Error: 解析文件列表失败: {ex.Message}"); } } private async Task InsertDb(List itemFileList) { try { var checkTasks = itemFileList.Select(async filePath => { if (!File.Exists(filePath)) { return $"NG,{Path.GetFileName(filePath)}日志文件不存在: {filePath}"; } var content = File.ReadAllText(filePath); if (content.Length == 0) { return $"NG,日志文件中内容为空: {filePath}"; } string outFileMsg = CheckFileAccess(filePath); if (outFileMsg != "OK") { return outFileMsg + ",请稍后再试"; } return "OK"; }); var checkRes = await Task.WhenAll(checkTasks); foreach (var checkItem in checkRes) { if (checkItem != "OK") { LogMessage(0, checkItem); return; } } string isCheck = dh.getFieldDataByCondition("make", "nvl(ma_firstitemcheck, 0)", $"ma_code = '{workOrder}'").ToString(); string sr_code = dh.getFieldDataByCondition("spotcheckrecord", "sr_code",$"sr_type = '首件检验' AND sr_linecode = '{line}' AND sr_makecode = '{workOrder}'").ToString(); if (string.IsNullOrEmpty(sr_code)) { if (generateRadio.Checked && isCheck == "-1") { string v_macraftcode = dh.getFieldDataByCondition("make", "ma_craftcode", $"ma_code = '{workOrder}'").ToString(); string v_maprodcode = dh.getFieldDataByCondition("make", "ma_prodcode", $"ma_code = '{workOrder}'").ToString(); string em_name = dh.getFieldDataByCondition("craft,make", "cr_qcemp", $"ma_code = '{workOrder}' and cr_prodcode = ma_prodcode and ma_craftcode = cr_code").ToString(); dh.ExecuteSql($@"INSERT INTO spotcheckrecord( sr_id, sr_code, sr_linecode, sr_craftcode, sr_indate, sr_inman, sr_status, sr_statuscode, sr_makecode, sr_prodcode, sr_source, sr_contractcode, sr_exportplace, sr_type) VALUES ( spotcheckrecord_seq.NEXTVAL, 'C' || '{workOrder}', '{line}', '{v_macraftcode}', sysdate, '{em_name}', '在录入', 'ENTERING', '{workOrder}', '{v_maprodcode}', '工单' || '{workOrder}' || 'SN投入系统自动生成', '', '{sn}', '首件检验' )", "insert"); } else { if (isCheck == "-1") { LogMessage(1, $"报告{itemFileList[1].Replace(txtPath.Text, "")},工单{workOrder}需检查首件,请检查是否需要生成首件任务单"); return; } else { LogMessage(1, $"报告{itemFileList[1].Replace(txtPath.Text, "")},工单{workOrder}无需检查首件,请核对工单是否检查首件"); return; } } } string sr_id = dh.getFieldDataByCondition("spotcheckrecord", "sr_id", $"sr_makecode = '{workOrder}' and sr_linecode = '{line}' and sr_type='首件检验'").ToString(); string cookie = "JSESSIONID=9A2D8BD2156087D2BB96CC2F6B6230D7; "; string uploadFileApi = "http://192.168.41.232:8098/mes//common/uploadFiles.action"; var uploadFileParams = new Dictionary { { "em_code", $"{User.UserCode}" }, { "caller", "checkFirst" } }; string uploadFileRes = await HttpHelper.PostMultipartWithFileAsync(uploadFileApi, uploadFileParams, itemFileList[1], cookie); //LogMessage(1, $"{uploadFileRes}"); JObject root = JObject.Parse(uploadFileRes); if (root["success"]?.ToString() == "True") { LogMessage(1, $"文件上传成功{itemFileList[1].Replace(txtPath.Text, "")}"); JArray dataArr = (JArray)root["data"]; foreach (JToken item in dataArr) { dh.ExecuteSql($@"UPDATE spotcheckrecord SET sr_prodtype = '{item["filepath"].ToString()};' WHERE sr_id = '{sr_id}'", "update"); LogMessage(1, $"首件检验单:C{workOrder.ToUpper()} ,附件上传成功"); } #region /*JArray dataArr = (JArray)root["data"]; string updateApi = "http://192.168.41.232:8098/mes/common/attach/update.action"; foreach (JToken item in dataArr) { var Params = new Dictionary { { "caller", "checkFirst" }, { "table", "SPOTCHECKRECORD" }, { "update", $"sr_prodtype='{item["filepath"].ToString()};'" }, { "condition", $"sr_id='{sr_id}'" }, { "type", "添加附件" } }; string updateRes = await HttpHelper.PostMultipartAsync(uploadFileApi, Params, cookie); LogMessage(1, $"{updateRes}"); JObject root1 = JObject.Parse(updateRes); if (root["success"]?.ToString() == "True") { LogMessage(1, $"首件检验单:C{workOrder.ToUpper()} ,附件上传成功"); } }*/ #endregion } } catch (Exception ex) { LogMessage(0, $"Error,处理解析异常: {ex.Message}"); } } public class HttpHelper { public static async Task PostMultipartAsync(string url, Dictionary parameters, string cookie = null) { try { var handler = new HttpClientHandler(); handler.UseCookies = true; handler.CookieContainer = new CookieContainer(); if (!string.IsNullOrEmpty(cookie) && cookie.Contains("JSESSIONID=")) { int start = cookie.IndexOf("JSESSIONID=") + 11; int end = cookie.IndexOf(";", start); if (end == -1) end = cookie.Length; string jsessionId = cookie.Substring(start, end - start).Trim(); handler.CookieContainer.Add(new Uri(url), new Cookie("JSESSIONID", jsessionId)); } using (var httpClient = new HttpClient(handler)) { httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "PostmanRuntime/7.29.0"); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "*/*"); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br"); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Cache-Control", "no-cache"); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Connection", "keep-alive"); string boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"; using (var memoryStream = new MemoryStream()) { var writer = new StreamWriter(memoryStream, System.Text.Encoding.UTF8); foreach (var param in parameters) { await writer.WriteAsync($"--{boundary}\r\n"); await writer.WriteAsync($"Content-Disposition: form-data; name=\"{param.Key}\"\r\n\r\n"); await writer.WriteAsync($"{param.Value}\r\n"); } await writer.WriteAsync($"--{boundary}--\r\n"); await writer.FlushAsync(); var content = new ByteArrayContent(memoryStream.ToArray()); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"); content.Headers.ContentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("boundary", boundary)); var response = await httpClient.PostAsync(url, content); string responseBody = await response.Content.ReadAsStringAsync(); return responseBody; } } } catch (Exception ex) { throw new Exception($"HTTP请求失败: {ex.Message}"); } } public static async Task PostMultipartWithFileAsync(string url, Dictionary parameters, string filePath, string cookie = null) { try { var handler = new HttpClientHandler(); handler.UseCookies = true; handler.CookieContainer = new CookieContainer(); if (!string.IsNullOrEmpty(cookie) && cookie.Contains("JSESSIONID=")) { int start = cookie.IndexOf("JSESSIONID=") + 11; int end = cookie.IndexOf(";", start); if (end == -1) end = cookie.Length; string jsessionId = cookie.Substring(start, end - start).Trim(); handler.CookieContainer.Add(new Uri(url), new Cookie("JSESSIONID", jsessionId)); } using (var httpClient = new HttpClient(handler)) { httpClient.DefaultRequestHeaders.ConnectionClose = true; httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "PostmanRuntime/7.29.0"); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "*/*"); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br"); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Cache-Control", "no-cache"); string boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"; string fileName = Path.GetFileName(filePath); byte[] fileBytes = File.ReadAllBytes(filePath); using (var memoryStream = new MemoryStream()) { var writer = new StreamWriter(memoryStream, System.Text.Encoding.UTF8); await writer.WriteAsync($"--{boundary}\r\n"); await writer.WriteAsync($"Content-Disposition: form-data; name=\"em_code\"\r\n\r\n"); await writer.WriteAsync($"{parameters["em_code"]}\r\n"); await writer.WriteAsync($"--{boundary}\r\n"); await writer.WriteAsync($"Content-Disposition: form-data; name=\"caller\"\r\n\r\n"); await writer.WriteAsync($"{parameters["caller"]}\r\n"); await writer.WriteAsync($"--{boundary}\r\n"); await writer.WriteAsync($"Content-Disposition: form-data; name=\"file\"; filename=\"{fileName}\"\r\n"); await writer.WriteAsync($"Content-Type: application/octet-stream\r\n\r\n"); await writer.FlushAsync(); await memoryStream.WriteAsync(fileBytes, 0, fileBytes.Length); await memoryStream.FlushAsync(); writer.WriteLine(); await writer.WriteAsync($"--{boundary}--\r\n"); await writer.FlushAsync(); var content = new ByteArrayContent(memoryStream.ToArray()); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"); content.Headers.ContentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("boundary", boundary)); var response = await httpClient.PostAsync(url, content); string responseBody = await response.Content.ReadAsStringAsync(); return responseBody; } } } catch (Exception ex) { throw new Exception($"HTTP请求失败: {ex.Message}"); } } } public string CheckFileAccess(string filePath) { try { using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None)) { return "OK"; } } catch (IOException ex) { return "NG,文件被占用: " + ex.Message; } catch (UnauthorizedAccessException ex) { return "NG,权限不足,无法访问文件: " + ex.Message; } catch (Exception ex) { return "NG," + ex.Message; } } private bool ConsoleLog(string Content, string PathName,string SN) { try { string sourcePaht = Path.GetDirectoryName(PathName); string changeName = Path.Combine(sourcePaht, $"{SN}.{currFileType}"); string newFolderName = "Logs"; string newFolderPath = Path.Combine(sourcePaht, newFolderName); if (!Directory.Exists(newFolderPath)) { Directory.CreateDirectory(newFolderPath); } string newFileName = "Log_" + Path.GetFileName(changeName); string newFilePath = Path.Combine(newFolderPath, newFileName); File.AppendAllText(newFilePath, Content + Environment.NewLine); return true; } catch (Exception ex) { MessageBox.Show(this.ParentForm, ex.Message, "警告"); return false; } } private void LogMessage(int type, string message) { if (type == 0) { if (lstFiles.InvokeRequired) { lstFiles.Invoke(new Action(LogMessage), new object[] { type, message }); return; } lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}"); lstFiles.TopIndex = lstFiles.Items.Count - 1; } else { if (lstOk.InvokeRequired) { lstOk.Invoke(new Action(LogMessage), new object[] { type, message }); return; } lstOk.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}"); lstOk.TopIndex = lstOk.Items.Count - 1; } } private void lstFiles_DrawItem(object sender, DrawItemEventArgs e) { if (e.Index < 0) return; e.DrawBackground(); string txt = lstFiles.Items[e.Index].ToString().ToUpper(); Brush color = Brushes.Black; if (txt.Contains("NG")) { color = Brushes.Red; } else if (txt.Contains("ERROR")) { color = Brushes.Red; } else { color = Brushes.Green; } e.DrawFocusRectangle(); e.Graphics.DrawString(lstFiles.Items[e.Index].ToString(), e.Font, color, e.Bounds, StringFormat.GenericDefault); } } }