Query_SOP.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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. ps_prodcode.Text = GetProdCodeFromFileName(FilePath.Text.Substring(FilePath.Text.LastIndexOf(@"\") + 1).Replace(".xls", "").Replace(".xlsx", ""));
  76. OperatResult.AppendText("解析SOP编号: " + ps_prodcode.Text + "\n");
  77. pr_code_Leave(new object(), new EventArgs());
  78. Workbook workbook = new Workbook(FilePath.Text);
  79. string pnTools = GetPnToolsFromExcel(workbook);
  80. if (pnTools == "")
  81. {
  82. pnTools = pr_code.Text;
  83. }
  84. OperatResult.AppendText("解析PN/TOOLS: " + pnTools + "\n");
  85. // 匹配已存在的旧数据:新旧版本号不同(如(R0)/(R1))、或历史数据存的是完整文件名,都按中间不变的SOP编号(如WI-LC-31-544)来匹配
  86. List<string> oldIds = FindDuplicatedSopIds(ps_prodcode.Text);
  87. if (oldIds.Count > 0)
  88. {
  89. // 已存在相同SOP编号:先删除原明细和主表数据,后面重新插入
  90. for (int d = 0; d < oldIds.Count; d++)
  91. {
  92. dh.ExecuteSql("delete from ProductSOPdetail where psd_psid='" + oldIds[d] + "'", "delete");
  93. dh.ExecuteSql("delete from productsop where ps_id='" + oldIds[d] + "'", "delete");
  94. }
  95. OperatResult.AppendText("已删除原SOP编号【" + ps_prodcode.Text + "】的旧数据(" + oldIds.Count + "条),重新插入\n");
  96. }
  97. string code = LogicHandler.GetPiInoutCode("ProductSOP", "1");
  98. ps_code.Text = code;
  99. if (VaildDate.Checked)
  100. {
  101. 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'),'" + pnTools + "')", "insert");
  102. }
  103. else
  104. {
  105. 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','" + pnTools + "')", "insert");
  106. }
  107. List<Worksheet> list = new List<Worksheet>();
  108. List<string> filename = new List<string>();
  109. if (VaildDate.Checked)
  110. {
  111. dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "',ps_prcode='" + pnTools + "',ps_vailddate=to_date('" + DateCode.Value.ToString("yyyy-MM-dd") + "','yyyy-mm-dd') where ps_prodcode='" + ps_prodcode.Text + "'", "update");
  112. }
  113. else
  114. {
  115. dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "',ps_prcode='" + pnTools + "' where ps_prodcode='" + ps_prodcode.Text + "'", "update");
  116. }
  117. OperatResult.AppendText("一共Sheet: " + workbook.Worksheets.Count + "\n");
  118. for (int i = 0; i < workbook.Worksheets.Count; i++)
  119. {
  120. OperatResult.AppendText("正在解析Sheet" + workbook.Worksheets[i].Name + "\n");
  121. if (JPG.Checked)
  122. {
  123. //try
  124. //{
  125. // ---------- 输出目录 ----------
  126. if (!Directory.Exists(Application.StartupPath + @"\" + ps_prodcode.Text))
  127. {
  128. Directory.CreateDirectory(Application.StartupPath + @"\" + ps_prodcode.Text);
  129. }
  130. string path = Application.StartupPath + @"\" + ps_prodcode.Text + @"\";
  131. Worksheet she = workbook.Worksheets[i];
  132. // ---------- 基础参数 ----------
  133. int contentMaxCol = she.Cells.MaxDataColumn;
  134. for (int p = 0; p < she.Pictures.Count; p++)
  135. {
  136. if (she.Pictures[p].LowerRightColumn > contentMaxCol)
  137. contentMaxCol = she.Pictures[p].LowerRightColumn;
  138. }
  139. for (int s = 0; s < she.Shapes.Count; s++)
  140. {
  141. if (she.Shapes[s].LowerRightColumn > contentMaxCol)
  142. contentMaxCol = she.Shapes[s].LowerRightColumn;
  143. }
  144. int lastColIndex = contentMaxCol + 3; // 额外留3列边距
  145. string lastColLetter = CellsHelper.ColumnIndexToName(lastColIndex);
  146. const int headerRows = 3;
  147. int dataRowsPerPage = int.Parse(RowCount.Value.ToString());
  148. int contentMaxRow = she.Cells.MaxDataRow;
  149. for (int p = 0; p < she.Pictures.Count; p++)
  150. {
  151. if (she.Pictures[p].LowerRightRow > contentMaxRow)
  152. contentMaxRow = she.Pictures[p].LowerRightRow;
  153. }
  154. for (int s = 0; s < she.Shapes.Count; s++)
  155. {
  156. if (she.Shapes[s].LowerRightRow > contentMaxRow)
  157. contentMaxRow = she.Shapes[s].LowerRightRow;
  158. }
  159. int actualDataRows = Math.Max(contentMaxRow + 1 - headerRows, 0);
  160. int totalPages = (int)Math.Ceiling(actualDataRows / (double)dataRowsPerPage);
  161. if (totalPages == 0) totalPages = 1;
  162. int totalRows = headerRows + totalPages * dataRowsPerPage;
  163. int totalDataRows = Math.Max(totalRows - headerRows, 0);
  164. int wmRowGlobal = int.Parse(Y.Value.ToString());
  165. int wmCol = int.Parse(X.Value.ToString());
  166. int imageIndex = 1;
  167. for (int page = 0; page < totalPages; page++)
  168. {
  169. // ---------- 1. 复制原表到临时工作表 ----------
  170. int newSheetIndex = workbook.Worksheets.Add();
  171. Worksheet newshe = workbook.Worksheets[newSheetIndex];
  172. newshe.Copy(she);
  173. newshe.Name = $"Temp_{page}";
  174. int dataStartRow = headerRows + page * dataRowsPerPage;
  175. int dataEndRow = Math.Min(headerRows + (page + 1) * dataRowsPerPage - 1, totalRows - 1);
  176. // ---------- 2. 按页过滤原表图片(Pictures) ----------
  177. for (int p = newshe.Pictures.Count - 1; p >= 0; p--)
  178. {
  179. Aspose.Cells.Drawing.Picture pic = newshe.Pictures[p];
  180. int topRow = pic.UpperLeftRow;
  181. bool isHeaderPic = topRow < headerRows;
  182. bool belongsToPage = topRow >= dataStartRow && topRow <= dataEndRow;
  183. if (!isHeaderPic && !belongsToPage)
  184. {
  185. newshe.Pictures.RemoveAt(p);
  186. }
  187. }
  188. // ---------- 3. 按页过滤原表形状(Shapes) ----------
  189. for (int s = newshe.Shapes.Count - 1; s >= 0; s--)
  190. {
  191. Aspose.Cells.Drawing.Shape shape;
  192. try {
  193. shape = newshe.Shapes[s];
  194. }
  195. catch { continue; }
  196. int topRow = shape.UpperLeftRow;
  197. bool isHeaderShape = topRow < headerRows;
  198. bool belongsToPage = topRow >= dataStartRow && topRow <= dataEndRow;
  199. if (!isHeaderShape && !belongsToPage)
  200. {
  201. try { newshe.Shapes.RemoveAt(s); }
  202. catch { shape.IsHidden = true; }
  203. }
  204. else {
  205. try
  206. {
  207. // 1. 启用文本自动换行
  208. shape.IsTextWrapped = true;
  209. Console.WriteLine(shape.Text);
  210. // 2. 获取文本对齐对象并设置内边距
  211. if (shape.TextBody != null && shape.TextBody.TextAlignment != null)
  212. {
  213. var textAlign = shape.TextBody.TextAlignment;
  214. textAlign.LeftMarginPt = 1;
  215. textAlign.RightMarginPt = 1;
  216. textAlign.TopMarginPt = 1;
  217. textAlign.BottomMarginPt = 1;
  218. }
  219. // 3. 设置文本对齐方式
  220. shape.TextVerticalAlignment = TextAlignmentType.Left;
  221. shape.TextHorizontalAlignment = TextAlignmentType.Left;
  222. // 4. 自动调整形状大小以适应文本(如果形状允许)
  223. if (shape.TextBody != null && shape.TextBody.TextAlignment != null)
  224. {
  225. shape.TextBody.TextAlignment.TextHorizontalOverflow = TextOverflowType.Ellipsis;
  226. }
  227. }
  228. catch (Exception ex)
  229. {
  230. // 某些形状可能不支持所有属性,忽略异常
  231. Console.WriteLine($"Shape优化失败: {ex.Message}");
  232. }
  233. }
  234. }
  235. // ---------- 4. 清空非本页单元格内容 ----------
  236. for (int r = 0; r < totalRows; r++)
  237. {
  238. if (r < headerRows) continue;
  239. if (r >= dataStartRow && r <= dataEndRow) continue;
  240. newshe.Cells.ClearRange(r, 0, r, lastColIndex);
  241. }
  242. // ---------- 5. 删除非本页整行 ----------
  243. for (int r = totalRows - 1; r >= 0; r--)
  244. {
  245. if (r < headerRows) continue;
  246. if (r >= dataStartRow && r <= dataEndRow) continue;
  247. newshe.Cells.DeleteRow(r);
  248. }
  249. // ---------- 6. 页面设置 ----------
  250. int printMaxRow = newshe.Cells.MaxDataRow;
  251. for (int p = 0; p < newshe.Pictures.Count; p++)
  252. {
  253. if (newshe.Pictures[p].LowerRightRow > printMaxRow)
  254. {
  255. printMaxRow = newshe.Pictures[p].LowerRightRow;
  256. }
  257. }
  258. for (int s = 0; s < newshe.Shapes.Count; s++)
  259. {
  260. if (newshe.Shapes[s].LowerRightRow > printMaxRow)
  261. {
  262. printMaxRow = newshe.Shapes[s].LowerRightRow;
  263. }
  264. }
  265. int newTotalRows = printMaxRow + 1;
  266. int pageHeight = headerRows + dataRowsPerPage;
  267. int printEndRow = Math.Max(newTotalRows, pageHeight);
  268. if (i == 0)
  269. newshe.PageSetup.PrintArea = $"A1:{lastColLetter}{25}";
  270. else
  271. newshe.PageSetup.PrintArea = $"A1:{lastColLetter}{printEndRow}";
  272. newshe.PageSetup.CenterHorizontally = true;
  273. newshe.PageSetup.CenterVertically = true;
  274. newshe.PageSetup.LeftMargin = 2;
  275. newshe.PageSetup.RightMargin = 2;
  276. newshe.PageSetup.TopMargin = 2;
  277. newshe.PageSetup.BottomMargin = 2;
  278. newshe.PageSetup.SetFooter(0, "");
  279. newshe.PageSetup.SetFooter(1, "");
  280. newshe.PageSetup.SetFooter(2, "");
  281. // ---------- 7. 插入水印 ----------
  282. if (File.Exists(PrintPath.Text))
  283. {
  284. int rowOffset = headerRows + int.Parse(Y.Value.ToString());
  285. newshe.Pictures.Add(rowOffset, int.Parse(X.Value.ToString()), PrintPath.Text);
  286. }
  287. // ---------- 8. 页脚 ----------
  288. string pageFooter = $"第 {imageIndex} 页 / 共 {totalPages} 页";
  289. newshe.PageSetup.SetFooter(1, pageFooter);
  290. // ==================★ 优化点:提高渲染分辨率(核心改动) ==================
  291. ImageOrPrintOptions options = new ImageOrPrintOptions();
  292. options.ImageFormat = ImageFormat.Png;
  293. options.OnePagePerSheet = true; // 保留:整页一张图
  294. options.PrintingPage = PrintingPageType.Default;
  295. // ★ 把默认 96 DPI 提高到 300 DPI,文字/表格瞬间变清晰(约放大3倍像素)
  296. options.HorizontalResolution = 300;
  297. options.VerticalResolution = 300;
  298. // ★ 开启抗锯齿,边缘更平滑(18.x 支持,可选)
  299. options.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  300. // ★ 文本渲染更清晰(可选)
  301. options.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
  302. // ==================★ 优化点结束 ==================
  303. SheetRender sr = new SheetRender(newshe, options);
  304. if (sr.PageCount > 0)
  305. {
  306. using (Bitmap bitmap = sr.ToImage(0))
  307. {
  308. string imagename = $"{she.Name}_{imageIndex}.png";
  309. string imagePath = Path.Combine(path, imagename);
  310. bitmap.Save(imagePath, ImageFormat.Png);
  311. OperatResult.AppendText("解析图片【" + imagePath + "】\n");
  312. // ---------- 10. 上传 ----------
  313. Dictionary<string, object> dic = new Dictionary<string, object>();
  314. dic.Add("em_name", "管理员");
  315. dic.Add("em_code", "ADMIN");
  316. dic.Add("caller", "ProductSOP");
  317. OperatResult.AppendText("上传文件【" + imagePath + "】\n");
  318. string fp_id = UploadFilesToRemoteUrl(
  319. "https://mes.lihantech.cn/mes/MEScommon/uploadFiles.action?_noc=1",
  320. imagePath, dic);
  321. // ---------- 11. 入库 ----------
  322. string ps_id = dh.getFieldDataByCondition(
  323. "ProductSOP", "ps_id", "ps_prodcode='" + ps_prodcode.Text + "'").ToString();
  324. dh.ExecuteSql(
  325. "insert into ProductSOPdetail(psd_id,psd_psid,psd_attach) " +
  326. "select ProductSOPdetail_seq.nextval,ps_id,'" + imagename + ";" + fp_id +
  327. "' from ProductSOP where ps_prodcode='" + ps_prodcode.Text + "'", "insert");
  328. }
  329. }
  330. // ---------- 12. 删除临时工作表 ----------
  331. workbook.Worksheets.RemoveAt(newSheetIndex);
  332. imageIndex++;
  333. }
  334. //}
  335. //catch (Exception ex)
  336. //{
  337. // OperatResult.AppendText(ex.Message + ex.StackTrace);
  338. //}
  339. }
  340. }
  341. }
  342. else if (PDF.Checked)
  343. {
  344. ps_prodcode.Text = GetProdCodeFromFileName(FilePath.Text.Substring(FilePath.Text.LastIndexOf(@"\") + 1).Replace(".pdf", ""));
  345. OperatResult.AppendText("解析SOP编号: " + ps_prodcode.Text + "\n");
  346. pr_code_Leave(new object(), new EventArgs());
  347. // 匹配已存在的旧数据:新旧版本号不同(如(R0)/(R1))、或历史数据存的是完整文件名,都按中间不变的SOP编号(如WI-LC-31-544)来匹配
  348. List<string> oldIds = FindDuplicatedSopIds(ps_prodcode.Text);
  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编号【" + ps_prodcode.Text + "】的旧数据(" + 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. /// </summary>
  444. private string GetPnToolsFromExcel(Workbook workbook)
  445. {
  446. List<string> values = new List<string>();
  447. for (int i = 0; i < workbook.Worksheets.Count; i++)
  448. {
  449. Worksheet she = workbook.Worksheets[i];
  450. Cells cells = she.Cells;
  451. int maxRow = cells.MaxDataRow;
  452. int maxCol = cells.MaxDataColumn;
  453. int headerCol = -1;
  454. int headerRow = -1;
  455. // 1. 先在单元格中查找PN/TOOLS标题
  456. for (int r = 0; r <= maxRow && headerCol < 0; r++)
  457. {
  458. for (int c = 0; c <= maxCol; c++)
  459. {
  460. object val = cells[r, c].Value;
  461. if (val == null) continue;
  462. string text = val.ToString().Trim().ToUpper();
  463. if (text.Contains("PN/TOOLS") || text.Contains("PN/TOOLS"))
  464. {
  465. headerCol = c;
  466. headerRow = r;
  467. break;
  468. }
  469. }
  470. }
  471. // 2. 单元格中没找到时,尝试从形状(文本框)标题中定位列
  472. if (headerCol < 0)
  473. {
  474. for (int s = 0; s < she.Shapes.Count; s++)
  475. {
  476. string shapeText;
  477. try { shapeText = she.Shapes[s].Text; }
  478. catch { continue; }
  479. if (shapeText != null && shapeText.Trim().ToUpper().Contains("PN/TOOLS"))
  480. {
  481. headerCol = she.Shapes[s].UpperLeftColumn;
  482. headerRow = she.Shapes[s].UpperLeftRow;
  483. break;
  484. }
  485. }
  486. }
  487. if (headerCol < 0) continue;
  488. // 3. 收集标题下方该列所有非空内容,去重(保持顺序)
  489. for (int r = headerRow + 1; r <= Math.Max(maxRow, cells.MaxDataRow); r++)
  490. {
  491. object val = cells[r, headerCol].Value;
  492. if (val == null) continue;
  493. string text = val.ToString().Trim();
  494. if (text != "" && !values.Contains(text))
  495. {
  496. values.Add(text);
  497. }
  498. }
  499. }
  500. return string.Join(",", values.ToArray());
  501. }
  502. /// <summary>
  503. /// 请求上传图片到阿里云
  504. /// </summary>
  505. /// <param name="url">上传地址</param>
  506. /// <param name="filepath">本地文件路径</param>
  507. /// <param name="dic">上传的数据信息</param>
  508. /// <returns></returns>
  509. public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic)
  510. {
  511. try
  512. {
  513. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
  514. ServicePointManager.DefaultConnectionLimit = 50;
  515. string boundary = DateTime.Now.Ticks.ToString("x");
  516. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  517. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  518. request.Method = "POST";
  519. request.Timeout = 10 * 10000;
  520. request.ContentType = "multipart/form-data; boundary=" + boundary;
  521. Stream rs = request.GetRequestStream();
  522. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  523. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  524. if (dic != null)
  525. {
  526. foreach (string key in dic.Keys)
  527. {
  528. rs.Write(boundarybytes, 0, boundarybytes.Length);
  529. string formitem = string.Format(formdataTemplate, key, dic[key]);
  530. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  531. rs.Write(formitembytes, 0, formitembytes.Length);
  532. }
  533. }
  534. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  535. {
  536. rs.Write(boundarybytes, 0, boundarybytes.Length);
  537. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  538. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  539. rs.Write(headerbytes, 0, headerbytes.Length);
  540. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  541. {
  542. var buffer = new byte[1024];
  543. var bytesRead = 0;
  544. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  545. {
  546. rs.Write(buffer, 0, bytesRead);
  547. }
  548. }
  549. var cr = Encoding.UTF8.GetBytes("\r\n");
  550. rs.Write(cr, 0, cr.Length);
  551. }
  552. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  553. var response = request.GetResponse() as HttpWebResponse;
  554. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  555. string Content = newReader.ReadToEnd();
  556. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  557. List<Dictionary<string, object>> dic2 = null;
  558. dic1 = BaseUtil.ToDictionary(Content);
  559. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  560. string fp_id = "";
  561. if (dic2[0]["filepath"] != null)
  562. {
  563. fp_id = dic2[0]["filepath"].ToString();
  564. }
  565. if (response.StatusCode == HttpStatusCode.OK)
  566. {
  567. return fp_id;
  568. }
  569. }
  570. catch (Exception e)
  571. {
  572. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP", "上传失败", ps_prodcode.Text, "");
  573. Console.WriteLine(e.Message + e.StackTrace);
  574. }
  575. return "";
  576. }
  577. private void ChooseFile_Click(object sender, EventArgs e)
  578. {
  579. ChoosePath.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls|(*.pdf)|*.pdf";
  580. DialogResult result = ChoosePath.ShowDialog();
  581. if (result == DialogResult.OK)
  582. {
  583. FilePath.Text = ChoosePath.FileName;
  584. }
  585. }
  586. private void UploadSOP_Click(object sender, EventArgs e)
  587. {
  588. Thread thread = new Thread(uploadfile);
  589. SetLoadingWindow stw = new SetLoadingWindow(thread, "上传文件");
  590. stw.StartPosition = FormStartPosition.CenterScreen;
  591. stw.ShowDialog();
  592. if (JPG.Checked)
  593. {
  594. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【图片格式】", "上传成功", ps_prodcode.Text, "");
  595. }
  596. else
  597. {
  598. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【PDF格式】", "上传成功", ps_prodcode.Text, "");
  599. }
  600. }
  601. private void OperatResult_TextChanged(object sender, EventArgs e)
  602. {
  603. //OperatResult.SelectionStart = Text.Length;
  604. OperatResult.ScrollToCaret();
  605. }
  606. private void SendSop_Click(object sender, EventArgs e)
  607. {
  608. try
  609. {
  610. if (ps_prodcode.Text == "")
  611. {
  612. MessageBox.Show("线别和SOP文档不能为空");
  613. return;
  614. }
  615. if (SendDGV.Rows.Count > 0)
  616. {
  617. List<Dictionary<string, string>> listr = new List<Dictionary<string, string>>();
  618. JavaScriptSerializer jss = new JavaScriptSerializer();
  619. Dictionary<string, object> map1 = new Dictionary<string, object>();
  620. Dictionary<string, object> map = new Dictionary<string, object>();
  621. string path;
  622. string pathroot = dh.GetConfig("filePathUrl", "sys").ToString();
  623. dh.ExecuteSql("insert into soprelease(SR_ID, sr_pscode, SR_STATUS, SR_MACHINETYPE,sr_releaseman,sr_readman)" +
  624. "select soprelease_seq.nextval,'" + ps_code.Text + "',0,'" + ps_prodcode.Text + "','" + User.UserName + "',em_code from employee ", "insert");
  625. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播成功", ps_prodcode.Text, "");
  626. MessageBox.Show("文档[" + ps_prodcode.Text + "]下放成功");
  627. }
  628. else
  629. {
  630. MessageBox.Show("产品编号" + ps_prodcode.Text + "未维护SOP文档");
  631. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败,未维护SOP文档", ps_prodcode.Text, "");
  632. }
  633. }
  634. catch (Exception ex)
  635. {
  636. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败", ps_prodcode.Text, "");
  637. Console.WriteLine(ex.Message + ex.StackTrace);
  638. }
  639. }
  640. public string encryptBASE64(string key)
  641. {
  642. Console.WriteLine(key);
  643. byte[] bytes = Encoding.Default.GetBytes(key);
  644. return Convert.ToBase64String(bytes);
  645. }
  646. public static string EncodeBase64(string code_type, string code)
  647. {
  648. string encode = "";
  649. byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
  650. try
  651. {
  652. encode = Convert.ToBase64String(bytes);
  653. }
  654. catch
  655. {
  656. encode = code;
  657. }
  658. return encode;
  659. }
  660. private void pr_code_KeyDown(object sender, KeyEventArgs e)
  661. {
  662. if (e.KeyCode == Keys.Enter)
  663. {
  664. LoadPrCode();
  665. }
  666. }
  667. private BindingSource bs = new BindingSource(); // 类成员变量
  668. private void LoadPrCode()
  669. {
  670. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "'", "select");
  671. if (dt.Rows.Count > 0)
  672. {
  673. string ps_id = dt.Rows[0]["ps_id"].ToString();
  674. dt = (DataTable)dh.ExecuteSql(@"select fp_name,fp_path,'' issend,psd_iskey
  675. from ProductSOPdetail
  676. left join filepath on FP_ID=substr(PSD_ATTACH,instr(PSD_ATTACH,';')+1)
  677. where psd_psid=" + ps_id, "select");
  678. if (dt.Rows.Count > 0)
  679. {
  680. // 在 UI 线程安全执行(如果已经在 UI 线程则直接调用)
  681. if (SendDGV.InvokeRequired)
  682. SendDGV.Invoke(new Action(() => BindData(dt)));
  683. else
  684. BindData(dt);
  685. }
  686. }
  687. }
  688. private void BindData(DataTable dt)
  689. {
  690. // 使用 BindingSource 避免直接置 null
  691. if (SendDGV.DataSource == null)
  692. {
  693. bs.DataSource = dt;
  694. SendDGV.DataSource = bs;
  695. }
  696. else
  697. {
  698. bs.DataSource = dt; // 直接替换内部数据,控件不会经历“无数据”状态
  699. }
  700. // 可选:刷新显示
  701. SendDGV.Refresh();
  702. }
  703. private void pr_code_Leave(object sender, EventArgs e)
  704. {
  705. //LoadPrCode();
  706. }
  707. bool AllChecked = false;
  708. private void ChooseALL_Click(object sender, EventArgs e)
  709. {
  710. if (AllChecked)
  711. {
  712. foreach (DataGridViewRow dr in SendDGV.Rows)
  713. dr.Cells[0].Value = false;
  714. AllChecked = false;
  715. }
  716. else
  717. {
  718. foreach (DataGridViewRow dr in SendDGV.Rows)
  719. dr.Cells[0].Value = true;
  720. AllChecked = true;
  721. }
  722. }
  723. private void ps_prodcode_UserControlTextChanged(object sender, EventArgs e)
  724. {
  725. LoadPrCode();
  726. }
  727. private void GetSOP_Click(object sender, EventArgs e)
  728. {
  729. LoadPrCode();
  730. }
  731. private void ChoosePrint_Click(object sender, EventArgs e)
  732. {
  733. ChoosePath.Filter = "(*.png)|*.png";
  734. DialogResult result = ChoosePath.ShowDialog();
  735. if (result == DialogResult.OK)
  736. {
  737. PrintPath.Text = ChoosePath.FileName;
  738. }
  739. }
  740. private void SendDGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
  741. {
  742. if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
  743. }
  744. }
  745. }