Main.cs 41 KB

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