Main.cs 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  1. using Microsoft.Office.Interop.Excel;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Data;
  7. using System.Drawing;
  8. using System.Globalization;
  9. using System.IO;
  10. using System.IO.Compression;
  11. using System.Linq;
  12. using System.Media;
  13. using System.Net;
  14. using System.Runtime.InteropServices;
  15. using System.Security.Principal;
  16. using System.Text;
  17. using System.Text.RegularExpressions;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using System.Windows.Forms;
  21. using UAS_Tools_HY;
  22. using UAS_Tools_HY.Properties;
  23. using UAS_Tools_HY.PublicMethods;
  24. using Application = Microsoft.Office.Interop.Excel.Application;
  25. using DataTable = System.Data.DataTable;
  26. using Timer = System.Windows.Forms.Timer;
  27. namespace UAS_MES_Tools
  28. {
  29. public partial class Main : Form
  30. {
  31. string _Account, _Password, _UserName;
  32. DataTable dt;
  33. Timer loadTime;
  34. string minTime, maxTime;
  35. string curRule, curRuleLeng;
  36. int ishaveInd;
  37. Timer File_timer;
  38. Timer File_timer1;
  39. string saveFiles;
  40. int currentNum = 1;
  41. private CancellationTokenSource _currentOperationCts;
  42. public Main(string account, string password)
  43. {
  44. _Account = account;
  45. _Password = password;
  46. InitializeComponent();
  47. }
  48. private void Main_Load(object sender, EventArgs e)
  49. {
  50. currUser.Text = "当前账户: " + _Account;
  51. dt = ConnectDB.ExecuteSelect($"select * from employee where em_code = '{_Account}'");
  52. if (dt.Rows.Count > 0)
  53. {
  54. _UserName = dt.Rows[0]["em_name"].ToString();
  55. }
  56. loadTime_Tick(null, null);
  57. loadTime = new Timer();
  58. loadTime.Interval = 1000;
  59. loadTime.Tick += loadTime_Tick;
  60. loadTime.Start();
  61. SN.SelectAll();
  62. SN.Focus();
  63. settingLeftInput1.Text = BaseUtil.GetCacheData("SettingCount").ToString();
  64. settingLeftInput2.Text = BaseUtil.GetCacheData("SettingVolume").ToString();
  65. dSum.Text = BaseUtil.GetCacheData("SettingVolume").ToString();
  66. settingRightInput1.Text = BaseUtil.GetCacheData("SettingNGPath").ToString();
  67. settingRightInput2.Text = BaseUtil.GetCacheData("SettingExportPath").ToString();
  68. QDcheckbox1.Checked = true;
  69. QDdtp2.Value = QDdtp1.Value.AddDays(1);
  70. rulesQuery_Click(null, null);
  71. QDquery_Click(null, null);
  72. saveFiles = Path.Combine(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).FullName, $"FtpFiles");
  73. if (!Directory.Exists(saveFiles))
  74. {
  75. Directory.CreateDirectory(saveFiles);
  76. }
  77. //saveFiles = Path.Combine(saveFiles, DateTime.Now.ToString("yyyyMMdd"));
  78. //if (!Directory.Exists(saveFiles))
  79. //{
  80. // Directory.CreateDirectory(saveFiles);
  81. //}
  82. File_timer = new Timer();
  83. File_timer.Interval = 30 * 1000;
  84. File_timer.Tick += Timer_Tick;
  85. timerVal.Text = "30";
  86. FileCountVal.Text = "10";
  87. FtpPathVal.Text = "ftp://10.18.13.48:21";
  88. handExeVal.Text = "120";
  89. File_timer1 = new Timer();
  90. File_timer1.Interval = Convert.ToInt32(handExeVal.Text) * 1000;
  91. File_timer1.Tick += FileTimer_Tick;
  92. }
  93. private void SN_KeyDown(object sender, KeyEventArgs e)
  94. {
  95. if (e.KeyCode != Keys.Enter) return;
  96. if (CheckEnter()) return;
  97. bool checkRes = true;
  98. if (radio1.Checked)
  99. {
  100. dt = ConnectDB.ExecuteSelect($@"SELECT COUNT(1) sum FROM dcrlogexcel WHERE item = '{SN.Text.Trim()}'");
  101. if (dt.Rows[0]["sum"].ToString() == "0")
  102. {
  103. PlaySound("NG");
  104. MessageBox.Show($"{SN.Text.Trim()},没有DCR测试数据", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  105. checkRes = false;
  106. return;
  107. }
  108. }
  109. if (FormMethods.IsCheckSNRules(curRule, SN.Text.Trim(), curRuleLeng))
  110. {
  111. PlaySound("NG");
  112. MessageBox.Show($"{SN.Text.Trim()},不符合条码规则", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  113. checkRes = false;
  114. return;
  115. }
  116. ishaveInd = -1;
  117. if (Datas.Rows.Count > 0)
  118. {
  119. foreach (DataGridViewRow item in Datas.Rows)
  120. {
  121. if (SN.Text.Trim() == item.Cells[0].Value.ToString())
  122. {
  123. ishaveInd = Datas.Rows.IndexOf(item);
  124. }
  125. }
  126. }
  127. if (ishaveInd >= 0)
  128. {
  129. int iCou = Convert.ToInt32(Datas.Rows[ishaveInd].Cells[2].Value);
  130. iCou += 1;
  131. Datas.Rows[ishaveInd].Cells[3].Value = currTime.Text;
  132. Datas.Rows[ishaveInd].Cells[6].Value = checkRes ? "OK" : "NG";
  133. PlaySound("OK");
  134. }
  135. else
  136. {
  137. DataGridViewRow row = new DataGridViewRow();
  138. row.CreateCells(Datas);
  139. row.Cells[0].Value = SN.Text.Trim();
  140. row.Cells[1].Value = BoxNo.Text.Trim();
  141. row.Cells[2].Value = 1;
  142. row.Cells[3].Value = currTime.Text;
  143. row.Cells[4].Value = _UserName;
  144. row.Cells[5].Value = radio1.Checked ? "是" : "否";
  145. row.Cells[6].Value = checkRes ? "OK" : "NG";
  146. Datas.Rows.Add(row);
  147. PlaySound("OK");
  148. Datas.FirstDisplayedScrollingRowIndex = Datas.Rows.Count - 1;
  149. if (ChangeDetail())
  150. {
  151. SN.Text = "";
  152. BoxNo.Text = "";
  153. dCount.Text = "0";
  154. Datas.Rows.Clear();
  155. BoxNo.Focus();
  156. BoxNo.SelectAll();
  157. }
  158. }
  159. }
  160. private bool ChangeDetail()
  161. {
  162. int inputSum = Convert.ToInt32(dCount.Text);
  163. dCount.Text = (inputSum + 1).ToString();
  164. if(Convert.ToInt32(dCount.Text) == Convert.ToInt32(dSum.Text))
  165. {
  166. foreach (DataGridViewRow item in Datas.Rows)
  167. {
  168. int insertCount = ConnectDB.ExecuteInsert($@"INSERT INTO g_packing_sncheck (work_order,part_no,sn,outbox_no,
  169. count,update_time,update_name,check_id,rule_name,rule_value)
  170. VALUES ( '', '', '{item.Cells[0].Value}', '{item.Cells[1].Value}',
  171. '{item.Cells[2].Value}',sysdate,'{_UserName}',packcheckid_seq.NEXTVAL,'{dRules.Text.Trim()}','{curRule}' )");
  172. }
  173. return true;
  174. }
  175. else
  176. {
  177. return false;
  178. }
  179. }
  180. private void BoxNo_KeyDown(object sender, KeyEventArgs e)
  181. {
  182. if (e.KeyCode != Keys.Enter) return;
  183. if (CheckEnter()) return;
  184. if (Datas.Rows.Count > 0)
  185. {
  186. foreach(DataGridViewRow item in Datas.Rows)
  187. {
  188. item.Cells[1].Value = BoxNo.Text.Trim();
  189. }
  190. }
  191. BoxNo.Enabled = false;
  192. SN.SelectAll();
  193. SN.Focus();
  194. }
  195. private bool CheckEnter()
  196. {
  197. if (string.IsNullOrEmpty(settingLeftInput1.Text))
  198. {
  199. MessageBox.Show("请维护列表记录数", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  200. return true;
  201. }
  202. if (string.IsNullOrEmpty(settingLeftInput2.Text))
  203. {
  204. MessageBox.Show("请维护箱内容量", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  205. return true;
  206. }
  207. if (!Regex.IsMatch(dSum.Text, @"^[1-9]\d*$"))
  208. {
  209. MessageBox.Show("箱内容量维护应为正整数", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  210. return true;
  211. }
  212. if (string.IsNullOrEmpty(dRules.Text))
  213. {
  214. MessageBox.Show("请选择条码规则", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  215. return true;
  216. }
  217. if (dRules.Enabled)
  218. {
  219. MessageBox.Show("请选择确认条码规则", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  220. return true;
  221. }
  222. return false;
  223. }
  224. private void settingLeftSubmit_Click(object sender, EventArgs e)
  225. {
  226. if (string.IsNullOrEmpty(settingLeftInput1.Text))
  227. {
  228. MessageBox.Show("请输入列表记录数", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  229. return;
  230. }
  231. if (string.IsNullOrEmpty(settingLeftInput2.Text))
  232. {
  233. MessageBox.Show("请输入箱内容量", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  234. return;
  235. }
  236. BaseUtil.SetCacheData("SettingCount", settingLeftInput1.Text);
  237. BaseUtil.SetCacheData("SettingVolume", settingLeftInput2.Text);
  238. dSum.Text = BaseUtil.GetCacheData("SettingVolume").ToString();
  239. MessageBox.Show("已提交扫描设置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  240. }
  241. private void settingRightSubmit_Click(object sender, EventArgs e)
  242. {
  243. if (string.IsNullOrEmpty(settingRightInput2.Text))
  244. {
  245. MessageBox.Show("请选择导出文件目录", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  246. return;
  247. }
  248. if(!string.IsNullOrEmpty(settingRightInput1.Text)) BaseUtil.SetCacheData("SettingNGPath", settingRightInput1.Text);
  249. BaseUtil.SetCacheData("SettingExportPath", settingRightInput2.Text);
  250. MessageBox.Show("已提交文件设置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  251. }
  252. private void QDquery_Click(object sender, EventArgs e)
  253. {
  254. StringBuilder filterStr = new StringBuilder();
  255. if (!string.IsNullOrEmpty(QDInput1.Text))
  256. {
  257. filterStr.Append($"WHERE instr(SN,'{QDInput1.Text}') > 0");
  258. }
  259. if (!string.IsNullOrEmpty(QDInput2.Text))
  260. {
  261. if (filterStr.Length == 0)
  262. {
  263. filterStr.Append($"WHERE instr(OUTBOX_NO,'{QDInput2.Text}') > 0");
  264. }
  265. else
  266. {
  267. filterStr.Append($" and instr(OUTBOX_NO, '{QDInput2.Text}') > 0");
  268. }
  269. }
  270. if (QDcheckbox1.Checked)
  271. {
  272. string dtp1 = QDdtp1.Value.ToString("yyyy-MM-dd 00:00:00");
  273. string dtp2 = QDdtp2.Value.ToString("yyyy-MM-dd 00:00:00");
  274. if (filterStr.Length == 0)
  275. {
  276. filterStr.Append($"WHERE update_time > TO_DATE('{dtp1}','YYYY-MM-DD HH24:MI:SS') AND update_time <= TO_DATE('{dtp2}','YYYY-MM-DD HH24:MI:SS')");
  277. }
  278. else
  279. {
  280. filterStr.Append($" AND update_time > TO_DATE('{dtp1}','YYYY-MM-DD HH24:MI:SS') AND update_time <= TO_DATE('{dtp2}','YYYY-MM-DD HH24:MI:SS')");
  281. }
  282. }
  283. dt = ConnectDB.ExecuteSelect($@"SELECT sn dqsn,outbox_no dqoutbox_no,count dqcount,
  284. update_time dqupdate_time,update_name dqname,rule_name dqrule_name,rule_value dqrule_value
  285. FROM g_packing_sncheck {filterStr.ToString()} ORDER BY sn,update_time desc");
  286. QDDatas.DataSource = dt;
  287. }
  288. private void QDexport_Click(object sender, EventArgs e)
  289. {
  290. if(QDDatas.Rows.Count == 0)
  291. {
  292. MessageBox.Show("请先查询出导出数据", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  293. return;
  294. }
  295. if (string.IsNullOrEmpty(settingRightInput2.Text))
  296. {
  297. MessageBox.Show("请先在设置中选择导出路径", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  298. return;
  299. }
  300. Application excelApp = null;
  301. Workbook workbook = null;
  302. Worksheet worksheet = null;
  303. Range range = null;
  304. string tempTemplatePath = null;
  305. try
  306. {
  307. string exportPath = Path.Combine(settingRightInput2.Text, DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".xlsx");
  308. if (string.IsNullOrEmpty(settingRightInput2.Text) || !Directory.Exists(settingRightInput2.Text))
  309. {
  310. MessageBox.Show($"输出目录不存在: {settingRightInput2.Text}", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  311. return;
  312. }
  313. byte[] templateBytes = Resources.exportModel; // 假设Resources.exportModel是有效的资源
  314. if (templateBytes == null || templateBytes.Length == 0)
  315. {
  316. MessageBox.Show("未能加载模板文件", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  317. return;
  318. }
  319. tempTemplatePath = Path.GetTempFileName().Replace(".tmp", ".xlsx");
  320. File.WriteAllBytes(tempTemplatePath, templateBytes);
  321. excelApp = new Application();
  322. excelApp.Visible = false;
  323. excelApp.DisplayAlerts = false;
  324. workbook = excelApp.Workbooks.Open(tempTemplatePath);
  325. object sheetIndex = 1;
  326. worksheet = (Worksheet)workbook.Worksheets[sheetIndex];
  327. int startRow = 2;
  328. int dataRowsCount = QDDatas.Rows.Count;
  329. for (int i = 0; i < QDDatas.Rows.Count; i++)
  330. {
  331. worksheet.Cells[startRow + i, 1] = i + 1; // 改为从1开始编号,更符合Excel习惯
  332. worksheet.Cells[startRow + i, 2] = QDDatas.Rows[i].Cells[0].Value?.ToString();
  333. }
  334. int endRow = startRow + dataRowsCount - 1;
  335. range = worksheet.Range[worksheet.Cells[startRow, 1], worksheet.Cells[endRow, 2]];
  336. range.HorizontalAlignment = XlHAlign.xlHAlignCenter; // 水平居中
  337. range.VerticalAlignment = XlVAlign.xlVAlignCenter; // 垂直居中
  338. worksheet.Columns.AutoFit();
  339. // 修复SaveAs方法,使用正确的参数
  340. workbook.SaveAs(
  341. Filename: exportPath,
  342. FileFormat: XlFileFormat.xlOpenXMLWorkbook,
  343. Password: Type.Missing,
  344. WriteResPassword: Type.Missing,
  345. ReadOnlyRecommended: Type.Missing,
  346. CreateBackup: Type.Missing,
  347. AccessMode: XlSaveAsAccessMode.xlExclusive,
  348. ConflictResolution: Type.Missing,
  349. AddToMru: false,
  350. TextCodepage: Type.Missing,
  351. TextVisualLayout: Type.Missing,
  352. Local: Type.Missing
  353. );
  354. MessageBox.Show($"Excel文件已成功导出到: {exportPath}", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
  355. }
  356. catch (Exception ex)
  357. {
  358. MessageBox.Show($"生成 Excel 文件时出错: {ex.Message}", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  359. }
  360. finally
  361. {
  362. // 正确释放COM对象
  363. if (worksheet != null)
  364. {
  365. try
  366. {
  367. Marshal.ReleaseComObject(worksheet);
  368. }
  369. catch { }
  370. worksheet = null;
  371. }
  372. if (workbook != null)
  373. {
  374. try
  375. {
  376. workbook.Close(false);
  377. Marshal.ReleaseComObject(workbook);
  378. }
  379. catch { }
  380. workbook = null;
  381. }
  382. if (excelApp != null)
  383. {
  384. try
  385. {
  386. excelApp.Quit();
  387. Marshal.ReleaseComObject(excelApp);
  388. }
  389. catch { }
  390. excelApp = null;
  391. }
  392. if (!string.IsNullOrEmpty(tempTemplatePath) && File.Exists(tempTemplatePath))
  393. {
  394. try
  395. {
  396. File.Delete(tempTemplatePath);
  397. }
  398. catch (Exception ex)
  399. {
  400. }
  401. }
  402. GC.Collect();
  403. GC.WaitForPendingFinalizers();
  404. }
  405. }
  406. private void rulesAdd_Click(object sender, EventArgs e)
  407. {
  408. StringBuilder filterStr = new StringBuilder();
  409. if (!string.IsNullOrEmpty(rulesInput1.Text))
  410. {
  411. filterStr.Append($"WHERE instr(RULE_NAME,'{rulesInput1.Text}') > 0");
  412. }
  413. if (!string.IsNullOrEmpty(rulesInput2.Text))
  414. {
  415. if(filterStr.Length == 0)
  416. {
  417. filterStr.Append($"WHERE instr(RULE_VALUE,'{rulesInput2.Text}') > 0");
  418. }
  419. else
  420. {
  421. filterStr.Append($" and instr(RULE_VALUE, '{rulesInput2.Text}') > 0");
  422. }
  423. }
  424. Form rulesList = new RulesList("Add",_UserName);
  425. if (rulesList.ShowDialog() == DialogResult.OK)
  426. {
  427. MessageBox.Show("新增规则成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  428. dt = ConnectDB.ExecuteSelect($@"SELECT RULE_ID ruleId,RULE_NAME RulesCol1, RULE_VALUE RulesCol2, RELE_REMARK RulesCol3,
  429. RULE_LENGTH RulesCol4,to_char(UPDATE_TIME, 'YYYY-MM-DD HH:Mi:SS') RulesCol5,UPDATE_USER RulesCol6 FROM g_packing_rules {filterStr.ToString()} order by UPDATE_TIME desc");
  430. RulesDatas.DataSource = dt;
  431. }
  432. }
  433. private void rulesQuery_Click(object sender, EventArgs e)
  434. {
  435. StringBuilder filterStr = new StringBuilder();
  436. if (!string.IsNullOrEmpty(rulesInput1.Text))
  437. {
  438. filterStr.Append($"WHERE instr(RULE_NAME,'{rulesInput1.Text}') > 0");
  439. }
  440. if (!string.IsNullOrEmpty(rulesInput2.Text))
  441. {
  442. if (filterStr.Length == 0)
  443. {
  444. filterStr.Append($"WHERE instr(RULE_VALUE,'{rulesInput2.Text}') > 0");
  445. }
  446. else
  447. {
  448. filterStr.Append($" and instr(RULE_VALUE, '{rulesInput2.Text}') > 0");
  449. }
  450. }
  451. dt = ConnectDB.ExecuteSelect($@"SELECT RULE_ID ruleId,RULE_NAME RulesCol1, RULE_VALUE RulesCol2, RELE_REMARK RulesCol3,
  452. RULE_LENGTH RulesCol4,to_char(UPDATE_TIME, 'YYYY-MM-DD HH:Mi:SS') RulesCol5,UPDATE_USER RulesCol6 FROM g_packing_rules {filterStr.ToString()} order by UPDATE_TIME desc");
  453. RulesDatas.DataSource = dt;
  454. }
  455. private void RulesDatas_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
  456. {
  457. if (e.RowIndex >= 0 && !RulesDatas.Rows[e.RowIndex].IsNewRow)
  458. {
  459. DataGridView dgv = sender as DataGridView;
  460. if (dgv != null)
  461. {
  462. DataGridViewRow selectedRow = dgv.Rows[e.RowIndex];
  463. string RULE_ID = selectedRow.Cells[0].Value.ToString();
  464. StringBuilder filterStr = new StringBuilder();
  465. if (!string.IsNullOrEmpty(rulesInput1.Text))
  466. {
  467. filterStr.Append($"WHERE instr(RULE_NAME,'{rulesInput1.Text}') > 0");
  468. }
  469. if (!string.IsNullOrEmpty(rulesInput2.Text))
  470. {
  471. if (filterStr.Length == 0)
  472. {
  473. filterStr.Append($"WHERE instr(RULE_VALUE,'{rulesInput2.Text}') > 0");
  474. }
  475. else
  476. {
  477. filterStr.Append($" and instr(RULE_VALUE, '{rulesInput2.Text}') > 0");
  478. }
  479. }
  480. Form rulesList = new RulesList("Modify",RULE_ID, _UserName);
  481. if (rulesList.ShowDialog() == DialogResult.OK)
  482. {
  483. MessageBox.Show("修改规则成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  484. dt = ConnectDB.ExecuteSelect($@"SELECT RULE_ID ruleId,RULE_NAME RulesCol1, RULE_VALUE RulesCol2, RELE_REMARK RulesCol3,
  485. RULE_LENGTH RulesCol4,to_char(UPDATE_TIME, 'YYYY-MM-DD HH:Mi:SS') RulesCol5,UPDATE_USER RulesCol6 FROM g_packing_rules {filterStr.ToString()} order by UPDATE_TIME desc");
  486. RulesDatas.DataSource = dt;
  487. }
  488. }
  489. }
  490. }
  491. private void RulesDatas_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
  492. {
  493. if (e.RowIndex >= 0 && !RulesDatas.Rows[e.RowIndex].IsNewRow)
  494. {
  495. DataGridView dgv = sender as DataGridView;
  496. if (dgv != null)
  497. {
  498. DataGridViewRow selectedRow = dgv.Rows[e.RowIndex];
  499. if (dRules.Enabled)
  500. {
  501. dRules.Text = selectedRow.Cells[1].Value.ToString();
  502. curRule = selectedRow.Cells[2].Value.ToString();
  503. curRuleLeng = selectedRow.Cells[4].Value.ToString();
  504. }
  505. }
  506. }
  507. }
  508. private void boxBtn_Click(object sender, EventArgs e)
  509. {
  510. BoxNo.Enabled = true;
  511. BoxNo.Focus();
  512. BoxNo.SelectAll();
  513. }
  514. private void settingRightInput1_Click(object sender, EventArgs e)
  515. {
  516. using (OpenFileDialog openFileDialog = new OpenFileDialog())
  517. {
  518. openFileDialog.Title = "请选择告警文件";
  519. openFileDialog.Filter = "可执行文件 (*.wav)|*.wav|所有文件 (*.*)|*.*";
  520. openFileDialog.FilterIndex = 1;
  521. openFileDialog.RestoreDirectory = true;
  522. if (!string.IsNullOrEmpty(settingRightInput1.Text) && System.IO.File.Exists(settingRightInput1.Text))
  523. {
  524. openFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(settingRightInput1.Text);
  525. }
  526. else
  527. {
  528. openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
  529. }
  530. if (openFileDialog.ShowDialog() == DialogResult.OK)
  531. {
  532. settingRightInput1.Text = openFileDialog.FileName;
  533. }
  534. }
  535. }
  536. private void settingRightInput2_Click(object sender, EventArgs e)
  537. {
  538. using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
  539. {
  540. folderBrowserDialog.Description = "请选择导出文件夹";
  541. if (!string.IsNullOrEmpty(settingRightInput2.Text) && System.IO.Directory.Exists(settingRightInput2.Text))
  542. {
  543. folderBrowserDialog.SelectedPath = settingRightInput2.Text;
  544. }
  545. else
  546. {
  547. folderBrowserDialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // folderBrowserDialog.SelectedPath = "";
  548. }
  549. if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
  550. {
  551. settingRightInput2.Text = folderBrowserDialog.SelectedPath;
  552. }
  553. }
  554. }
  555. private void QDdtp1_ValueChanged(object sender, EventArgs e)
  556. {
  557. if (QDdtp1.Value > QDdtp2.Value)
  558. {
  559. QDdtp1.Value = QDdtp2.Value.AddDays(-1);
  560. MessageBox.Show("时间不得大于最大时间", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  561. return;
  562. }
  563. minTime = QDdtp1.Value.ToString("yyyy-mm-dd hh:mm:ss");
  564. }
  565. private void DRulesBtn_Click(object sender, EventArgs e)
  566. {
  567. if (string.IsNullOrEmpty(dRules.Text))
  568. {
  569. MessageBox.Show("请选择条码规则", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  570. return;
  571. }
  572. dRules.Enabled = false;
  573. }
  574. private void DRulesBtn1_Click(object sender, EventArgs e)
  575. {
  576. dRules.Enabled = true;
  577. }
  578. private void QDdtp2_ValueChanged(object sender, EventArgs e)
  579. {
  580. if (QDdtp2.Value < QDdtp1.Value)
  581. {
  582. QDdtp2.Value = QDdtp1.Value.AddDays(1);
  583. MessageBox.Show("时间不得小于最小时间", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  584. return;
  585. }
  586. maxTime = QDdtp2.Value.ToString("yyyy-mm-dd hh:mm:ss");
  587. }
  588. private void PlaySound(string type)
  589. {
  590. if (type == "OK")
  591. {
  592. ShowMsg.Text = "Pass";
  593. ShowMsg.BackColor = Color.LawnGreen;
  594. }
  595. else
  596. {
  597. ShowMsg.Text = "Fail";
  598. ShowMsg.BackColor = Color.Red;
  599. }
  600. Task.Run(() => {
  601. if (type == "OK")
  602. {
  603. using (var stream = UAS_Tools_HY.Properties.Resources.OK)
  604. {
  605. SoundPlayer player = new SoundPlayer(stream);
  606. player.Play();
  607. }
  608. }
  609. else
  610. {
  611. if (string.IsNullOrEmpty(settingRightInput1.Text))
  612. {
  613. using (var stream = UAS_Tools_HY.Properties.Resources.NG)
  614. {
  615. SoundPlayer player = new SoundPlayer(stream);
  616. player.Play();
  617. }
  618. }
  619. else
  620. {
  621. string customPath = settingRightInput1.Text.Trim();
  622. if (File.Exists(customPath))
  623. {
  624. SoundPlayer player = new SoundPlayer(customPath);
  625. player.Play();
  626. }
  627. }
  628. }
  629. });
  630. }
  631. public void loadTime_Tick(object sender, EventArgs e)
  632. {
  633. string currentDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
  634. currTime.Text = currentDate;
  635. handTime.Value = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,DateTime.Now.Hour,0, 0);
  636. }
  637. private async void FtpConnect_Click(object sender, EventArgs e)
  638. {
  639. if(FtpConnect.Text == "开启连接")
  640. {
  641. if (string.IsNullOrEmpty(FtpAccountVal.Text))
  642. {
  643. LogMessage("NG,请填写ftp账户");
  644. return;
  645. }
  646. if (string.IsNullOrEmpty(FtpPwVal.Text))
  647. {
  648. LogMessage("NG,请填写ftp密码");
  649. return;
  650. }
  651. if (string.IsNullOrEmpty(timerVal.Text))
  652. {
  653. LogMessage("NG,请填写间隔抓取文件时间");
  654. return;
  655. }
  656. if (string.IsNullOrEmpty(FtpPathVal.Text))
  657. {
  658. LogMessage("NG,请填写ftp抓取路径地址");
  659. return;
  660. }
  661. if (string.IsNullOrEmpty(FileCountVal.Text))
  662. {
  663. LogMessage("NG,请填写打包文件数");
  664. return;
  665. }
  666. FtpConnect.Enabled = false;
  667. FtpConnect.Text = "连接中...";
  668. LogMessage("开始测试连接...");
  669. bool testConnect = await TestFtpConnection(FtpPathVal.Text.Trim(), FtpAccountVal.Text.Trim(), FtpPwVal.Text.Trim());
  670. if (testConnect)
  671. {
  672. FtpAccountVal.Enabled = false;
  673. FtpPwVal.Enabled = false;
  674. timerVal.Enabled = false;
  675. FtpPathVal.Enabled = false;
  676. FileCountVal.Enabled = false;
  677. FtpConnect.Text = "关闭连接";
  678. FtpListen.Enabled = true;
  679. }
  680. else
  681. {
  682. FtpConnect.Enabled = true;
  683. FtpConnect.Text = "开启连接";
  684. }
  685. }
  686. else if(FtpConnect.Text == "关闭连接")
  687. {
  688. FtpAccountVal.Enabled = true;
  689. FtpPwVal.Enabled = true;
  690. timerVal.Enabled = true;
  691. FtpPathVal.Enabled = true;
  692. FileCountVal.Enabled = true;
  693. FtpConnect.Text = "开启连接";
  694. FtpListen.Enabled = false;
  695. }
  696. }
  697. public async Task<bool> TestFtpConnection(string ftpServer, string username, string password)
  698. {
  699. try
  700. {
  701. var request = (FtpWebRequest)WebRequest.Create(ftpServer);
  702. request.Method = WebRequestMethods.Ftp.ListDirectory;
  703. request.Credentials = new NetworkCredential(username, password);
  704. request.UsePassive = true;
  705. request.UseBinary = true;
  706. request.KeepAlive = false;
  707. request.Timeout = 10000;
  708. using (var response = await request.GetResponseAsync() as FtpWebResponse)
  709. {
  710. await Task.Run(() =>
  711. {
  712. LogMessage($"OK,FTP连接成功: {response.StatusDescription}");
  713. });
  714. return true;
  715. }
  716. }
  717. catch (WebException ex)
  718. {
  719. await Task.Run(() =>
  720. {
  721. if (ex.Response is FtpWebResponse response)
  722. {
  723. LogMessage($"NG,FTP连接失败,错误码: {(int)response.StatusCode} - {response.StatusDescription}");
  724. }
  725. else
  726. {
  727. LogMessage("NG,连接异常: " + ex.Message);
  728. }
  729. });
  730. return false;
  731. }
  732. catch (Exception ex)
  733. {
  734. await Task.Run(() =>
  735. {
  736. LogMessage($"NG,连接失败: " + ex.Message);
  737. });
  738. return false;
  739. }
  740. }
  741. private void FtpListen_Click(object sender, EventArgs e)
  742. {
  743. File_timer.Interval = Convert.ToInt32(timerVal.Text.Trim()) * 1000;
  744. if (FtpListen.Text == "开启监听")
  745. {
  746. FtpListen.Text = "关闭监听";
  747. FtpConnect.Enabled = false;
  748. File_timer.Start();
  749. Timer_Tick(null, null);
  750. }
  751. else if (FtpListen.Text == "关闭监听")
  752. {
  753. FtpListen.Text = "开启监听";
  754. FtpConnect.Enabled = true;
  755. File_timer.Stop();
  756. }
  757. }
  758. private void MsgBox_DrawItem(object sender, DrawItemEventArgs e)
  759. {
  760. e.DrawBackground();
  761. Brush mybsh = Brushes.Black;
  762. string msgStr = MsgBox.Items[e.Index].ToString();
  763. Console.WriteLine();
  764. if (MsgBox.Items[e.Index].ToString().Contains("OK"))
  765. {
  766. mybsh = Brushes.Green;
  767. }
  768. else if (MsgBox.Items[e.Index].ToString().Contains("NG"))
  769. {
  770. mybsh = Brushes.Red;
  771. }
  772. e.DrawFocusRectangle();
  773. e.Graphics.DrawString(MsgBox.Items[e.Index].ToString(), e.Font, mybsh, e.Bounds, StringFormat.GenericDefault);
  774. }
  775. private void LogMessage(string message)
  776. {
  777. if (MsgBox.InvokeRequired)
  778. {
  779. MsgBox.Invoke(new Action<string>(LogMessage), message);
  780. return;
  781. }
  782. MsgBox.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  783. MsgBox.TopIndex = MsgBox.Items.Count - 1;
  784. MsgBox.DrawMode = DrawMode.OwnerDrawFixed;
  785. }
  786. private void Timer_Tick(object sender, EventArgs e)
  787. {
  788. try
  789. {
  790. string childSaveFiles = Path.Combine(saveFiles, DateTime.Now.ToString("yyyyMMdd"));
  791. if (!Directory.Exists(childSaveFiles))
  792. {
  793. Directory.CreateDirectory(childSaveFiles);
  794. currentNum = 1;
  795. LogMessage($"创建本地文件夹: {childSaveFiles}");
  796. }
  797. string ftpServer = FtpPathVal.Text.Trim();
  798. string remoteFolderPath = "";
  799. string username = FtpAccountVal.Text.Trim();
  800. string password = FtpPwVal.Text.Trim();
  801. List<string> fileList = GetFtpFileList(ftpServer, remoteFolderPath, username, password);
  802. if (fileList.Count == 0)
  803. {
  804. LogMessage($"远程文件夹 '{remoteFolderPath}' 中没有文件");
  805. return;
  806. }
  807. int successCount = 0;
  808. int failCount = 0;
  809. LogMessage($"开始下载 {fileList.Count} 个文件...");
  810. foreach (string remoteFile in fileList)
  811. {
  812. if (!Directory.Exists(childSaveFiles))
  813. {
  814. Directory.CreateDirectory(childSaveFiles);
  815. }
  816. string remoteFilePath = $"{remoteFolderPath.TrimEnd('/')}/{remoteFile}";
  817. string localFilePath = Path.Combine(childSaveFiles, remoteFile);
  818. if (DownloadSingleFile(ftpServer, remoteFilePath, localFilePath, username, password))
  819. {
  820. successCount++;
  821. }
  822. else
  823. {
  824. failCount++;
  825. }
  826. string[] files = Directory.GetFiles(childSaveFiles);
  827. string zipFilePath = Path.Combine(Path.GetDirectoryName(childSaveFiles), Path.GetFileName(childSaveFiles) + $"-{currentNum}.zip");
  828. if (Convert.ToInt32(FileCountVal.Text.Trim()) == files.Length)
  829. {
  830. CompressFolder(childSaveFiles, zipFilePath);
  831. currentNum++;
  832. }
  833. }
  834. LogMessage($"下载完成: 成功 {successCount} 个, 失败 {failCount} 个");
  835. }
  836. catch (Exception ex)
  837. {
  838. LogMessage($"NG,自动获取文件失败,Error: {ex.Message}");
  839. }
  840. }
  841. private List<string> GetFtpFileList(string ftpServer, string folderPath, string username, string password)
  842. {
  843. List<string> fileList = new List<string>();
  844. try
  845. {
  846. string uri = $"{ftpServer.TrimEnd('/')}/{folderPath.TrimStart('/')}";
  847. var request = (FtpWebRequest)WebRequest.Create(uri);
  848. request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  849. request.Credentials = new NetworkCredential(username, password);
  850. request.UsePassive = true;
  851. request.UseBinary = true;
  852. request.KeepAlive = false;
  853. using (var response = (FtpWebResponse)request.GetResponse())
  854. using (var responseStream = response.GetResponseStream())
  855. using (var reader = new StreamReader(responseStream))
  856. {
  857. string line;
  858. while ((line = reader.ReadLine()) != null)
  859. {
  860. if (!string.IsNullOrWhiteSpace(line))
  861. {
  862. string[] parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  863. if (parts.Length >= 3)
  864. {
  865. //string fileName = parts[8];
  866. //if (!parts[0].StartsWith("d") && fileName != "." && fileName != "..")
  867. //{
  868. // fileList.Add(fileName);
  869. //}
  870. string fileName = parts[parts.Length - 1];
  871. if (fileName.Contains("."))
  872. {
  873. fileList.Add(fileName);
  874. }
  875. }
  876. }
  877. }
  878. }
  879. }
  880. catch (Exception ex)
  881. {
  882. LogMessage($"获取文件列表失败: {ex.Message}");
  883. }
  884. return fileList;
  885. }
  886. private bool DownloadSingleFile(string ftpServer, string remoteFilePath, string localFilePath, string username, string password)
  887. {
  888. try
  889. {
  890. bool downloadSuccess = false;
  891. string uri = $"{ftpServer.TrimEnd('/')}/{remoteFilePath.TrimStart('/')}";
  892. var request = (FtpWebRequest)WebRequest.Create(uri);
  893. request.Method = WebRequestMethods.Ftp.DownloadFile;
  894. request.Credentials = new NetworkCredential(username, password);
  895. request.UsePassive = true;
  896. request.UseBinary = true;
  897. request.KeepAlive = false;
  898. using (var response = (FtpWebResponse)request.GetResponse())
  899. using (var responseStream = response.GetResponseStream())
  900. using (var fileStream = File.Create(localFilePath))
  901. {
  902. byte[] buffer = new byte[4096];
  903. int bytesRead;
  904. while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
  905. {
  906. fileStream.Write(buffer, 0, bytesRead);
  907. }
  908. downloadSuccess = true;
  909. LogMessage($"OK,文件下载成功: {remoteFilePath} -> {localFilePath}");
  910. if (downloadSuccess)
  911. {
  912. var deleteRequest = (FtpWebRequest)WebRequest.Create(uri);
  913. deleteRequest.Method = WebRequestMethods.Ftp.DeleteFile;
  914. deleteRequest.Credentials = new NetworkCredential(username, password);
  915. deleteRequest.UsePassive = true;
  916. deleteRequest.KeepAlive = false;
  917. using (var deleteResponse = (FtpWebResponse)deleteRequest.GetResponse())
  918. {
  919. LogMessage($"OK,服务器文件删除成功: {remoteFilePath}");
  920. }
  921. }
  922. return true;
  923. }
  924. }
  925. catch (WebException ex)
  926. {
  927. if (ex.Response is FtpWebResponse response)
  928. {
  929. LogMessage($"NG,下载失败 {remoteFilePath}: {(int)response.StatusCode} - {response.StatusDescription}");
  930. }
  931. else
  932. {
  933. LogMessage($"NG,下载失败 {remoteFilePath}: {ex.Message}");
  934. }
  935. return false;
  936. }
  937. catch (Exception ex)
  938. {
  939. LogMessage($"NG,下载失败 {remoteFilePath}: {ex.Message}");
  940. return false;
  941. }
  942. }
  943. private string CreateFtpDirectoryIfNotExists(string ftpDirectoryPath, string username, string password)
  944. {
  945. try
  946. {
  947. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpDirectoryPath);
  948. request.Method = WebRequestMethods.Ftp.MakeDirectory;
  949. request.Credentials = new NetworkCredential(username, password);
  950. request.UsePassive = true;
  951. request.UseBinary = true;
  952. request.KeepAlive = false;
  953. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  954. {
  955. response.Close();
  956. return "OK,目录创建成功: " + response.StatusDescription;
  957. }
  958. }
  959. catch (WebException ex)
  960. {
  961. if (ex.Response is FtpWebResponse response && response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
  962. {
  963. return "OK,目录已存在: " + response.StatusDescription;
  964. }
  965. else
  966. {
  967. return "NG,创建目录时发生错误: " + ex.Message;
  968. }
  969. }
  970. }
  971. private void CompressFile(string sourceFile, string zipPath)
  972. {
  973. try
  974. {
  975. using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Create))
  976. using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
  977. {
  978. string fileName = Path.GetFileName(sourceFile);
  979. ZipArchiveEntry readmeEntry = archive.CreateEntry(fileName);
  980. using (Stream stream = readmeEntry.Open())
  981. using (FileStream fileStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
  982. {
  983. fileStream.CopyTo(stream);
  984. }
  985. }
  986. LogMessage($"OK,文件已压缩到:{zipPath}");
  987. }
  988. catch (Exception ex)
  989. {
  990. LogMessage($"NG,压缩失败:{ex.Message}");
  991. }
  992. }
  993. private void CompressFolder(string sourceFolder, string zipPath)
  994. {
  995. try
  996. {
  997. if (File.Exists(zipPath))
  998. {
  999. try
  1000. {
  1001. File.Delete(zipPath);
  1002. }
  1003. catch (IOException ex)
  1004. {
  1005. LogMessage($"NG,无法删除已存在的文件,可能被其他程序占用:{ex.Message}");
  1006. return;
  1007. }
  1008. catch (UnauthorizedAccessException ex)
  1009. {
  1010. LogMessage($"NG,没有权限删除文件:{ex.Message}");
  1011. return;
  1012. }
  1013. }
  1014. ZipFile.CreateFromDirectory(sourceFolder, zipPath);
  1015. Directory.Delete(sourceFolder, true);
  1016. LogMessage($"OK,文件已压缩到:{zipPath}");
  1017. }
  1018. catch (UnauthorizedAccessException ex)
  1019. {
  1020. LogMessage($"NG,访问被拒绝:{ex.Message}");
  1021. }
  1022. catch (Exception ex)
  1023. {
  1024. LogMessage($"NG,压缩失败:{ex.Message}");
  1025. }
  1026. }
  1027. private void listenVal_Click(object sender, EventArgs e)
  1028. {
  1029. using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
  1030. {
  1031. folderDialog.Description = "请选择监控文件夹";
  1032. folderDialog.SelectedPath = listenVal.Text;
  1033. if (folderDialog.ShowDialog() == DialogResult.OK)
  1034. {
  1035. listenVal.Text = folderDialog.SelectedPath;
  1036. }
  1037. }
  1038. }
  1039. private void handPathVal_Click(object sender, EventArgs e)
  1040. {
  1041. using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
  1042. {
  1043. folderDialog.Description = "请选择导出文件夹";
  1044. folderDialog.SelectedPath = handPathVal.Text;
  1045. if (folderDialog.ShowDialog() == DialogResult.OK)
  1046. {
  1047. handPathVal.Text = folderDialog.SelectedPath;
  1048. }
  1049. }
  1050. }
  1051. private void buildConfirm_Click(object sender, EventArgs e)
  1052. {
  1053. if (buildConfirm.Text == "确定")
  1054. {
  1055. if (string.IsNullOrEmpty(handExeVal.Text))
  1056. {
  1057. LogMessage($"NG,请填写处理间隔时间");
  1058. return;
  1059. }
  1060. if (string.IsNullOrEmpty(listenVal.Text))
  1061. {
  1062. LogMessage($"NG,请填写监控路径");
  1063. return;
  1064. }
  1065. if (string.IsNullOrEmpty(handPathVal.Text))
  1066. {
  1067. LogMessage($"NG,请填写导出路径");
  1068. return;
  1069. }
  1070. handExeVal.Enabled = false;
  1071. handTime.Enabled = false;
  1072. listenVal.Enabled = false;
  1073. handPathVal.Enabled = false;
  1074. buildConfirm.Text = "取消";
  1075. }
  1076. else
  1077. {
  1078. handExeVal.Enabled = true;
  1079. handTime.Enabled = true;
  1080. listenVal.Enabled = true;
  1081. handPathVal.Enabled = true;
  1082. buildConfirm.Text = "确定";
  1083. }
  1084. }
  1085. private void buildStart_Click(object sender, EventArgs e)
  1086. {
  1087. if(buildStart.Text == "开启处理")
  1088. {
  1089. buildStart.Text = "关闭处理";
  1090. File_timer1.Interval = Convert.ToInt32(handExeVal.Text) * 60 * 1000;
  1091. File_timer1.Start();
  1092. FileTimer_Tick(null, null);
  1093. }
  1094. else
  1095. {
  1096. buildStart.Text = "开启处理";
  1097. File_timer.Stop();
  1098. }
  1099. }
  1100. private async void FileTimer_Tick(object sender, EventArgs e)
  1101. {
  1102. _currentOperationCts?.Cancel();
  1103. _currentOperationCts = new CancellationTokenSource();
  1104. try
  1105. {
  1106. await Task.Run(() => ProcessFilesInternal(_currentOperationCts.Token));
  1107. }
  1108. catch (OperationCanceledException)
  1109. {
  1110. LogMessage("文件处理操作被新任务取消。");
  1111. }
  1112. catch (Exception ex)
  1113. {
  1114. LogMessage($"NG,定时器任务启动失败: {ex}");
  1115. }
  1116. /*try
  1117. {
  1118. string[] txtFiles = Directory.GetFiles(listenVal.Text, $"*.json");
  1119. string currentHour = DateTime.Now.ToString("yyyyMMdd_hh");
  1120. string outPath = Path.Combine(handPathVal.Text, currentHour + "_Count_" + txtFiles.Length);
  1121. if (!Directory.Exists(outPath))
  1122. {
  1123. Directory.CreateDirectory(outPath);
  1124. }
  1125. foreach (string file in txtFiles)
  1126. {
  1127. string targetFile = Path.Combine(outPath, Path.GetFileName(file));
  1128. if (File.Exists(targetFile))
  1129. {
  1130. File.Delete(targetFile);
  1131. }
  1132. File.Move(file, targetFile);
  1133. }
  1134. string zipPath = outPath + ".zip";
  1135. if (File.Exists(zipPath))
  1136. {
  1137. File.Delete(zipPath);
  1138. }
  1139. ZipFile.CreateFromDirectory(outPath, zipPath);
  1140. LogMessage($"OK,文件已压缩到:{zipPath}");
  1141. }
  1142. catch(Exception ex)
  1143. {
  1144. LogMessage($"NG,解析文件列表失败: {ex.Message}");
  1145. }*/
  1146. }
  1147. private void ProcessFilesInternal(CancellationToken cancellationToken)
  1148. {
  1149. try
  1150. {
  1151. var txtFiles = Directory.EnumerateFiles(listenVal.Text, "*.json", SearchOption.TopDirectoryOnly).ToList();
  1152. int fileCount = txtFiles.Count;
  1153. if (fileCount == 0)
  1154. {
  1155. LogMessage("没有找到需要处理的 .json 文件。");
  1156. return;
  1157. }
  1158. cancellationToken.ThrowIfCancellationRequested();
  1159. LogMessage($"已找到找到 {fileCount} 个json文件,开始处理...");
  1160. string currentHour = DateTime.Now.ToString("yyyyMMdd_HH");
  1161. string outPath = Path.Combine(handPathVal.Text, $"{currentHour}_{Convert.ToInt32(handExeVal.Text)}_Count_{fileCount}");
  1162. cancellationToken.ThrowIfCancellationRequested();
  1163. if (!Directory.Exists(outPath))
  1164. {
  1165. Directory.CreateDirectory(outPath);
  1166. }
  1167. int movedCount = 0;
  1168. foreach (string file in txtFiles)
  1169. {
  1170. cancellationToken.ThrowIfCancellationRequested();
  1171. string targetFile = Path.Combine(outPath, Path.GetFileName(file));
  1172. if (File.Exists(targetFile))
  1173. {
  1174. File.Delete(targetFile);
  1175. }
  1176. File.Move(file, targetFile);
  1177. movedCount++;
  1178. if (movedCount % 1000 == 0)
  1179. {
  1180. LogMessage($"已移动 {movedCount}/{fileCount} 个文件...");
  1181. }
  1182. }
  1183. LogMessage($"成功移动 {movedCount} 个文件到 '{outPath}'");
  1184. string zipPath = outPath + ".zip";
  1185. cancellationToken.ThrowIfCancellationRequested();
  1186. if (File.Exists(zipPath))
  1187. {
  1188. File.Delete(zipPath);
  1189. }
  1190. ZipFile.CreateFromDirectory(outPath, zipPath);
  1191. //Directory.Delete(outPath, true);
  1192. LogMessage($"OK, {fileCount} 个文件已成功压缩到: {zipPath}");
  1193. }
  1194. catch (OperationCanceledException)
  1195. {
  1196. LogMessage("OK, 文件处理操作被用户取消。");
  1197. }
  1198. catch (UnauthorizedAccessException ex)
  1199. {
  1200. LogMessage($"NG, 访问被拒绝,可能没有足够权限读写文件或目录: {ex.Message}");
  1201. }
  1202. catch (DirectoryNotFoundException ex)
  1203. {
  1204. LogMessage($"NG, 指定的路径不存在: {ex.Message}");
  1205. }
  1206. catch (IOException ex)
  1207. {
  1208. LogMessage($"NG, 文件 I/O 错误: {ex.Message}");
  1209. }
  1210. catch (Exception ex)
  1211. {
  1212. LogMessage($"NG, 文件处理过程中发生未知错误: {ex}");
  1213. }
  1214. }
  1215. }
  1216. }