Query_SOP.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Windows.Forms;
  5. using System.Net;
  6. using System.Collections.Generic;
  7. using System.Threading;
  8. using System.Data;
  9. using System.Drawing.Imaging;
  10. using System.Drawing;
  11. using UAS_MES_NEW.Entity;
  12. using UAS_MES_NEW.PublicMethod;
  13. using Aspose.Cells;
  14. using UAS_MES_NEW.DataOperate;
  15. using UAS_MES_NEW.PublicForm;
  16. using Aspose.Cells.Drawing;
  17. using Aspose.Cells.Rendering;
  18. using System.Web.Script.Serialization;
  19. using Seagull.BarTender.Print;
  20. namespace UAS_MES_NEW.Query
  21. {
  22. public partial class Query_SOP : Form
  23. {
  24. DataHelper dh;
  25. string usercode;
  26. string sourcecode;
  27. DataTable Dbfind;
  28. public Query_SOP()
  29. {
  30. usercode = "";
  31. sourcecode = "";
  32. InitializeComponent();
  33. }
  34. private void Form3_Load(object sender, EventArgs e)
  35. {
  36. CheckForIllegalCrossThreadCalls = false;
  37. ps_prodcode.TableName = "productsop";
  38. ps_prodcode.SelectField = "ps_code # 流水号,ps_prodcode # SOP编号";
  39. ps_prodcode.FormName = Name;
  40. ps_prodcode.DBTitle = "SOP查询";
  41. ps_prodcode.SetValueField = new string[] { "ps_code", "ps_prodcode" };
  42. ps_prodcode.Condition = "";
  43. ps_prodcode.DbChange += nr_rule_DBChange;
  44. //pr_code.TableName = "product";
  45. //pr_code.SelectField = "pr_code # 产品编号,pr_detail # 产品名称,pr_spec # 产品规格";
  46. //pr_code.FormName = Name;
  47. //pr_code.DBTitle = "物料查询";
  48. //pr_code.Condition = "pr_code not like '%LX%'";
  49. //pr_code.SetValueField = new string[] { "pr_code" };
  50. DateTime targetMonth = DateCode.Value.AddMonths(2);
  51. DateTime endOfMonth = new DateTime(targetMonth.Year, targetMonth.Month,
  52. DateTime.DaysInMonth(targetMonth.Year, targetMonth.Month));
  53. DateCode.Value = endOfMonth;
  54. dh = SystemInf.dh;
  55. }
  56. private void nr_rule_DBChange(object sender, EventArgs e)
  57. {
  58. Dbfind = ps_prodcode.ReturnData;
  59. BaseUtil.SetFormValue(this.Controls, Dbfind);
  60. }
  61. void uploadfile()
  62. {
  63. if (FilePath.Text == "")
  64. {
  65. MessageBox.Show("文件不能为空!");
  66. return;
  67. }
  68. //if (pr_code.Text == "")
  69. //{
  70. // MessageBox.Show("产品编号不能为空!");
  71. // return;
  72. //}
  73. if (JPG.Checked)
  74. {
  75. string fileName = FilePath.Text.Substring(FilePath.Text.LastIndexOf(@"\") + 1).Replace(".xlsx", "").Replace(".xls", "");
  76. // 入库的ps_prodcode用完整文件名,如 (R1)WI-LC-31-544 冷端热端铜柱焊接组件检漏作业指导书x
  77. ps_prodcode.Text = fileName;
  78. // 匹配/删除时用截取出来的编号,如 WI-LC-31-544(新旧版本号都指向同一条数据)
  79. string prodCode = GetProdCodeFromFileName(fileName);
  80. OperatResult.AppendText("解析SOP编号: " + prodCode + ",文件名: " + ps_prodcode.Text + "\n");
  81. Workbook workbook = new Workbook(FilePath.Text);
  82. // 匹配已存在的旧数据:新旧版本号不同(如(R0)/(R1))、或历史数据存的是完整文件名,都按中间不变的SOP编号(如WI-LC-31-544)来匹配
  83. List<string> oldIds = FindDuplicatedSopIds(prodCode);
  84. if (oldIds.Count > 0)
  85. {
  86. // 已存在相同SOP编号:先删除原明细和主表数据,后面重新插入
  87. for (int d = 0; d < oldIds.Count; d++)
  88. {
  89. dh.ExecuteSql("delete from ProductSOPdetail where psd_psid='" + oldIds[d] + "'", "delete");
  90. dh.ExecuteSql("delete from productsop where ps_id='" + oldIds[d] + "'", "delete");
  91. }
  92. OperatResult.AppendText("已删除原SOP编号【" + prodCode + "】的旧数据(" + oldIds.Count + "条),重新插入\n");
  93. }
  94. string code = LogicHandler.GetPiInoutCode("ProductSOP", "1");
  95. ps_code.Text = code;
  96. if (VaildDate.Checked)
  97. {
  98. dh.ExecuteSql("insert into productsop(ps_id,ps_code,ps_prodcode,ps_indate,ps_inman,ps_status,ps_statuscode,ps_vailddate,ps_prcode)values(productsop_seq.nextval,'" + code + "','" + ps_prodcode.Text + "',sysdate,'" + User.UserName + "','在录入','ENTERING',to_date('" + DateCode.Value.ToString("yyyy-MM-dd") + "','yyyy-mm-dd'),'" + pr_code.Text + "')", "insert");
  99. }
  100. else
  101. {
  102. dh.ExecuteSql("insert into productsop(ps_id,ps_code,ps_prodcode,ps_indate,ps_inman,ps_status,ps_statuscode,ps_prcode)values(productsop_seq.nextval,'" + code + "','" + ps_prodcode.Text + "',sysdate,'" + User.UserName + "','在录入','ENTERING','" + pr_code.Text + "')", "insert");
  103. }
  104. List<Worksheet> list = new List<Worksheet>();
  105. List<string> filename = new List<string>();
  106. if (VaildDate.Checked)
  107. {
  108. dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "',ps_prcode='" + pr_code.Text + "',ps_vailddate=to_date('" + DateCode.Value.ToString("yyyy-MM-dd") + "','yyyy-mm-dd') where ps_prodcode='" + ps_prodcode.Text + "'", "update");
  109. }
  110. else
  111. {
  112. dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "',ps_prcode='" + pr_code.Text + "' where ps_prodcode='" + ps_prodcode.Text + "'", "update");
  113. }
  114. OperatResult.AppendText("一共Sheet: " + workbook.Worksheets.Count + "\n");
  115. for (int i = 0; i < workbook.Worksheets.Count; i++)
  116. {
  117. OperatResult.AppendText("正在解析Sheet" + workbook.Worksheets[i].Name + "\n");
  118. if (JPG.Checked)
  119. {
  120. //try
  121. //{
  122. // ---------- 输出目录 ----------
  123. if (!Directory.Exists(Application.StartupPath + @"\" + ps_prodcode.Text))
  124. {
  125. Directory.CreateDirectory(Application.StartupPath + @"\" + ps_prodcode.Text);
  126. }
  127. string path = Application.StartupPath + @"\" + ps_prodcode.Text + @"\";
  128. Worksheet she = workbook.Worksheets[i];
  129. // ---------- 基础参数 ----------
  130. int contentMaxCol = she.Cells.MaxDataColumn;
  131. for (int p = 0; p < she.Pictures.Count; p++)
  132. {
  133. if (she.Pictures[p].LowerRightColumn > contentMaxCol)
  134. contentMaxCol = she.Pictures[p].LowerRightColumn;
  135. }
  136. for (int s = 0; s < she.Shapes.Count; s++)
  137. {
  138. if (she.Shapes[s].LowerRightColumn > contentMaxCol)
  139. contentMaxCol = she.Shapes[s].LowerRightColumn;
  140. }
  141. int lastColIndex = contentMaxCol + 3; // 额外留3列边距
  142. string lastColLetter = CellsHelper.ColumnIndexToName(lastColIndex);
  143. const int headerRows = 3;
  144. int dataRowsPerPage = int.Parse(RowCount.Value.ToString());
  145. int contentMaxRow = she.Cells.MaxDataRow;
  146. for (int p = 0; p < she.Pictures.Count; p++)
  147. {
  148. if (she.Pictures[p].LowerRightRow > contentMaxRow)
  149. contentMaxRow = she.Pictures[p].LowerRightRow;
  150. }
  151. for (int s = 0; s < she.Shapes.Count; s++)
  152. {
  153. if (she.Shapes[s].LowerRightRow > contentMaxRow)
  154. contentMaxRow = she.Shapes[s].LowerRightRow;
  155. }
  156. int actualDataRows = Math.Max(contentMaxRow + 1 - headerRows, 0);
  157. int totalPages = (int)Math.Ceiling(actualDataRows / (double)dataRowsPerPage);
  158. if (totalPages == 0) totalPages = 1;
  159. int totalRows = headerRows + totalPages * dataRowsPerPage;
  160. int totalDataRows = Math.Max(totalRows - headerRows, 0);
  161. int wmRowGlobal = int.Parse(Y.Value.ToString());
  162. int wmCol = int.Parse(X.Value.ToString());
  163. int imageIndex = 1;
  164. for (int page = 0; page < totalPages; page++)
  165. {
  166. // ---------- 1. 复制原表到临时工作表 ----------
  167. int newSheetIndex = workbook.Worksheets.Add();
  168. Worksheet newshe = workbook.Worksheets[newSheetIndex];
  169. newshe.Copy(she);
  170. newshe.Name = $"Temp_{page}";
  171. int dataStartRow = headerRows + page * dataRowsPerPage;
  172. int dataEndRow = Math.Min(headerRows + (page + 1) * dataRowsPerPage - 1, totalRows - 1);
  173. // ---------- 2. 按页过滤原表图片(Pictures) ----------
  174. for (int p = newshe.Pictures.Count - 1; p >= 0; p--)
  175. {
  176. Aspose.Cells.Drawing.Picture pic = newshe.Pictures[p];
  177. int topRow = pic.UpperLeftRow;
  178. bool isHeaderPic = topRow < headerRows;
  179. bool belongsToPage = topRow >= dataStartRow && topRow <= dataEndRow;
  180. if (!isHeaderPic && !belongsToPage)
  181. {
  182. newshe.Pictures.RemoveAt(p);
  183. }
  184. }
  185. // ---------- 3. 按页过滤原表形状(Shapes) ----------
  186. for (int s = newshe.Shapes.Count - 1; s >= 0; s--)
  187. {
  188. Aspose.Cells.Drawing.Shape shape;
  189. try {
  190. shape = newshe.Shapes[s];
  191. }
  192. catch { continue; }
  193. int topRow = shape.UpperLeftRow;
  194. bool isHeaderShape = topRow < headerRows;
  195. bool belongsToPage = topRow >= dataStartRow && topRow <= dataEndRow;
  196. if (!isHeaderShape && !belongsToPage)
  197. {
  198. try { newshe.Shapes.RemoveAt(s); }
  199. catch { shape.IsHidden = true; }
  200. }
  201. else {
  202. try
  203. {
  204. // 1. 启用文本自动换行
  205. shape.IsTextWrapped = true;
  206. Console.WriteLine(shape.Text);
  207. // 2. 获取文本对齐对象并设置内边距
  208. if (shape.TextBody != null && shape.TextBody.TextAlignment != null)
  209. {
  210. var textAlign = shape.TextBody.TextAlignment;
  211. textAlign.LeftMarginPt = 1;
  212. textAlign.RightMarginPt = 1;
  213. textAlign.TopMarginPt = 1;
  214. textAlign.BottomMarginPt = 1;
  215. }
  216. // 3. 设置文本对齐方式
  217. shape.TextVerticalAlignment = TextAlignmentType.Left;
  218. shape.TextHorizontalAlignment = TextAlignmentType.Left;
  219. // 4. 自动调整形状大小以适应文本(如果形状允许)
  220. if (shape.TextBody != null && shape.TextBody.TextAlignment != null)
  221. {
  222. shape.TextBody.TextAlignment.TextHorizontalOverflow = TextOverflowType.Ellipsis;
  223. }
  224. }
  225. catch (Exception ex)
  226. {
  227. // 某些形状可能不支持所有属性,忽略异常
  228. Console.WriteLine($"Shape优化失败: {ex.Message}");
  229. }
  230. }
  231. }
  232. // ---------- 4. 清空非本页单元格内容 ----------
  233. for (int r = 0; r < totalRows; r++)
  234. {
  235. if (r < headerRows) continue;
  236. if (r >= dataStartRow && r <= dataEndRow) continue;
  237. newshe.Cells.ClearRange(r, 0, r, lastColIndex);
  238. }
  239. // ---------- 5. 删除非本页整行 ----------
  240. for (int r = totalRows - 1; r >= 0; r--)
  241. {
  242. if (r < headerRows) continue;
  243. if (r >= dataStartRow && r <= dataEndRow) continue;
  244. newshe.Cells.DeleteRow(r);
  245. }
  246. // ---------- 6. 页面设置 ----------
  247. int printMaxRow = newshe.Cells.MaxDataRow;
  248. for (int p = 0; p < newshe.Pictures.Count; p++)
  249. {
  250. if (newshe.Pictures[p].LowerRightRow > printMaxRow)
  251. {
  252. printMaxRow = newshe.Pictures[p].LowerRightRow;
  253. }
  254. }
  255. for (int s = 0; s < newshe.Shapes.Count; s++)
  256. {
  257. if (newshe.Shapes[s].LowerRightRow > printMaxRow)
  258. {
  259. printMaxRow = newshe.Shapes[s].LowerRightRow;
  260. }
  261. }
  262. int newTotalRows = printMaxRow + 1;
  263. int pageHeight = headerRows + dataRowsPerPage;
  264. int printEndRow = Math.Max(newTotalRows, pageHeight);
  265. if (i == 0)
  266. newshe.PageSetup.PrintArea = $"A1:{lastColLetter}{25}";
  267. else
  268. newshe.PageSetup.PrintArea = $"A1:{lastColLetter}{printEndRow}";
  269. newshe.PageSetup.CenterHorizontally = true;
  270. newshe.PageSetup.CenterVertically = true;
  271. newshe.PageSetup.LeftMargin = 2;
  272. newshe.PageSetup.RightMargin = 2;
  273. newshe.PageSetup.TopMargin = 2;
  274. newshe.PageSetup.BottomMargin = 2;
  275. newshe.PageSetup.SetFooter(0, "");
  276. newshe.PageSetup.SetFooter(1, "");
  277. newshe.PageSetup.SetFooter(2, "");
  278. // ---------- 7. 插入水印 ----------
  279. if (File.Exists(PrintPath.Text))
  280. {
  281. int rowOffset = headerRows + int.Parse(Y.Value.ToString());
  282. newshe.Pictures.Add(rowOffset, int.Parse(X.Value.ToString()), PrintPath.Text);
  283. }
  284. // ---------- 8. 页脚 ----------
  285. string pageFooter = $"第 {imageIndex} 页 / 共 {totalPages} 页";
  286. newshe.PageSetup.SetFooter(1, pageFooter);
  287. // ==================★ 优化点:提高渲染分辨率(核心改动) ==================
  288. ImageOrPrintOptions options = new ImageOrPrintOptions();
  289. options.ImageFormat = ImageFormat.Png;
  290. options.OnePagePerSheet = true; // 保留:整页一张图
  291. options.PrintingPage = PrintingPageType.Default;
  292. // ★ 把默认 96 DPI 提高到 300 DPI,文字/表格瞬间变清晰(约放大3倍像素)
  293. options.HorizontalResolution = 300;
  294. options.VerticalResolution = 300;
  295. // ★ 开启抗锯齿,边缘更平滑(18.x 支持,可选)
  296. options.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  297. // ★ 文本渲染更清晰(可选)
  298. options.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
  299. // ==================★ 优化点结束 ==================
  300. SheetRender sr = new SheetRender(newshe, options);
  301. if (sr.PageCount > 0)
  302. {
  303. using (Bitmap bitmap = sr.ToImage(0))
  304. {
  305. string imagename = $"{she.Name}_{imageIndex}.png";
  306. string imagePath = Path.Combine(path, imagename);
  307. bitmap.Save(imagePath, ImageFormat.Png);
  308. OperatResult.AppendText("解析图片【" + imagePath + "】\n");
  309. // ---------- 10. 上传 ----------
  310. Dictionary<string, object> dic = new Dictionary<string, object>();
  311. dic.Add("em_name", "管理员");
  312. dic.Add("em_code", "ADMIN");
  313. dic.Add("caller", "ProductSOP");
  314. OperatResult.AppendText("上传文件【" + imagePath + "】\n");
  315. string fp_id = UploadFilesToRemoteUrl(
  316. "https://mes.lihantech.cn/mes/MEScommon/uploadFiles.action?_noc=1",
  317. imagePath, dic);
  318. // ---------- 11. 入库 ----------
  319. string ps_id = dh.getFieldDataByCondition(
  320. "ProductSOP", "ps_id", "ps_prodcode='" + ps_prodcode.Text + "'").ToString();
  321. dh.ExecuteSql(
  322. "insert into ProductSOPdetail(psd_id,psd_psid,psd_attach) " +
  323. "select ProductSOPdetail_seq.nextval,ps_id,'" + imagename + ";" + fp_id +
  324. "' from ProductSOP where ps_prodcode='" + ps_prodcode.Text + "'", "insert");
  325. }
  326. }
  327. // ---------- 12. 删除临时工作表 ----------
  328. workbook.Worksheets.RemoveAt(newSheetIndex);
  329. imageIndex++;
  330. }
  331. //}
  332. //catch (Exception ex)
  333. //{
  334. // OperatResult.AppendText(ex.Message + ex.StackTrace);
  335. //}
  336. }
  337. }
  338. }
  339. else if (PDF.Checked)
  340. {
  341. string fileName = FilePath.Text.Substring(FilePath.Text.LastIndexOf(@"\") + 1).Replace(".pdf", "");
  342. // 入库的ps_prodcode用完整文件名
  343. ps_prodcode.Text = fileName;
  344. // 匹配/删除时用截取出来的编号
  345. string prodCode = GetProdCodeFromFileName(fileName);
  346. OperatResult.AppendText("解析SOP编号: " + prodCode + ",文件名: " + ps_prodcode.Text + "\n");
  347. // 匹配已存在的旧数据:新旧版本号不同(如(R0)/(R1))、或历史数据存的是完整文件名,都按中间不变的SOP编号(如WI-LC-31-544)来匹配
  348. List<string> oldIds = FindDuplicatedSopIds(prodCode);
  349. if (oldIds.Count > 0)
  350. {
  351. // 已存在相同SOP编号:先删除原明细和主表数据,后面重新插入
  352. for (int d = 0; d < oldIds.Count; d++)
  353. {
  354. dh.ExecuteSql("delete from ProductSOPdetail where psd_psid='" + oldIds[d] + "'", "delete");
  355. dh.ExecuteSql("delete from productsop where ps_id='" + oldIds[d] + "'", "delete");
  356. }
  357. OperatResult.AppendText("已删除原SOP编号【" + prodCode + "】的旧数据(" + oldIds.Count + "条),重新插入\n");
  358. }
  359. string code = LogicHandler.GetPiInoutCode("ProductSOP", "1");
  360. ps_code.Text = code;
  361. if (VaildDate.Checked)
  362. {
  363. dh.ExecuteSql("insert into productsop(ps_id,ps_code,ps_prodcode,ps_indate,ps_inman,ps_status,ps_statuscode,ps_vailddate)values(productsop_seq.nextval,'" + code + "','" + ps_prodcode.Text + "',sysdate,'" + User.UserName + "','在录入','ENTERING',to_date('" + DateCode.Value.ToString("yyyy-MM-dd") + "','yyyy-mm-dd'))", "insert");
  364. }
  365. else
  366. {
  367. dh.ExecuteSql("insert into productsop(ps_id,ps_code,ps_prodcode,ps_indate,ps_inman,ps_status,ps_statuscode)values(productsop_seq.nextval,'" + code + "','" + ps_prodcode.Text + "',sysdate,'" + User.UserName + "','在录入','ENTERING')", "insert");
  368. }
  369. if (VaildDate.Checked)
  370. {
  371. dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "',ps_vailddate=to_date('" + DateCode.Value.ToString("yyyy-MM-dd") + "','yyyy-mm-dd') where ps_prodcode='" + ps_prodcode.Text + "'", "update");
  372. }
  373. else
  374. {
  375. dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "' where ps_prodcode='" + ps_prodcode.Text + "'", "update");
  376. }
  377. Dictionary<string, object> dic = new Dictionary<string, object>();
  378. dic.Add("em_name", "管理员");
  379. dic.Add("em_code", "ADMIN");
  380. dic.Add("caller", "ProductSOP");
  381. OperatResult.AppendText("上传文件【" + ps_prodcode.Text + "" + "】\n");
  382. string fp_id = UploadFilesToRemoteUrl("https://mes.lihantech.cn/mes/MEScommon/uploadFiles.action?_noc=1", FilePath.Text, dic);
  383. string ps_id = dh.getFieldDataByCondition("ProductSOP", "ps_id", "ps_prodcode='" + ps_prodcode.Text + "'").ToString();
  384. dh.ExecuteSql("insert into ProductSOPdetail(psd_id,psd_psid,psd_attach) select ProductSOPdetail_seq.nextval,ps_id,'" + ps_prodcode.Text + ";" + fp_id + "' from ProductSOP where ps_prodcode='" + ps_prodcode.Text + "'", "insert");
  385. }
  386. }
  387. /// <summary>
  388. /// 从文件名中截取中间不变的SOP编号(忽略版本号)
  389. /// 新版本:(R1)WI-LC-31-544 冷端热端铜柱焊接组件检漏作业指导书x
  390. /// 旧版本:(R0)WI-LC-31-544 冷端热端铜柱焊接组件检漏作业指导书x
  391. /// 两者都取到同一个编号:WI-LC-31-544,按它来匹配是否重复
  392. /// 匹配不到编号时返回原文件名
  393. /// </summary>
  394. private string GetProdCodeFromFileName(string fileName)
  395. {
  396. if (string.IsNullOrEmpty(fileName))
  397. {
  398. return "";
  399. }
  400. string name = fileName.Trim();
  401. // 1. 去掉版本号,如 (R1)、(R0)、(R1)、(Rev.1),以及开头的 R1- / R0_ 这类写法
  402. name = System.Text.RegularExpressions.Regex.Replace(name, @"[((]\s*[Rr](?:[Ee][Vv]?)?\.?\s*\d+\s*[))]", " ");
  403. name = System.Text.RegularExpressions.Regex.Replace(name, @"^\s*[Rr](?:[Ee][Vv]?)?\.?\s*\d+\s*[-_\s]+", "");
  404. // 2. 取编号形式的字符串:由字母数字和短横线组成,如 WI-LC-31-544
  405. System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(
  406. name, "[A-Za-z0-9]+(?:-[A-Za-z0-9]+)+");
  407. if (m.Success)
  408. {
  409. return m.Value;
  410. }
  411. return name.Trim();
  412. }
  413. /// <summary>
  414. /// 按SOP编号查找productsop中已存在的重复数据(返回ps_id列表)
  415. /// 兼容两种情况:
  416. /// 1. 历史数据存的是完整文件名,如 (R0)WI-LC-31-544 冷端热端铜柱焊接组件检漏作业指导书x
  417. /// 2. 已按编号存储的数据,如 WI-LC-31-544
  418. /// 只要去掉版本号后中间那段编号与目标编号一致,就视为同一条SOP
  419. /// </summary>
  420. private List<string> FindDuplicatedSopIds(string prodcode)
  421. {
  422. List<string> ids = new List<string>();
  423. if (string.IsNullOrEmpty(prodcode))
  424. {
  425. return ids;
  426. }
  427. // 先用like把可能命中的记录捞出来,再在程序里按编号精确比对,避免 WI-LC-31-5441 这类误匹配
  428. DataTable dt = (DataTable)dh.ExecuteSql(
  429. "select ps_id,ps_prodcode from productsop where ps_prodcode like '%" + prodcode + "%'", "select");
  430. for (int i = 0; i < dt.Rows.Count; i++)
  431. {
  432. string dbValue = dt.Rows[i]["ps_prodcode"].ToString();
  433. if (dbValue.Trim().Equals(prodcode, StringComparison.OrdinalIgnoreCase)
  434. || GetProdCodeFromFileName(dbValue).Equals(prodcode, StringComparison.OrdinalIgnoreCase))
  435. {
  436. ids.Add(dt.Rows[i]["ps_id"].ToString());
  437. }
  438. }
  439. return ids;
  440. }
  441. /// <summary>
  442. /// 从Excel中查找标题为PN/TOOLS的列,收集该列标题下方所有非空内容,去重后用逗号拼接返回
  443. /// 值为JT开头的不记录
  444. /// 找不到PN/TOOLS列时返回null;找到但内容为空(或被JT过滤完)时返回空字符串
  445. /// </summary>
  446. /// <summary>
  447. /// 请求上传图片到阿里云
  448. /// </summary>
  449. /// <param name="url">上传地址</param>
  450. /// <param name="filepath">本地文件路径</param>
  451. /// <param name="dic">上传的数据信息</param>
  452. /// <returns></returns>
  453. public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic)
  454. {
  455. try
  456. {
  457. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
  458. ServicePointManager.DefaultConnectionLimit = 50;
  459. string boundary = DateTime.Now.Ticks.ToString("x");
  460. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  461. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  462. request.Method = "POST";
  463. request.Timeout = 10 * 10000;
  464. request.ContentType = "multipart/form-data; boundary=" + boundary;
  465. Stream rs = request.GetRequestStream();
  466. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  467. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  468. if (dic != null)
  469. {
  470. foreach (string key in dic.Keys)
  471. {
  472. rs.Write(boundarybytes, 0, boundarybytes.Length);
  473. string formitem = string.Format(formdataTemplate, key, dic[key]);
  474. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  475. rs.Write(formitembytes, 0, formitembytes.Length);
  476. }
  477. }
  478. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  479. {
  480. rs.Write(boundarybytes, 0, boundarybytes.Length);
  481. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  482. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  483. rs.Write(headerbytes, 0, headerbytes.Length);
  484. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  485. {
  486. var buffer = new byte[1024];
  487. var bytesRead = 0;
  488. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  489. {
  490. rs.Write(buffer, 0, bytesRead);
  491. }
  492. }
  493. var cr = Encoding.UTF8.GetBytes("\r\n");
  494. rs.Write(cr, 0, cr.Length);
  495. }
  496. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  497. var response = request.GetResponse() as HttpWebResponse;
  498. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  499. string Content = newReader.ReadToEnd();
  500. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  501. List<Dictionary<string, object>> dic2 = null;
  502. dic1 = BaseUtil.ToDictionary(Content);
  503. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  504. string fp_id = "";
  505. if (dic2[0]["filepath"] != null)
  506. {
  507. fp_id = dic2[0]["filepath"].ToString();
  508. }
  509. if (response.StatusCode == HttpStatusCode.OK)
  510. {
  511. return fp_id;
  512. }
  513. }
  514. catch (Exception e)
  515. {
  516. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP", "上传失败", ps_prodcode.Text, "");
  517. Console.WriteLine(e.Message + e.StackTrace);
  518. }
  519. return "";
  520. }
  521. private void ChooseFile_Click(object sender, EventArgs e)
  522. {
  523. ChoosePath.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls|(*.pdf)|*.pdf";
  524. DialogResult result = ChoosePath.ShowDialog();
  525. if (result == DialogResult.OK)
  526. {
  527. FilePath.Text = ChoosePath.FileName;
  528. }
  529. }
  530. private void UploadSOP_Click(object sender, EventArgs e)
  531. {
  532. Thread thread = new Thread(uploadfile);
  533. SetLoadingWindow stw = new SetLoadingWindow(thread, "上传文件");
  534. stw.StartPosition = FormStartPosition.CenterScreen;
  535. stw.ShowDialog();
  536. if (JPG.Checked)
  537. {
  538. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【图片格式】", "上传成功", ps_prodcode.Text, "");
  539. }
  540. else
  541. {
  542. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【PDF格式】", "上传成功", ps_prodcode.Text, "");
  543. }
  544. }
  545. private void OperatResult_TextChanged(object sender, EventArgs e)
  546. {
  547. //OperatResult.SelectionStart = Text.Length;
  548. OperatResult.ScrollToCaret();
  549. }
  550. private void SendSop_Click(object sender, EventArgs e)
  551. {
  552. try
  553. {
  554. if (ps_prodcode.Text == "")
  555. {
  556. MessageBox.Show("线别和SOP文档不能为空");
  557. return;
  558. }
  559. if (SendDGV.Rows.Count > 0)
  560. {
  561. List<Dictionary<string, string>> listr = new List<Dictionary<string, string>>();
  562. JavaScriptSerializer jss = new JavaScriptSerializer();
  563. Dictionary<string, object> map1 = new Dictionary<string, object>();
  564. Dictionary<string, object> map = new Dictionary<string, object>();
  565. string path;
  566. string pathroot = dh.GetConfig("filePathUrl", "sys").ToString();
  567. dh.ExecuteSql("insert into soprelease(SR_ID, sr_pscode, SR_STATUS, SR_MACHINETYPE,sr_releaseman,sr_readman)" +
  568. "select soprelease_seq.nextval,'" + ps_code.Text + "',0,'" + ps_prodcode.Text + "','" + User.UserName + "',em_code from employee ", "insert");
  569. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播成功", ps_prodcode.Text, "");
  570. MessageBox.Show("文档[" + ps_prodcode.Text + "]下放成功");
  571. }
  572. else
  573. {
  574. MessageBox.Show("产品编号" + ps_prodcode.Text + "未维护SOP文档");
  575. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败,未维护SOP文档", ps_prodcode.Text, "");
  576. }
  577. }
  578. catch (Exception ex)
  579. {
  580. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败", ps_prodcode.Text, "");
  581. Console.WriteLine(ex.Message + ex.StackTrace);
  582. }
  583. }
  584. public string encryptBASE64(string key)
  585. {
  586. Console.WriteLine(key);
  587. byte[] bytes = Encoding.Default.GetBytes(key);
  588. return Convert.ToBase64String(bytes);
  589. }
  590. public static string EncodeBase64(string code_type, string code)
  591. {
  592. string encode = "";
  593. byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
  594. try
  595. {
  596. encode = Convert.ToBase64String(bytes);
  597. }
  598. catch
  599. {
  600. encode = code;
  601. }
  602. return encode;
  603. }
  604. private void pr_code_KeyDown(object sender, KeyEventArgs e)
  605. {
  606. if (e.KeyCode == Keys.Enter)
  607. {
  608. LoadPrCode();
  609. }
  610. }
  611. private BindingSource bs = new BindingSource(); // 类成员变量
  612. private void LoadPrCode()
  613. {
  614. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "'", "select");
  615. if (dt.Rows.Count > 0)
  616. {
  617. string ps_id = dt.Rows[0]["ps_id"].ToString();
  618. dt = (DataTable)dh.ExecuteSql(@"select fp_name,fp_path,'' issend,psd_iskey
  619. from ProductSOPdetail
  620. left join filepath on FP_ID=substr(PSD_ATTACH,instr(PSD_ATTACH,';')+1)
  621. where psd_psid=" + ps_id, "select");
  622. if (dt.Rows.Count > 0)
  623. {
  624. // 在 UI 线程安全执行(如果已经在 UI 线程则直接调用)
  625. if (SendDGV.InvokeRequired)
  626. SendDGV.Invoke(new Action(() => BindData(dt)));
  627. else
  628. BindData(dt);
  629. }
  630. }
  631. }
  632. private void BindData(DataTable dt)
  633. {
  634. // 使用 BindingSource 避免直接置 null
  635. if (SendDGV.DataSource == null)
  636. {
  637. bs.DataSource = dt;
  638. SendDGV.DataSource = bs;
  639. }
  640. else
  641. {
  642. bs.DataSource = dt; // 直接替换内部数据,控件不会经历“无数据”状态
  643. }
  644. // 可选:刷新显示
  645. SendDGV.Refresh();
  646. }
  647. private void pr_code_Leave(object sender, EventArgs e)
  648. {
  649. //LoadPrCode();
  650. }
  651. bool AllChecked = false;
  652. private void ChooseALL_Click(object sender, EventArgs e)
  653. {
  654. if (AllChecked)
  655. {
  656. foreach (DataGridViewRow dr in SendDGV.Rows)
  657. dr.Cells[0].Value = false;
  658. AllChecked = false;
  659. }
  660. else
  661. {
  662. foreach (DataGridViewRow dr in SendDGV.Rows)
  663. dr.Cells[0].Value = true;
  664. AllChecked = true;
  665. }
  666. }
  667. private void ps_prodcode_UserControlTextChanged(object sender, EventArgs e)
  668. {
  669. LoadPrCode();
  670. }
  671. private void GetSOP_Click(object sender, EventArgs e)
  672. {
  673. LoadPrCode();
  674. }
  675. private void ChoosePrint_Click(object sender, EventArgs e)
  676. {
  677. ChoosePath.Filter = "(*.png)|*.png";
  678. DialogResult result = ChoosePath.ShowDialog();
  679. if (result == DialogResult.OK)
  680. {
  681. PrintPath.Text = ChoosePath.FileName;
  682. }
  683. }
  684. private void SendDGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
  685. {
  686. if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
  687. }
  688. }
  689. }