Query_SOP.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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.Net.Sockets;
  9. using System.Data;
  10. using UAS_MES_NEW.DataOperate;
  11. using UAS_MES_NEW.PublicMethod;
  12. using Spire.Xls;
  13. using UAS_MES_NEW.PublicForm;
  14. using System.Web.Script.Serialization;
  15. namespace UAS_MES_NEW.Query
  16. {
  17. public partial class Query_SOP : Form
  18. {
  19. DataHelper dh = new DataHelper();
  20. string usercode;
  21. string sourcecode;
  22. public Query_SOP()
  23. {
  24. InitializeComponent();
  25. }
  26. public Query_SOP(string iUserCode, string iSource)
  27. {
  28. usercode = iUserCode;
  29. sourcecode = iSource;
  30. InitializeComponent();
  31. }
  32. private void Form3_Load(object sender, EventArgs e)
  33. {
  34. CheckForIllegalCrossThreadCalls = false;
  35. }
  36. void uploadfile()
  37. {
  38. pr_code.Text = FilePath.Text.Substring(FilePath.Text.LastIndexOf(@"\") + 1).Replace(".xls", "").Replace(".xlsx", "");
  39. pr_code_Leave(new object(), new EventArgs());
  40. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where instr('" + pr_code.Text + "',ps_prodcode)>0 ", "select");
  41. if (dt.Rows.Count == 0)
  42. {
  43. DataTable dt1 = (DataTable)dh.ExecuteSql("select pr_code from product where instr('" + pr_code.Text + "',pr_code)>0", "select");
  44. if (dt1.Rows.Count > 0)
  45. {
  46. string code = LogicHandler.GetPiInoutCode("ProductSOP", "1");
  47. pr_code.Text = dt1.Rows[0]["pr_code"].ToString();
  48. dh.ExecuteSql("insert into productsop(ps_id,ps_code,ps_prodcode,ps_indate,ps_inman)values(productsop_seq.nextval,'" + code + "','" + pr_code.Text + "',sysdate,'" + usercode + "')", "insert");
  49. }
  50. else
  51. {
  52. MessageBox.Show("产品编号" + pr_code.Text + "不存在");
  53. return;
  54. }
  55. }
  56. else
  57. {
  58. pr_code.Text = dt.Rows[0]["ps_prodcode"].ToString();
  59. }
  60. Workbook workbook = new Workbook();
  61. workbook.LoadFromFile(FilePath.Text);
  62. workbook.ConverterSetting.JPEGQuality = 100;
  63. workbook.ConverterSetting.XDpi = 600;
  64. workbook.ConverterSetting.YDpi = 600;
  65. //先清空旧的 ps_attachsop,避免残留旧数据
  66. dh.ExecuteSql("update ProductSOP set ps_attachsop='' where ps_prodcode='" + pr_code.Text + "'", "update");
  67. OperatResult.AppendText("一共Sheet: " + workbook.Worksheets.Count + "\n");
  68. //串行处理每个Sheet,避免并发导致缺页
  69. //根因:DataHelper.connection是static全局唯一,多线程并发ExecuteSql会互相覆盖command字段
  70. // 且ps_attachsop=ps_attachsop||fp_id并发拼接非原子,后提交覆盖先提交
  71. // Spire.Xls的SaveToPdf/SaveToImage也不是线程安全的
  72. //方案:串行转换+上传,内存收集fp_id,最后一次性UPDATE
  73. List<string> successIds = new List<string>();
  74. List<string> failedSheets = new List<string>();
  75. int total = workbook.Worksheets.Count;
  76. for (int i = 0; i < total; i++)
  77. {
  78. string sheetName = workbook.Worksheets[i].Name;
  79. OperatResult.AppendText("[" + (i + 1) + "/" + total + "] 处理Sheet: " + sheetName + "\n");
  80. try
  81. {
  82. //处理TextBox(放大文字,保持原有逻辑)
  83. for (int k = 0; k < workbook.Worksheets[i].TextBoxes.Count; k++)
  84. {
  85. if (workbook.Worksheets[i].TextBoxes[k].RichText.Text.Length > 1)
  86. {
  87. workbook.Worksheets[i].TextBoxes[k].RichText.Text = workbook.Worksheets[i].TextBoxes[k].RichText.Text;
  88. workbook.Worksheets[i].TextBoxes[k].Width = workbook.Worksheets[i].TextBoxes[k].Width * 2;
  89. workbook.Worksheets[i].TextBoxes[k].Height = workbook.Worksheets[i].TextBoxes[k].Height * 2;
  90. workbook.Worksheets[i].TextBoxes[k].HAlignment = CommentHAlignType.Center;
  91. }
  92. }
  93. //复制到独立Workbook再转换,避免污染原workbook
  94. Workbook bw = new Workbook();
  95. Worksheet she = bw.CreateEmptySheet();
  96. she.Name = sheetName;
  97. she.CopyFrom(workbook.Worksheets[i]);
  98. string fp_id = "";
  99. if (JPG.Checked)
  100. {
  101. fp_id = SaveFileToJPG(she);
  102. }
  103. else
  104. {
  105. fp_id = SaveFileToPDF(she);
  106. }
  107. if (fp_id != "")
  108. {
  109. successIds.Add(fp_id);
  110. OperatResult.AppendText(" -> 成功, fp_id=" + fp_id + "\n");
  111. }
  112. else
  113. {
  114. failedSheets.Add(sheetName);
  115. OperatResult.AppendText(" -> 失败\n");
  116. }
  117. }
  118. catch (Exception ex)
  119. {
  120. failedSheets.Add(sheetName);
  121. OperatResult.AppendText(" -> 异常: " + ex.Message + "\n");
  122. }
  123. }
  124. //所有Sheet处理完成后,一次性拼接fp_id写入数据库
  125. if (successIds.Count > 0)
  126. {
  127. string idList = "";
  128. foreach (string id in successIds)
  129. {
  130. idList += id + ";";
  131. }
  132. dh.ExecuteSql("update ProductSOP set ps_attachsop='" + idList + "' where ps_prodcode='" + pr_code.Text + "'", "update");
  133. OperatResult.AppendText("已写入" + successIds.Count + "个文件到ProductSOP\n");
  134. }
  135. if (failedSheets.Count > 0)
  136. {
  137. string msg = "以下Sheet上传失败,可能缺页:\n" + string.Join(", ", failedSheets.ToArray());
  138. OperatResult.AppendText(msg + "\n");
  139. MessageBox.Show(msg, "上传部分失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  140. }
  141. else
  142. {
  143. OperatResult.AppendText("全部" + total + "个Sheet上传成功\n");
  144. }
  145. }
  146. private string SaveFileToPDF(Worksheet sheet)
  147. {
  148. string fp_id = "";
  149. //失败重试2次
  150. for (int retry = 0; retry < 2; retry++)
  151. {
  152. try
  153. {
  154. if (!Directory.Exists(Application.StartupPath + @"\" + pr_code.Text))
  155. {
  156. Directory.CreateDirectory(Application.StartupPath + @"\" + pr_code.Text);
  157. }
  158. string filePath = Application.StartupPath + @"\" + pr_code.Text + @"\" + sheet.Name + ".pdf";
  159. sheet.SaveToPdf(filePath);
  160. OperatResult.AppendText("解析PDF【" + sheet.Name + ".pdf】" + "\n");
  161. Dictionary<string, object> dic = new Dictionary<string, object>();
  162. dic.Add("em_name", "管理员");
  163. dic.Add("em_code", "ADMIN");
  164. dic.Add("caller", "ProductSOP");
  165. OperatResult.AppendText("上传文件【" + sheet.Name + ".pdf" + "】\n");
  166. fp_id = UploadFilesToRemoteUrl("http://192.168.101.253:8099/mes/MEScommon/uploadFiles.action?_noc=1", filePath, dic);
  167. if (fp_id != "")
  168. {
  169. break;
  170. }
  171. if (retry == 0)
  172. {
  173. OperatResult.AppendText("首次上传失败,重试中...\n");
  174. }
  175. }
  176. catch (Exception ex)
  177. {
  178. OperatResult.AppendText("SaveFileToPDF异常: " + ex.Message + (retry == 0 ? " 重试中..." : "") + "\n");
  179. }
  180. }
  181. return fp_id;
  182. }
  183. private string SaveFileToJPG(Worksheet sheet)
  184. {
  185. string fp_id = "";
  186. //失败重试2次
  187. for (int retry = 0; retry < 2; retry++)
  188. {
  189. try
  190. {
  191. if (!Directory.Exists(Application.StartupPath + @"\" + pr_code.Text))
  192. {
  193. Directory.CreateDirectory(Application.StartupPath + @"\" + pr_code.Text);
  194. }
  195. ExcelPicture picture = sheet.Pictures.Add(@"图片\电子受控章.png");
  196. picture.Width = 113;
  197. picture.Height = 38;
  198. picture.LeftColumn = 20;
  199. picture.TopRowOffset = 20;
  200. ExcelPicture picture1 = sheet.Pictures.Add(@"图片\签名.png");
  201. picture1.Width = 100;
  202. picture1.Height = 38;
  203. picture1.LeftColumn = 15;
  204. picture1.TopRowOffset = 600;
  205. string filePath = Application.StartupPath + @"\" + pr_code.Text + @"\" + sheet.Name + ".jpg";
  206. sheet.SaveToImage(filePath);
  207. OperatResult.AppendText("解析图片【" + sheet.Name + ".jpg】" + "\n");
  208. Dictionary<string, object> dic = new Dictionary<string, object>();
  209. dic.Add("em_name", "管理员");
  210. dic.Add("em_code", "ADMIN");
  211. dic.Add("caller", "ProductSOP");
  212. OperatResult.AppendText("上传文件【" + sheet.Name + ".jpg" + "】\n");
  213. fp_id = UploadFilesToRemoteUrl("http://192.168.101.253:8099/mes/MEScommon/uploadFiles.action?_noc=1", filePath, dic);
  214. if (fp_id != "")
  215. {
  216. break;
  217. }
  218. if (retry == 0)
  219. {
  220. OperatResult.AppendText("首次上传失败,重试中...\n");
  221. }
  222. }
  223. catch (Exception ex)
  224. {
  225. OperatResult.AppendText("SaveFileToJPG异常: " + ex.Message + (retry == 0 ? " 重试中..." : "") + "\n");
  226. }
  227. }
  228. return fp_id;
  229. }
  230. /// <summary>
  231. /// 请求上传图片到阿里云
  232. /// </summary>
  233. /// <param name="url">上传地址</param>
  234. /// <param name="filepath">本地文件路径</param>
  235. /// <param name="dic">上传的数据信息</param>
  236. /// <returns></returns>
  237. public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic)
  238. {
  239. try
  240. {
  241. ServicePointManager.DefaultConnectionLimit = 50;
  242. string boundary = DateTime.Now.Ticks.ToString("x");
  243. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  244. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  245. request.Method = "POST";
  246. request.Timeout = 10 * 10000;
  247. request.ContentType = "multipart/form-data; boundary=" + boundary;
  248. Stream rs = request.GetRequestStream();
  249. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  250. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  251. if (dic != null)
  252. {
  253. foreach (string key in dic.Keys)
  254. {
  255. rs.Write(boundarybytes, 0, boundarybytes.Length);
  256. string formitem = string.Format(formdataTemplate, key, dic[key]);
  257. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  258. rs.Write(formitembytes, 0, formitembytes.Length);
  259. }
  260. }
  261. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  262. {
  263. rs.Write(boundarybytes, 0, boundarybytes.Length);
  264. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  265. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  266. rs.Write(headerbytes, 0, headerbytes.Length);
  267. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  268. {
  269. var buffer = new byte[1024];
  270. var bytesRead = 0;
  271. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  272. {
  273. rs.Write(buffer, 0, bytesRead);
  274. }
  275. }
  276. var cr = Encoding.UTF8.GetBytes("\r\n");
  277. rs.Write(cr, 0, cr.Length);
  278. }
  279. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  280. var response = request.GetResponse() as HttpWebResponse;
  281. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  282. string Content = newReader.ReadToEnd();
  283. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  284. List<Dictionary<string, object>> dic2 = null;
  285. dic1 = BaseUtil.ToDictionary(Content);
  286. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  287. string fp_id = "";
  288. if (dic2[0]["filepath"] != null)
  289. {
  290. fp_id = dic2[0]["filepath"].ToString();
  291. }
  292. if (response.StatusCode == HttpStatusCode.OK)
  293. {
  294. return fp_id;
  295. }
  296. }
  297. catch (Exception e)
  298. {
  299. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP", "上传失败", pr_code.Text, "");
  300. Console.WriteLine(e.Message + e.StackTrace);
  301. }
  302. return "";
  303. }
  304. private void ChooseFile_Click(object sender, EventArgs e)
  305. {
  306. ChoosePath.Filter = "(*.xls)|*.xls|(*.xlsx)|*.xlsx";
  307. DialogResult result = ChoosePath.ShowDialog();
  308. if (result == DialogResult.OK)
  309. {
  310. FilePath.Text = ChoosePath.FileName;
  311. }
  312. }
  313. private void UploadSOP_Click(object sender, EventArgs e)
  314. {
  315. Thread thread = new Thread(uploadfile);
  316. SetLoadingWindow stw = new SetLoadingWindow(thread, "上传文件");
  317. stw.StartPosition = FormStartPosition.CenterScreen;
  318. stw.ShowDialog();
  319. if (JPG.Checked)
  320. {
  321. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【图片格式】", "上传成功", pr_code.Text, "");
  322. }
  323. else
  324. {
  325. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【PDF格式】", "上传成功", pr_code.Text, "");
  326. }
  327. }
  328. private void OperatResult_TextChanged(object sender, EventArgs e)
  329. {
  330. //OperatResult.SelectionStart = Text.Length;
  331. OperatResult.ScrollToCaret();
  332. }
  333. TcpServer tcpserver = new TcpServer();
  334. private void SendSop_Click(object sender, EventArgs e)
  335. {
  336. try
  337. {
  338. IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
  339. string IPAddress = "";
  340. for (int i = 0; i < IpEntry.AddressList.Length; i++)
  341. {
  342. if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
  343. {
  344. IPAddress = IpEntry.AddressList[i].ToString();
  345. }
  346. }
  347. dh.ExecuteSql("update SOPSOURCE set SS_BRDIP='" + IPAddress + "'", "update");
  348. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + pr_code.Text + "'", "select");
  349. if (dt.Rows.Count > 0)
  350. {
  351. tcpserver.Start();
  352. Thread.Sleep(5000);
  353. List<Dictionary<string, string>> listr = new List<Dictionary<string, string>>();
  354. string PS_ATTACHSOP = dt.Rows[0]["PS_ATTACHSOP"].ToString();
  355. PS_ATTACHSOP = PS_ATTACHSOP.Substring(0, PS_ATTACHSOP.Length - 1).Replace(";", ",");
  356. dt = (DataTable)dh.ExecuteSql("select fp_path, fp_name from filepath where fp_id in (" + PS_ATTACHSOP + ") and nvl(fp_path, ' ') <> ' '", "select");
  357. JavaScriptSerializer jss = new JavaScriptSerializer();
  358. Dictionary<string, object> map1 = new Dictionary<string, object>();
  359. Dictionary<string, object> map = new Dictionary<string, object>();
  360. string path;
  361. string pathroot = dh.GetConfig("filePathUrl", "sys").ToString();
  362. for (int i = 0; i < dt.Rows.Count; i++)
  363. {
  364. Dictionary<string, string> dic1 = new Dictionary<string, string>();
  365. path = dt.Rows[i]["fp_path"].ToString();
  366. path = encryptBASE64(path.Replace("/app/uas/webapps/postattach", pathroot)).Replace("\\s*|\r|\n|\t", "");
  367. dic1.Add("path", path);
  368. dic1.Add("filename", dt.Rows[i]["fp_name"].ToString().Replace(" ", "").Replace("(", "").Replace(")", ""));
  369. dic1.Add("ps_prodcode", pr_code.Text);
  370. listr.Add(dic1);
  371. }
  372. map1.Add("ps_code", "");
  373. map1.Add("url", listr);
  374. map.Add("success", true);
  375. map.Add("data", map1);
  376. tcpserver.Send(jss.Serialize(map));
  377. tcpserver.Stop();
  378. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播成功", pr_code.Text, "");
  379. MessageBox.Show("产品编号" + pr_code.Text + "广播成功");
  380. }
  381. else
  382. {
  383. MessageBox.Show("产品编号" + pr_code.Text + "未维护SOP文档");
  384. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败,未维护SOP文档", pr_code.Text, "");
  385. }
  386. }
  387. catch (Exception ex)
  388. {
  389. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败", pr_code.Text, "");
  390. Console.WriteLine(ex.Message + ex.StackTrace);
  391. }
  392. }
  393. public string encryptBASE64(string key)
  394. {
  395. byte[] bytes = Encoding.Default.GetBytes(key);
  396. return Convert.ToBase64String(bytes);
  397. }
  398. public static string EncodeBase64(string code_type, string code)
  399. {
  400. string encode = "";
  401. byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
  402. try
  403. {
  404. encode = Convert.ToBase64String(bytes);
  405. }
  406. catch
  407. {
  408. encode = code;
  409. }
  410. return encode;
  411. }
  412. private void pr_code_KeyDown(object sender, KeyEventArgs e)
  413. {
  414. if (e.KeyCode == Keys.Enter)
  415. {
  416. LoadPrCode();
  417. }
  418. }
  419. private void LoadPrCode()
  420. {
  421. DataTable dt = (DataTable)dh.ExecuteSql("select pr_code,pr_spec,pr_detail from product where instr('" + pr_code.Text + "',pr_code)>0", "select");
  422. if (dt.Rows.Count > 0)
  423. {
  424. pr_spec.Clear();
  425. pr_spec.AppendText(dt.Rows[0]["pr_spec"].ToString());
  426. pr_detail.Text = dt.Rows[0]["pr_detail"].ToString();
  427. pr_code.Text = dt.Rows[0]["pr_code"].ToString();
  428. }
  429. else
  430. {
  431. MessageBox.Show("产品编号" + pr_code.Text + "不存在");
  432. }
  433. }
  434. private void pr_code_Leave(object sender, EventArgs e)
  435. {
  436. LoadPrCode();
  437. }
  438. private void pr_spec_Click(object sender, EventArgs e)
  439. {
  440. }
  441. }
  442. }