Main.cs 43 KB

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