Make_FirstInspect.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. using DevExpress.Utils.OAuth;
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.Drawing;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Net.Http;
  12. using System.Net.Sockets;
  13. using System.Security.Policy;
  14. using System.ServiceModel;
  15. using System.Text;
  16. using System.Text.RegularExpressions;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. using System.Windows.Forms;
  20. using UAS_MES_NEW.DataOperate;
  21. using UAS_MES_NEW.Entity;
  22. using UAS_MES_NEW.PublicMethod;
  23. namespace UAS_MES_NEW.Make
  24. {
  25. public partial class Make_FirstInspect : Form
  26. {
  27. public Make_FirstInspect()
  28. {
  29. InitializeComponent();
  30. }
  31. DataHelper dh;
  32. DataTable dt;
  33. FileSystemWatcher watcher;
  34. string currFileType , equiType ;
  35. List<string> fileList = new List<string>();
  36. string workOrder,line,sideType,sn;
  37. private void Make_ParseLog_Load(object sender, EventArgs e)
  38. {
  39. dh = SystemInf.dh;
  40. fileList.Add("E:\\4_奥维精密\\首件检测仪");
  41. txtPath.Text = fileList[0];
  42. currFileType = "txt";
  43. equiType = "首件测试仪";
  44. watcher = new FileSystemWatcher();
  45. watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
  46. watcher.Created += OnFileCreated;
  47. /*watcher.Changed += OnFileChanged;
  48. watcher.Deleted += OnFileChanged;
  49. watcher.Renamed += OnFileChanged;*/
  50. }
  51. private void Choose_Click(object sender, EventArgs e)
  52. {
  53. using (var dialog = new FolderBrowserDialog())
  54. {
  55. if (dialog.ShowDialog() == DialogResult.OK)
  56. {
  57. txtPath.Text = dialog.SelectedPath;
  58. txtPath.Enabled = false;
  59. watcher.EnableRaisingEvents = false;
  60. }
  61. }
  62. }
  63. private void claerBtn_Click(object sender, EventArgs e)
  64. {
  65. lstFiles.Items.Clear();
  66. }
  67. private async void allParse_Click(object sender, EventArgs e)
  68. {
  69. if (String.IsNullOrEmpty(txtPath.Text))
  70. {
  71. txtPath.Focus();
  72. txtPath.SelectAll();
  73. MessageBox.Show(this.ParentForm, "请选择解析路径", "提示");
  74. return;
  75. }
  76. string[] txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
  77. if (txtFiles.Length == 0)
  78. {
  79. LogMessage(0, $"当前{txtPath.Text},没有{equiType}设备输出的{currFileType.ToLower()}文件");
  80. return;
  81. }
  82. txtPath.Enabled = false;
  83. Choose.Enabled = false;
  84. generateRadio.Enabled = false;
  85. try
  86. {
  87. await Task.Run(() => RefreshFileList());
  88. }
  89. catch (Exception ex)
  90. {
  91. LogMessage(0, $"处理失败: {ex.Message}");
  92. }
  93. finally
  94. {
  95. txtPath.Enabled = true;
  96. Choose.Enabled = true;
  97. generateRadio.Enabled = true;
  98. }
  99. }
  100. private void onWatch_Click(object sender, EventArgs e)
  101. {
  102. if (String.IsNullOrEmpty(txtPath.Text))
  103. {
  104. txtPath.Focus();
  105. txtPath.SelectAll();
  106. MessageBox.Show(this.ParentForm, "请选择监控路径", "提示");
  107. return;
  108. }
  109. try
  110. {
  111. watcher.Path = txtPath.Text;
  112. watcher.Filter = $"*.{currFileType}";
  113. if (onWatch.Text == "开启监控")
  114. {
  115. onWatch.Text = "关闭监控";
  116. txtPath.Enabled = false;
  117. Choose.Enabled = false;
  118. generateRadio.Enabled = false;
  119. watcher.EnableRaisingEvents = true;
  120. }
  121. else
  122. {
  123. onWatch.Text = "开启监控";
  124. txtPath.Enabled = true;
  125. Choose.Enabled = true;
  126. generateRadio.Enabled = true;
  127. watcher.EnableRaisingEvents = false;
  128. }
  129. }
  130. catch (Exception ex)
  131. {
  132. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  133. }
  134. }
  135. private async void OnFileCreated(object sender, FileSystemEventArgs e)
  136. {
  137. try
  138. {
  139. await Task.Delay(500);
  140. await Task.Run(() => RefreshFileList());
  141. }
  142. catch (Exception ex)
  143. {
  144. LogMessage(0, $"监控文件处理失败: {ex.Message}");
  145. }
  146. }
  147. private async void OnFileChanged(object sender, FileSystemEventArgs e)
  148. {
  149. if (e.ChangeType == WatcherChangeTypes.Changed)
  150. {
  151. try
  152. {
  153. await Task.Delay(500);
  154. await Task.Run(() => RefreshFileList());
  155. }
  156. catch (Exception ex)
  157. {
  158. LogMessage(0, $"监控文件变更处理失败: {ex.Message}");
  159. }
  160. }
  161. }
  162. private async Task RefreshFileList()
  163. {
  164. if (lstFiles.InvokeRequired)
  165. {
  166. await Task.Run(() =>
  167. {
  168. lstFiles.Invoke(new Action(async () => await RefreshFileList()));
  169. });
  170. return;
  171. }
  172. try
  173. {
  174. if (!Directory.Exists(txtPath.Text))
  175. {
  176. LogMessage(0, $"NG,目录不存在: {txtPath.Text}");
  177. return;
  178. }
  179. string[] txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
  180. if (txtFiles.Length == 0)
  181. {
  182. return;
  183. }
  184. List<string> itemFileList = new List<string>();
  185. foreach (string file in txtFiles)
  186. {
  187. itemFileList.Clear();
  188. itemFileList.Add(file);
  189. byte[] bytes = File.ReadAllBytes(file);
  190. Encoding encoding = Encoding.GetEncoding("GB2312");
  191. string[] lines = File.ReadAllLines(file, encoding);
  192. foreach (string rowLine in lines)
  193. {
  194. if (rowLine.Contains("工单号"))
  195. {
  196. workOrder = rowLine.Replace("工单号:", "");
  197. }
  198. if (rowLine.Contains("生产线"))
  199. {
  200. line = rowLine.Replace("生产线:", "") ;
  201. }
  202. if (rowLine.Contains("样品条码"))
  203. {
  204. sn = rowLine.Replace("样品条码:", "");
  205. }
  206. if (rowLine.Contains("板面"))
  207. {
  208. sideType = rowLine.Replace("板面:", "");
  209. }
  210. }
  211. string pdFile = Regex.Replace(file, ".{7}$", $"{sideType}.pdf");
  212. itemFileList.Add(pdFile);
  213. }
  214. await InsertDb(itemFileList);
  215. }
  216. catch (Exception ex)
  217. {
  218. LogMessage(0, $"Error: 解析文件列表失败: {ex.Message}");
  219. }
  220. }
  221. private async Task InsertDb(List<string> itemFileList)
  222. {
  223. try
  224. {
  225. var checkTasks = itemFileList.Select(async filePath =>
  226. {
  227. if (!File.Exists(filePath))
  228. {
  229. return $"NG,{Path.GetFileName(filePath)}日志文件不存在: {filePath}";
  230. }
  231. var content = File.ReadAllText(filePath);
  232. if (content.Length == 0)
  233. {
  234. return $"NG,日志文件中内容为空: {filePath}";
  235. }
  236. string outFileMsg = CheckFileAccess(filePath);
  237. if (outFileMsg != "OK")
  238. {
  239. return outFileMsg + ",请稍后再试";
  240. }
  241. return "OK";
  242. });
  243. var checkRes = await Task.WhenAll(checkTasks);
  244. foreach (var checkItem in checkRes)
  245. {
  246. if (checkItem != "OK")
  247. {
  248. LogMessage(0, checkItem);
  249. return;
  250. }
  251. }
  252. string isCheck = dh.getFieldDataByCondition("make", "nvl(ma_firstitemcheck, 0)", $"ma_code = '{workOrder}'").ToString();
  253. string sr_code = dh.getFieldDataByCondition("spotcheckrecord", "sr_code",$"sr_type = '首件检验' AND sr_linecode = '{line}' AND sr_makecode = '{workOrder}'").ToString();
  254. if (string.IsNullOrEmpty(sr_code))
  255. {
  256. if (generateRadio.Checked && isCheck == "-1")
  257. {
  258. string v_macraftcode = dh.getFieldDataByCondition("make", "ma_craftcode", $"ma_code = '{workOrder}'").ToString();
  259. string v_maprodcode = dh.getFieldDataByCondition("make", "ma_prodcode", $"ma_code = '{workOrder}'").ToString();
  260. string em_name = dh.getFieldDataByCondition("craft,make", "cr_qcemp", $"ma_code = '{workOrder}' and cr_prodcode = ma_prodcode and ma_craftcode = cr_code").ToString();
  261. dh.ExecuteSql($@"INSERT INTO spotcheckrecord( sr_id, sr_code, sr_linecode, sr_craftcode, sr_indate,
  262. sr_inman, sr_status, sr_statuscode, sr_makecode, sr_prodcode, sr_source,
  263. sr_contractcode, sr_exportplace, sr_type)
  264. VALUES ( spotcheckrecord_seq.NEXTVAL, 'C' || '{workOrder}', '{line}', '{v_macraftcode}', sysdate,
  265. '{em_name}', '在录入', 'ENTERING', '{workOrder}', '{v_maprodcode}', '工单' || '{workOrder}' || 'SN投入系统自动生成',
  266. '', '{sn}', '首件检验' )", "insert");
  267. }
  268. else
  269. {
  270. if (isCheck == "-1")
  271. {
  272. LogMessage(1, $"报告{itemFileList[1].Replace(txtPath.Text, "")},工单{workOrder}需检查首件,请检查是否需要生成首件任务单");
  273. return;
  274. }
  275. else
  276. {
  277. LogMessage(1, $"报告{itemFileList[1].Replace(txtPath.Text, "")},工单{workOrder}无需检查首件,请核对工单是否检查首件");
  278. return;
  279. }
  280. }
  281. }
  282. string sr_id = dh.getFieldDataByCondition("spotcheckrecord", "sr_id", $"sr_makecode = '{workOrder}' and sr_linecode = '{line}' and sr_type='首件检验'").ToString();
  283. string cookie = "JSESSIONID=9A2D8BD2156087D2BB96CC2F6B6230D7; ";
  284. string uploadFileApi = "http://192.168.41.232:8098/mes//common/uploadFiles.action";
  285. var uploadFileParams = new Dictionary<string, string>
  286. {
  287. { "em_code", $"{User.UserCode}" },
  288. { "caller", "checkFirst" }
  289. };
  290. string uploadFileRes = await HttpHelper.PostMultipartWithFileAsync(uploadFileApi, uploadFileParams, itemFileList[1], cookie);
  291. //LogMessage(1, $"{uploadFileRes}");
  292. JObject root = JObject.Parse(uploadFileRes);
  293. if (root["success"]?.ToString() == "True")
  294. {
  295. LogMessage(1, $"文件上传成功{itemFileList[1].Replace(txtPath.Text, "")}");
  296. JArray dataArr = (JArray)root["data"];
  297. foreach (JToken item in dataArr)
  298. {
  299. dh.ExecuteSql($@"UPDATE spotcheckrecord SET sr_prodtype = '{item["filepath"].ToString()};' WHERE sr_id = '{sr_id}'", "update");
  300. LogMessage(1, $"首件检验单:C{workOrder.ToUpper()} ,附件上传成功");
  301. }
  302. #region
  303. /*JArray dataArr = (JArray)root["data"];
  304. string updateApi = "http://192.168.41.232:8098/mes/common/attach/update.action";
  305. foreach (JToken item in dataArr)
  306. {
  307. var Params = new Dictionary<string, string>
  308. {
  309. { "caller", "checkFirst" },
  310. { "table", "SPOTCHECKRECORD" },
  311. { "update", $"sr_prodtype='{item["filepath"].ToString()};'" },
  312. { "condition", $"sr_id='{sr_id}'" },
  313. { "type", "添加附件" }
  314. };
  315. string updateRes = await HttpHelper.PostMultipartAsync(uploadFileApi, Params, cookie);
  316. LogMessage(1, $"{updateRes}");
  317. JObject root1 = JObject.Parse(updateRes);
  318. if (root["success"]?.ToString() == "True")
  319. {
  320. LogMessage(1, $"首件检验单:C{workOrder.ToUpper()} ,附件上传成功");
  321. }
  322. }*/
  323. #endregion
  324. }
  325. }
  326. catch (Exception ex)
  327. {
  328. LogMessage(0, $"Error,处理解析异常: {ex.Message}");
  329. }
  330. }
  331. public class HttpHelper
  332. {
  333. public static async Task<string> PostMultipartAsync(string url, Dictionary<string, string> parameters, string cookie = null)
  334. {
  335. try
  336. {
  337. var handler = new HttpClientHandler();
  338. handler.UseCookies = true;
  339. handler.CookieContainer = new CookieContainer();
  340. if (!string.IsNullOrEmpty(cookie) && cookie.Contains("JSESSIONID="))
  341. {
  342. int start = cookie.IndexOf("JSESSIONID=") + 11;
  343. int end = cookie.IndexOf(";", start);
  344. if (end == -1) end = cookie.Length;
  345. string jsessionId = cookie.Substring(start, end - start).Trim();
  346. handler.CookieContainer.Add(new Uri(url), new Cookie("JSESSIONID", jsessionId));
  347. }
  348. using (var httpClient = new HttpClient(handler))
  349. {
  350. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "PostmanRuntime/7.29.0");
  351. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "*/*");
  352. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
  353. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Cache-Control", "no-cache");
  354. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Connection", "keep-alive");
  355. string boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
  356. using (var memoryStream = new MemoryStream())
  357. {
  358. var writer = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
  359. foreach (var param in parameters)
  360. {
  361. await writer.WriteAsync($"--{boundary}\r\n");
  362. await writer.WriteAsync($"Content-Disposition: form-data; name=\"{param.Key}\"\r\n\r\n");
  363. await writer.WriteAsync($"{param.Value}\r\n");
  364. }
  365. await writer.WriteAsync($"--{boundary}--\r\n");
  366. await writer.FlushAsync();
  367. var content = new ByteArrayContent(memoryStream.ToArray());
  368. content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");
  369. content.Headers.ContentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("boundary", boundary));
  370. var response = await httpClient.PostAsync(url, content);
  371. string responseBody = await response.Content.ReadAsStringAsync();
  372. return responseBody;
  373. }
  374. }
  375. }
  376. catch (Exception ex)
  377. {
  378. throw new Exception($"HTTP请求失败: {ex.Message}");
  379. }
  380. }
  381. public static async Task<string> PostMultipartWithFileAsync(string url, Dictionary<string, string> parameters, string filePath, string cookie = null)
  382. {
  383. try
  384. {
  385. var handler = new HttpClientHandler();
  386. handler.UseCookies = true;
  387. handler.CookieContainer = new CookieContainer();
  388. if (!string.IsNullOrEmpty(cookie) && cookie.Contains("JSESSIONID="))
  389. {
  390. int start = cookie.IndexOf("JSESSIONID=") + 11;
  391. int end = cookie.IndexOf(";", start);
  392. if (end == -1) end = cookie.Length;
  393. string jsessionId = cookie.Substring(start, end - start).Trim();
  394. handler.CookieContainer.Add(new Uri(url), new Cookie("JSESSIONID", jsessionId));
  395. }
  396. using (var httpClient = new HttpClient(handler))
  397. {
  398. httpClient.DefaultRequestHeaders.ConnectionClose = true;
  399. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "PostmanRuntime/7.29.0");
  400. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "*/*");
  401. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
  402. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Cache-Control", "no-cache");
  403. string boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
  404. string fileName = Path.GetFileName(filePath);
  405. byte[] fileBytes = File.ReadAllBytes(filePath);
  406. using (var memoryStream = new MemoryStream())
  407. {
  408. var writer = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
  409. await writer.WriteAsync($"--{boundary}\r\n");
  410. await writer.WriteAsync($"Content-Disposition: form-data; name=\"em_code\"\r\n\r\n");
  411. await writer.WriteAsync($"{parameters["em_code"]}\r\n");
  412. await writer.WriteAsync($"--{boundary}\r\n");
  413. await writer.WriteAsync($"Content-Disposition: form-data; name=\"caller\"\r\n\r\n");
  414. await writer.WriteAsync($"{parameters["caller"]}\r\n");
  415. await writer.WriteAsync($"--{boundary}\r\n");
  416. await writer.WriteAsync($"Content-Disposition: form-data; name=\"file\"; filename=\"{fileName}\"\r\n");
  417. await writer.WriteAsync($"Content-Type: application/octet-stream\r\n\r\n");
  418. await writer.FlushAsync();
  419. await memoryStream.WriteAsync(fileBytes, 0, fileBytes.Length);
  420. await memoryStream.FlushAsync();
  421. writer.WriteLine();
  422. await writer.WriteAsync($"--{boundary}--\r\n");
  423. await writer.FlushAsync();
  424. var content = new ByteArrayContent(memoryStream.ToArray());
  425. content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");
  426. content.Headers.ContentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("boundary", boundary));
  427. var response = await httpClient.PostAsync(url, content);
  428. string responseBody = await response.Content.ReadAsStringAsync();
  429. return responseBody;
  430. }
  431. }
  432. }
  433. catch (Exception ex)
  434. {
  435. throw new Exception($"HTTP请求失败: {ex.Message}");
  436. }
  437. }
  438. }
  439. public string CheckFileAccess(string filePath)
  440. {
  441. try
  442. {
  443. using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
  444. {
  445. return "OK";
  446. }
  447. }
  448. catch (IOException ex)
  449. {
  450. return "NG,文件被占用: " + ex.Message;
  451. }
  452. catch (UnauthorizedAccessException ex)
  453. {
  454. return "NG,权限不足,无法访问文件: " + ex.Message;
  455. }
  456. catch (Exception ex)
  457. {
  458. return "NG," + ex.Message;
  459. }
  460. }
  461. private bool ConsoleLog(string Content, string PathName,string SN)
  462. {
  463. try
  464. {
  465. string sourcePaht = Path.GetDirectoryName(PathName);
  466. string changeName = Path.Combine(sourcePaht, $"{SN}.{currFileType}");
  467. string newFolderName = "Logs";
  468. string newFolderPath = Path.Combine(sourcePaht, newFolderName);
  469. if (!Directory.Exists(newFolderPath))
  470. {
  471. Directory.CreateDirectory(newFolderPath);
  472. }
  473. string newFileName = "Log_" + Path.GetFileName(changeName);
  474. string newFilePath = Path.Combine(newFolderPath, newFileName);
  475. File.AppendAllText(newFilePath, Content + Environment.NewLine);
  476. return true;
  477. }
  478. catch (Exception ex)
  479. {
  480. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  481. return false;
  482. }
  483. }
  484. private void LogMessage(int type, string message)
  485. {
  486. if (type == 0)
  487. {
  488. if (lstFiles.InvokeRequired)
  489. {
  490. lstFiles.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  491. return;
  492. }
  493. lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  494. lstFiles.TopIndex = lstFiles.Items.Count - 1;
  495. }
  496. else
  497. {
  498. if (lstOk.InvokeRequired)
  499. {
  500. lstOk.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  501. return;
  502. }
  503. lstOk.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  504. lstOk.TopIndex = lstOk.Items.Count - 1;
  505. }
  506. }
  507. private void lstFiles_DrawItem(object sender, DrawItemEventArgs e)
  508. {
  509. if (e.Index < 0) return;
  510. e.DrawBackground();
  511. string txt = lstFiles.Items[e.Index].ToString().ToUpper();
  512. Brush color = Brushes.Black;
  513. if (txt.Contains("NG"))
  514. {
  515. color = Brushes.Red;
  516. }
  517. else if (txt.Contains("ERROR"))
  518. {
  519. color = Brushes.Red;
  520. }
  521. else
  522. {
  523. color = Brushes.Green;
  524. }
  525. e.DrawFocusRectangle();
  526. e.Graphics.DrawString(lstFiles.Items[e.Index].ToString(), e.Font, color, e.Bounds, StringFormat.GenericDefault);
  527. }
  528. }
  529. }