Main.cs 56 KB

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