Query_SOP.cs 41 KB

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