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("D:\\FAIReport"); 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, workOrder, line, sn); } } catch (Exception ex) { LogMessage(0, $"Error: 解析文件列表失败: {ex.Message}"); } } private async Task InsertDb(List itemFileList, string workOrder, string line, string sn) { 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(); if (string.IsNullOrEmpty(isCheck)) { LogMessage(0, $"NG,工单号:{workOrder}不存在,请检查报告中{currFileType}文件"); return; } 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 uploadFileApi = "http://192.168.41.232:8098/mes/MEScommon/uploadFiles.action?_noc=1"; Dictionary uploadFileParams = new Dictionary() { {"em_name", "管理员" }, {"em_code", "ADMIN" }, {"caller", "FirstInspect" } }; string fp_id = await HttpHelper.UploadFilesToRemoteUrl(uploadFileApi, itemFileList[1], uploadFileParams); if (!string.IsNullOrEmpty(fp_id)) { LogMessage(1, $"文件上传成功{itemFileList[1].Replace(txtPath.Text, "")}"); dh.ExecuteSql($@"UPDATE spotcheckrecord SET sr_prodtype = '{fp_id};' WHERE sr_id = '{sr_id}'", "update"); LogMessage(1, $"首件检验单:C{workOrder.ToUpper()} ,附件上传成功"); using (StreamReader SR = new StreamReader(itemFileList[0], Encoding.GetEncoding("GBK"))) { string Content = SR.ReadToEnd(); SR.Close(); SR.Dispose(); ConsoleLog(Content, itemFileList[0], $"C{workOrder.ToUpper()}"); } using (StreamReader SR = new StreamReader(itemFileList[1], Encoding.GetEncoding("GBK"))) { string Content = SR.ReadToEnd(); SR.Close(); SR.Dispose(); ConsoleLog(Content, itemFileList[1], $"C{workOrder.ToUpper()}"); } } } catch (Exception ex) { LogMessage(0, $"Error,处理解析异常: {ex.Message}"); } } public class HttpHelper { public static async Task UploadFilesToRemoteUrl(string url1, string filepath, Dictionary dic) { try { ServicePointManager.DefaultConnectionLimit = 50; string boundary = DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1); request.Method = "POST"; request.Timeout = 10 * 10000; request.ContentType = "multipart/form-data; boundary=" + boundary; Stream rs = request.GetRequestStream(); var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n"); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n"; if (dic != null) { foreach (string key in dic.Keys) { rs.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, key, dic[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); rs.Write(formitembytes, 0, formitembytes.Length); } } string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n"; { rs.Write(boundarybytes, 0, boundarybytes.Length); var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath)); var headerbytes = System.Text.Encoding.UTF8.GetBytes(header); rs.Write(headerbytes, 0, headerbytes.Length); using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read)) { var buffer = new byte[1024]; var bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { rs.Write(buffer, 0, bytesRead); } } var cr = Encoding.UTF8.GetBytes("\r\n"); rs.Write(cr, 0, cr.Length); } rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); var response = request.GetResponse() as HttpWebResponse; StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string Content = newReader.ReadToEnd(); Dictionary dic1 = new Dictionary(); List> dic2 = null; dic1 = BaseUtil.ToDictionary(Content); dic2 = dic1["data"] as List>; string fp_id = ""; if (dic2[0]["filepath"] != null) { fp_id = dic2[0]["filepath"].ToString(); } if (response.StatusCode == HttpStatusCode.OK) { return fp_id; } } catch (Exception e) { LogicHandler.DoCommandLog("FirstInspect", User.UserCode, "", "", User.UserSourceCode, "上传首件报告", "上传失败", "", ""); Console.WriteLine(e.Message + e.StackTrace); } return ""; } 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 sourcePath = Path.GetDirectoryName(PathName); string newFolderName = "Meslog"; string newFolderPath = Path.Combine(sourcePath, newFolderName, SN); if (!Directory.Exists(newFolderPath)) { Directory.CreateDirectory(newFolderPath); } string newFileName = Path.GetFileName(PathName); string newFilePath = Path.Combine(newFolderPath, newFileName); if (File.Exists(newFilePath)) { File.Delete(newFilePath); } File.Move(PathName, newFilePath); 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); } } }