Query_SOP.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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 = FilePath.Text.Substring(FilePath.Text.LastIndexOf(@"\") + 1).Replace(".xls", "").Replace(".xlsx", "");
  76. pr_code_Leave(new object(), new EventArgs());
  77. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "' ", "select");
  78. if (dt.Rows.Count == 0)
  79. {
  80. string code = LogicHandler.GetPiInoutCode("ProductSOP", "1");
  81. ps_code.Text = code;
  82. if (VaildDate.Checked)
  83. {
  84. 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");
  85. }
  86. else
  87. {
  88. 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");
  89. }
  90. }
  91. else
  92. {
  93. string ps_id = dt.Rows[0]["ps_id"].ToString();
  94. dh.ExecuteSql("delete from ProductSOPdetail where psd_psid='" + ps_id + "'", "delete");
  95. ps_prodcode.Text = dt.Rows[0]["ps_prodcode"].ToString();
  96. }
  97. Workbook workbook = new Workbook(FilePath.Text);
  98. List<Worksheet> list = new List<Worksheet>();
  99. List<string> filename = new List<string>();
  100. if (VaildDate.Checked)
  101. {
  102. 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");
  103. }
  104. else
  105. {
  106. dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "' where ps_prodcode='" + ps_prodcode.Text + "'", "update");
  107. }
  108. OperatResult.AppendText("一共Sheet: " + workbook.Worksheets.Count + "\n");
  109. for (int i = 0; i < workbook.Worksheets.Count; i++)
  110. {
  111. OperatResult.AppendText("正在解析Sheet" + workbook.Worksheets[i].Name + "\n");
  112. if (JPG.Checked)
  113. {
  114. //try
  115. //{
  116. // ---------- 输出目录 ----------
  117. if (!Directory.Exists(Application.StartupPath + @"\" + ps_prodcode.Text))
  118. {
  119. Directory.CreateDirectory(Application.StartupPath + @"\" + ps_prodcode.Text);
  120. }
  121. string path = Application.StartupPath + @"\" + ps_prodcode.Text + @"\";
  122. Worksheet she = workbook.Worksheets[i];
  123. // ---------- 基础参数 ----------
  124. int contentMaxCol = she.Cells.MaxDataColumn;
  125. for (int p = 0; p < she.Pictures.Count; p++)
  126. {
  127. if (she.Pictures[p].LowerRightColumn > contentMaxCol)
  128. contentMaxCol = she.Pictures[p].LowerRightColumn;
  129. }
  130. for (int s = 0; s < she.Shapes.Count; s++)
  131. {
  132. if (she.Shapes[s].LowerRightColumn > contentMaxCol)
  133. contentMaxCol = she.Shapes[s].LowerRightColumn;
  134. }
  135. int lastColIndex = contentMaxCol; // 额外留3列边距
  136. string lastColLetter = CellsHelper.ColumnIndexToName(lastColIndex);
  137. const int headerRows = 3;
  138. int dataRowsPerPage = int.Parse(RowCount.Value.ToString());
  139. int contentMaxRow = she.Cells.MaxDataRow;
  140. for (int p = 0; p < she.Pictures.Count; p++)
  141. {
  142. if (she.Pictures[p].LowerRightRow > contentMaxRow)
  143. contentMaxRow = she.Pictures[p].LowerRightRow;
  144. }
  145. for (int s = 0; s < she.Shapes.Count; s++)
  146. {
  147. if (she.Shapes[s].LowerRightRow > contentMaxRow)
  148. contentMaxRow = she.Shapes[s].LowerRightRow;
  149. }
  150. int actualDataRows = Math.Max(contentMaxRow + 1 - headerRows, 0);
  151. int totalPages = (int)Math.Ceiling(actualDataRows / (double)dataRowsPerPage);
  152. if (totalPages == 0) totalPages = 1;
  153. int totalRows = headerRows + totalPages * dataRowsPerPage;
  154. int totalDataRows = Math.Max(totalRows - headerRows, 0);
  155. int wmRowGlobal = int.Parse(Y.Value.ToString());
  156. int wmCol = int.Parse(X.Value.ToString());
  157. int imageIndex = 1;
  158. for (int page = 0; page < totalPages; page++)
  159. {
  160. // ---------- 1. 复制原表到临时工作表 ----------
  161. int newSheetIndex = workbook.Worksheets.Add();
  162. Worksheet newshe = workbook.Worksheets[newSheetIndex];
  163. newshe.Copy(she);
  164. newshe.Name = $"Temp_{page}";
  165. int dataStartRow = headerRows + page * dataRowsPerPage;
  166. int dataEndRow = Math.Min(headerRows + (page + 1) * dataRowsPerPage - 1, totalRows - 1);
  167. // ---------- 2. 按页过滤原表图片(Pictures) ----------
  168. for (int p = newshe.Pictures.Count - 1; p >= 0; p--)
  169. {
  170. Aspose.Cells.Drawing.Picture pic = newshe.Pictures[p];
  171. int topRow = pic.UpperLeftRow;
  172. bool isHeaderPic = topRow < headerRows;
  173. bool belongsToPage = topRow >= dataStartRow && topRow <= dataEndRow;
  174. if (!isHeaderPic && !belongsToPage)
  175. {
  176. newshe.Pictures.RemoveAt(p);
  177. }
  178. }
  179. // ---------- 3. 按页过滤原表形状(Shapes) ----------
  180. for (int s = newshe.Shapes.Count - 1; s >= 0; s--)
  181. {
  182. Aspose.Cells.Drawing.Shape shape;
  183. try {
  184. shape = newshe.Shapes[s];
  185. }
  186. catch { continue; }
  187. int topRow = shape.UpperLeftRow;
  188. bool isHeaderShape = topRow < headerRows;
  189. bool belongsToPage = topRow >= dataStartRow && topRow <= dataEndRow;
  190. if (!isHeaderShape && !belongsToPage)
  191. {
  192. try { newshe.Shapes.RemoveAt(s); }
  193. catch { shape.IsHidden = true; }
  194. }
  195. else {
  196. try
  197. {
  198. // 1. 启用文本自动换行
  199. shape.IsTextWrapped = true;
  200. Console.WriteLine(shape.Text);
  201. // 2. 获取文本对齐对象并设置内边距
  202. if (shape.TextBody != null && shape.TextBody.TextAlignment != null)
  203. {
  204. var textAlign = shape.TextBody.TextAlignment;
  205. textAlign.LeftMarginPt = 1;
  206. textAlign.RightMarginPt = 1;
  207. textAlign.TopMarginPt = 1;
  208. textAlign.BottomMarginPt = 1;
  209. }
  210. // 3. 设置文本对齐方式
  211. shape.TextVerticalAlignment = TextAlignmentType.Left;
  212. shape.TextHorizontalAlignment = TextAlignmentType.Left;
  213. // 4. 自动调整形状大小以适应文本(如果形状允许)
  214. if (shape.TextBody != null && shape.TextBody.TextAlignment != null)
  215. {
  216. shape.TextBody.TextAlignment.TextHorizontalOverflow = TextOverflowType.Ellipsis;
  217. }
  218. }
  219. catch (Exception ex)
  220. {
  221. // 某些形状可能不支持所有属性,忽略异常
  222. Console.WriteLine($"Shape优化失败: {ex.Message}");
  223. }
  224. }
  225. }
  226. // ---------- 4. 清空非本页单元格内容 ----------
  227. for (int r = 0; r < totalRows; r++)
  228. {
  229. if (r < headerRows) continue;
  230. if (r >= dataStartRow && r <= dataEndRow) continue;
  231. newshe.Cells.ClearRange(r, 0, r, lastColIndex);
  232. }
  233. // ---------- 5. 删除非本页整行 ----------
  234. for (int r = totalRows - 1; r >= 0; r--)
  235. {
  236. if (r < headerRows) continue;
  237. if (r >= dataStartRow && r <= dataEndRow) continue;
  238. newshe.Cells.DeleteRow(r);
  239. }
  240. // ---------- 6. 页面设置 ----------
  241. int printMaxRow = newshe.Cells.MaxDataRow;
  242. for (int p = 0; p < newshe.Pictures.Count; p++)
  243. {
  244. if (newshe.Pictures[p].LowerRightRow > printMaxRow)
  245. {
  246. printMaxRow = newshe.Pictures[p].LowerRightRow;
  247. }
  248. }
  249. for (int s = 0; s < newshe.Shapes.Count; s++)
  250. {
  251. if (newshe.Shapes[s].LowerRightRow > printMaxRow)
  252. {
  253. printMaxRow = newshe.Shapes[s].LowerRightRow;
  254. }
  255. }
  256. int newTotalRows = printMaxRow + 1;
  257. int pageHeight = headerRows + dataRowsPerPage;
  258. int printEndRow = Math.Max(newTotalRows, pageHeight);
  259. if (i == 0)
  260. newshe.PageSetup.PrintArea = $"A1:{lastColLetter}{25}";
  261. else
  262. newshe.PageSetup.PrintArea = $"A1:{lastColLetter}{printEndRow}";
  263. newshe.PageSetup.CenterHorizontally = true;
  264. newshe.PageSetup.CenterVertically = true;
  265. newshe.PageSetup.LeftMargin = 2;
  266. newshe.PageSetup.RightMargin = 2;
  267. newshe.PageSetup.TopMargin = 2;
  268. newshe.PageSetup.BottomMargin = 2;
  269. newshe.PageSetup.SetFooter(0, "");
  270. newshe.PageSetup.SetFooter(1, "");
  271. newshe.PageSetup.SetFooter(2, "");
  272. // ---------- 7. 插入水印 ----------
  273. if (File.Exists(PrintPath.Text))
  274. {
  275. int rowOffset = headerRows + int.Parse(Y.Value.ToString());
  276. newshe.Pictures.Add(rowOffset, int.Parse(X.Value.ToString()), PrintPath.Text);
  277. }
  278. // ---------- 8. 页脚 ----------
  279. string pageFooter = $"第 {imageIndex} 页 / 共 {totalPages} 页";
  280. newshe.PageSetup.SetFooter(1, pageFooter);
  281. // ==================★ 优化点:提高渲染分辨率(核心改动) ==================
  282. ImageOrPrintOptions options = new ImageOrPrintOptions();
  283. options.ImageFormat = ImageFormat.Png;
  284. options.OnePagePerSheet = true; // 保留:整页一张图
  285. options.PrintingPage = PrintingPageType.Default;
  286. // ★ 把默认 96 DPI 提高到 300 DPI,文字/表格瞬间变清晰(约放大3倍像素)
  287. options.HorizontalResolution = 300;
  288. options.VerticalResolution = 300;
  289. // ★ 开启抗锯齿,边缘更平滑(18.x 支持,可选)
  290. options.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  291. // ★ 文本渲染更清晰(可选)
  292. options.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
  293. // ==================★ 优化点结束 ==================
  294. SheetRender sr = new SheetRender(newshe, options);
  295. if (sr.PageCount > 0)
  296. {
  297. using (Bitmap bitmap = sr.ToImage(0))
  298. {
  299. string imagename = $"{she.Name}_{imageIndex}.png";
  300. string imagePath = Path.Combine(path, imagename);
  301. bitmap.Save(imagePath, ImageFormat.Png);
  302. OperatResult.AppendText("解析图片【" + imagePath + "】\n");
  303. // ---------- 10. 上传 ----------
  304. Dictionary<string, object> dic = new Dictionary<string, object>();
  305. dic.Add("em_name", "管理员");
  306. dic.Add("em_code", "ADMIN");
  307. dic.Add("caller", "ProductSOP");
  308. OperatResult.AppendText("上传文件【" + imagePath + "】\n");
  309. string fp_id = UploadFilesToRemoteUrl(
  310. "https://mes.lihantech.cn/mes/MEScommon/uploadFiles.action?_noc=1",
  311. imagePath, dic);
  312. // ---------- 11. 入库 ----------
  313. string ps_id = dh.getFieldDataByCondition(
  314. "ProductSOP", "ps_id", "ps_prodcode='" + ps_prodcode.Text + "'").ToString();
  315. dh.ExecuteSql(
  316. "insert into ProductSOPdetail(psd_id,psd_psid,psd_attach) " +
  317. "select ProductSOPdetail_seq.nextval,ps_id,'" + imagename + ";" + fp_id +
  318. "' from ProductSOP where ps_prodcode='" + ps_prodcode.Text + "'", "insert");
  319. }
  320. }
  321. // ---------- 12. 删除临时工作表 ----------
  322. workbook.Worksheets.RemoveAt(newSheetIndex);
  323. imageIndex++;
  324. }
  325. //}
  326. //catch (Exception ex)
  327. //{
  328. // OperatResult.AppendText(ex.Message + ex.StackTrace);
  329. //}
  330. }
  331. }
  332. }
  333. else if (PDF.Checked)
  334. {
  335. ps_prodcode.Text = FilePath.Text.Substring(FilePath.Text.LastIndexOf(@"\") + 1).Replace(".pdf", "");
  336. pr_code_Leave(new object(), new EventArgs());
  337. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "' ", "select");
  338. if (dt.Rows.Count == 0)
  339. {
  340. string code = LogicHandler.GetPiInoutCode("ProductSOP", "1");
  341. ps_code.Text = code;
  342. if (VaildDate.Checked)
  343. {
  344. 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");
  345. }
  346. else
  347. {
  348. 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");
  349. }
  350. }
  351. else
  352. {
  353. string psid = dt.Rows[0]["ps_id"].ToString();
  354. dh.ExecuteSql("delete from ProductSOPdetail where psd_psid='" + psid + "'", "delete");
  355. ps_prodcode.Text = dt.Rows[0]["ps_prodcode"].ToString();
  356. }
  357. if (VaildDate.Checked)
  358. {
  359. 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");
  360. }
  361. else
  362. {
  363. dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "' where ps_prodcode='" + ps_prodcode.Text + "'", "update");
  364. }
  365. Dictionary<string, object> dic = new Dictionary<string, object>();
  366. dic.Add("em_name", "管理员");
  367. dic.Add("em_code", "ADMIN");
  368. dic.Add("caller", "ProductSOP");
  369. OperatResult.AppendText("上传文件【" + ps_prodcode.Text + "" + "】\n");
  370. string fp_id = UploadFilesToRemoteUrl("https://mes.lihantech.cn/mes/MEScommon/uploadFiles.action?_noc=1", FilePath.Text, dic);
  371. string ps_id = dh.getFieldDataByCondition("ProductSOP", "ps_id", "ps_prodcode='" + ps_prodcode.Text + "'").ToString();
  372. 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");
  373. }
  374. }
  375. /// <summary>
  376. /// 请求上传图片到阿里云
  377. /// </summary>
  378. /// <param name="url">上传地址</param>
  379. /// <param name="filepath">本地文件路径</param>
  380. /// <param name="dic">上传的数据信息</param>
  381. /// <returns></returns>
  382. public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic)
  383. {
  384. try
  385. {
  386. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
  387. ServicePointManager.DefaultConnectionLimit = 50;
  388. string boundary = DateTime.Now.Ticks.ToString("x");
  389. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  390. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  391. request.Method = "POST";
  392. request.Timeout = 10 * 10000;
  393. request.ContentType = "multipart/form-data; boundary=" + boundary;
  394. Stream rs = request.GetRequestStream();
  395. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  396. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  397. if (dic != null)
  398. {
  399. foreach (string key in dic.Keys)
  400. {
  401. rs.Write(boundarybytes, 0, boundarybytes.Length);
  402. string formitem = string.Format(formdataTemplate, key, dic[key]);
  403. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  404. rs.Write(formitembytes, 0, formitembytes.Length);
  405. }
  406. }
  407. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  408. {
  409. rs.Write(boundarybytes, 0, boundarybytes.Length);
  410. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  411. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  412. rs.Write(headerbytes, 0, headerbytes.Length);
  413. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  414. {
  415. var buffer = new byte[1024];
  416. var bytesRead = 0;
  417. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  418. {
  419. rs.Write(buffer, 0, bytesRead);
  420. }
  421. }
  422. var cr = Encoding.UTF8.GetBytes("\r\n");
  423. rs.Write(cr, 0, cr.Length);
  424. }
  425. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  426. var response = request.GetResponse() as HttpWebResponse;
  427. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  428. string Content = newReader.ReadToEnd();
  429. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  430. List<Dictionary<string, object>> dic2 = null;
  431. dic1 = BaseUtil.ToDictionary(Content);
  432. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  433. string fp_id = "";
  434. if (dic2[0]["filepath"] != null)
  435. {
  436. fp_id = dic2[0]["filepath"].ToString();
  437. }
  438. if (response.StatusCode == HttpStatusCode.OK)
  439. {
  440. return fp_id;
  441. }
  442. }
  443. catch (Exception e)
  444. {
  445. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP", "上传失败", ps_prodcode.Text, "");
  446. Console.WriteLine(e.Message + e.StackTrace);
  447. }
  448. return "";
  449. }
  450. private void ChooseFile_Click(object sender, EventArgs e)
  451. {
  452. ChoosePath.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls|(*.pdf)|*.pdf";
  453. DialogResult result = ChoosePath.ShowDialog();
  454. if (result == DialogResult.OK)
  455. {
  456. FilePath.Text = ChoosePath.FileName;
  457. }
  458. }
  459. private void UploadSOP_Click(object sender, EventArgs e)
  460. {
  461. Thread thread = new Thread(uploadfile);
  462. SetLoadingWindow stw = new SetLoadingWindow(thread, "上传文件");
  463. stw.StartPosition = FormStartPosition.CenterScreen;
  464. stw.ShowDialog();
  465. if (JPG.Checked)
  466. {
  467. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【图片格式】", "上传成功", ps_prodcode.Text, "");
  468. }
  469. else
  470. {
  471. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【PDF格式】", "上传成功", ps_prodcode.Text, "");
  472. }
  473. }
  474. private void OperatResult_TextChanged(object sender, EventArgs e)
  475. {
  476. //OperatResult.SelectionStart = Text.Length;
  477. OperatResult.ScrollToCaret();
  478. }
  479. private void SendSop_Click(object sender, EventArgs e)
  480. {
  481. try
  482. {
  483. if (ps_prodcode.Text == "")
  484. {
  485. MessageBox.Show("线别和SOP文档不能为空");
  486. return;
  487. }
  488. if (SendDGV.Rows.Count > 0)
  489. {
  490. List<Dictionary<string, string>> listr = new List<Dictionary<string, string>>();
  491. JavaScriptSerializer jss = new JavaScriptSerializer();
  492. Dictionary<string, object> map1 = new Dictionary<string, object>();
  493. Dictionary<string, object> map = new Dictionary<string, object>();
  494. string path;
  495. string pathroot = dh.GetConfig("filePathUrl", "sys").ToString();
  496. dh.ExecuteSql("insert into soprelease(SR_ID, sr_pscode, SR_STATUS, SR_MACHINETYPE,sr_releaseman,sr_readman)" +
  497. "select soprelease_seq.nextval,'" + ps_code.Text + "',0,'" + ps_prodcode.Text + "','" + User.UserName + "',em_code from employee ", "insert");
  498. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播成功", ps_prodcode.Text, "");
  499. MessageBox.Show("文档[" + ps_prodcode.Text + "]下放成功");
  500. }
  501. else
  502. {
  503. MessageBox.Show("产品编号" + ps_prodcode.Text + "未维护SOP文档");
  504. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败,未维护SOP文档", ps_prodcode.Text, "");
  505. }
  506. }
  507. catch (Exception ex)
  508. {
  509. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败", ps_prodcode.Text, "");
  510. Console.WriteLine(ex.Message + ex.StackTrace);
  511. }
  512. }
  513. public string encryptBASE64(string key)
  514. {
  515. Console.WriteLine(key);
  516. byte[] bytes = Encoding.Default.GetBytes(key);
  517. return Convert.ToBase64String(bytes);
  518. }
  519. public static string EncodeBase64(string code_type, string code)
  520. {
  521. string encode = "";
  522. byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
  523. try
  524. {
  525. encode = Convert.ToBase64String(bytes);
  526. }
  527. catch
  528. {
  529. encode = code;
  530. }
  531. return encode;
  532. }
  533. private void pr_code_KeyDown(object sender, KeyEventArgs e)
  534. {
  535. if (e.KeyCode == Keys.Enter)
  536. {
  537. LoadPrCode();
  538. }
  539. }
  540. private BindingSource bs = new BindingSource(); // 类成员变量
  541. private void LoadPrCode()
  542. {
  543. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "'", "select");
  544. if (dt.Rows.Count > 0)
  545. {
  546. string ps_id = dt.Rows[0]["ps_id"].ToString();
  547. dt = (DataTable)dh.ExecuteSql(@"select fp_name,fp_path,'' issend,psd_iskey
  548. from ProductSOPdetail
  549. left join filepath on FP_ID=substr(PSD_ATTACH,instr(PSD_ATTACH,';')+1)
  550. where psd_psid=" + ps_id, "select");
  551. if (dt.Rows.Count > 0)
  552. {
  553. // 在 UI 线程安全执行(如果已经在 UI 线程则直接调用)
  554. if (SendDGV.InvokeRequired)
  555. SendDGV.Invoke(new Action(() => BindData(dt)));
  556. else
  557. BindData(dt);
  558. }
  559. }
  560. }
  561. private void BindData(DataTable dt)
  562. {
  563. // 使用 BindingSource 避免直接置 null
  564. if (SendDGV.DataSource == null)
  565. {
  566. bs.DataSource = dt;
  567. SendDGV.DataSource = bs;
  568. }
  569. else
  570. {
  571. bs.DataSource = dt; // 直接替换内部数据,控件不会经历“无数据”状态
  572. }
  573. // 可选:刷新显示
  574. SendDGV.Refresh();
  575. }
  576. private void pr_code_Leave(object sender, EventArgs e)
  577. {
  578. //LoadPrCode();
  579. }
  580. bool AllChecked = false;
  581. private void ChooseALL_Click(object sender, EventArgs e)
  582. {
  583. if (AllChecked)
  584. {
  585. foreach (DataGridViewRow dr in SendDGV.Rows)
  586. dr.Cells[0].Value = false;
  587. AllChecked = false;
  588. }
  589. else
  590. {
  591. foreach (DataGridViewRow dr in SendDGV.Rows)
  592. dr.Cells[0].Value = true;
  593. AllChecked = true;
  594. }
  595. }
  596. private void ps_prodcode_UserControlTextChanged(object sender, EventArgs e)
  597. {
  598. LoadPrCode();
  599. }
  600. private void GetSOP_Click(object sender, EventArgs e)
  601. {
  602. LoadPrCode();
  603. }
  604. private void ChoosePrint_Click(object sender, EventArgs e)
  605. {
  606. ChoosePath.Filter = "(*.png)|*.png";
  607. DialogResult result = ChoosePath.ShowDialog();
  608. if (result == DialogResult.OK)
  609. {
  610. PrintPath.Text = ChoosePath.FileName;
  611. }
  612. }
  613. private void SendDGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
  614. {
  615. if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
  616. }
  617. }
  618. }