Query_SOP.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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. dh = SystemInf.dh;
  45. }
  46. private void nr_rule_DBChange(object sender, EventArgs e)
  47. {
  48. Dbfind = ps_prodcode.ReturnData;
  49. BaseUtil.SetFormValue(this.Controls, Dbfind);
  50. }
  51. void uploadfile()
  52. {
  53. if (FilePath.Text == "")
  54. {
  55. MessageBox.Show("文件不能为空!");
  56. return;
  57. }
  58. ps_prodcode.Text = FilePath.Text.Substring(FilePath.Text.LastIndexOf(@"\") + 1).Replace(".xls", "").Replace(".xlsx", "");
  59. pr_code_Leave(new object(), new EventArgs());
  60. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "' ", "select");
  61. if (dt.Rows.Count == 0)
  62. {
  63. string code = LogicHandler.GetPiInoutCode("ProductSOP", "1");
  64. ps_code.Text = code;
  65. if (VaildDate.Checked)
  66. {
  67. 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");
  68. }
  69. else
  70. {
  71. 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");
  72. }
  73. }
  74. else
  75. {
  76. string ps_id = dt.Rows[0]["ps_id"].ToString();
  77. dh.ExecuteSql("delete from ProductSOPdetail where psd_psid='" + ps_id + "'", "delete");
  78. ps_prodcode.Text = dt.Rows[0]["ps_prodcode"].ToString();
  79. }
  80. Workbook workbook = new Workbook(FilePath.Text);
  81. List<Worksheet> list = new List<Worksheet>();
  82. List<string> filename = new List<string>();
  83. if (VaildDate.Checked)
  84. {
  85. 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");
  86. }
  87. else
  88. {
  89. dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "' where ps_prodcode='" + ps_prodcode.Text + "'", "update");
  90. }
  91. OperatResult.AppendText("一共Sheet: " + workbook.Worksheets.Count + "\n");
  92. for (int i = 0; i < workbook.Worksheets.Count; i++)
  93. {
  94. OperatResult.AppendText("正在解析Sheet" + workbook.Worksheets[i].Name + "\n");
  95. string path = Application.StartupPath + @"\" + ps_prodcode.Text + @"\";
  96. Worksheet she = workbook.Worksheets[i];
  97. int lastColIndex = she.Cells.MaxDataColumn;
  98. string lastColLetter = CellsHelper.ColumnIndexToName(lastColIndex);
  99. she.PageSetup.LeftMargin = 0;
  100. she.PageSetup.RightMargin = 0;
  101. she.PageSetup.TopMargin = 0;
  102. she.PageSetup.BottomMargin = 0;
  103. if (JPG.Checked)
  104. {
  105. try
  106. {
  107. if (!Directory.Exists(Application.StartupPath + @"\" + ps_prodcode.Text))
  108. {
  109. Directory.CreateDirectory(Application.StartupPath + @"\" + ps_prodcode.Text);
  110. }
  111. string sheetname = she.Name;
  112. // 获取工作表中的所有图片
  113. List<Picture> pictures = new List<Picture>();
  114. foreach (Aspose.Cells.Drawing.Picture picture in she.Pictures)
  115. {
  116. pictures.Add(picture);
  117. }
  118. // 获取使用的行数
  119. int totalRows = she.Cells.MaxDataRow + 1;
  120. int imageIndex = 1;
  121. // 每40行生成一张图片
  122. for (int startRow = 0; startRow < totalRows; startRow += int.Parse(RowCount.Value.ToString()))
  123. {
  124. int endRow = Math.Min(startRow + int.Parse(RowCount.Value.ToString()) - 1, totalRows - 1);
  125. // 创建图片选项
  126. ImageOrPrintOptions options = new ImageOrPrintOptions();
  127. options.ImageFormat = ImageFormat.Png;
  128. options.OnePagePerSheet = false;
  129. options.PrintingPage = PrintingPageType.IgnoreBlank;
  130. she.PageSetup.PrintArea = $"A{startRow + 1}:{lastColLetter}{endRow + 1}";
  131. if (File.Exists(PrintPath.Text))
  132. {
  133. if (startRow == 0)
  134. {
  135. she.Pictures.Add(startRow + int.Parse(Y.Value.ToString()), int.Parse(X.Value.ToString()), PrintPath.Text);
  136. }
  137. else
  138. {
  139. she.Pictures.Add(startRow - 4 + int.Parse(Y.Value.ToString()), int.Parse(X.Value.ToString()), PrintPath.Text);
  140. }
  141. }
  142. // 创建SheetRender对象
  143. SheetRender sr = new SheetRender(she, options);
  144. string imagename = $"{she.Name}_{imageIndex}.png";
  145. // 获取渲染后的图像
  146. Bitmap bitmap = sr.ToImage(0);
  147. string imagePath = "";
  148. // 如果有图片在当前行范围内,将它们添加到最终图像中
  149. if (pictures.Count > 0)
  150. {
  151. using (Bitmap finalImage = new Bitmap(bitmap.Width, bitmap.Height))
  152. using (Graphics g = Graphics.FromImage(finalImage))
  153. {
  154. // 绘制Excel内容
  155. g.DrawImage(bitmap, 0, 0);
  156. // 绘制原始Excel中的图片
  157. int yOffset = bitmap.Height;
  158. // 保存图像
  159. imagePath = Path.Combine(path, $"{she.Name}_{imageIndex}.png");
  160. finalImage.Save(imagePath, ImageFormat.Png);
  161. Console.WriteLine($"Saved: {imagePath}");
  162. }
  163. }
  164. else
  165. {
  166. // 如果没有图片,直接保存渲染的图像
  167. imagePath = Path.Combine(path, $"{she.Name}_{imageIndex}.png");
  168. bitmap.Save(imagePath, ImageFormat.Png);
  169. Console.WriteLine($"Saved: {imagePath}");
  170. }
  171. imageIndex++;
  172. OperatResult.AppendText("解析图片【" + imagePath + ".jpg】" + "\n");
  173. Dictionary<string, object> dic = new Dictionary<string, object>();
  174. dic.Add("em_name", "管理员");
  175. dic.Add("em_code", "ADMIN");
  176. dic.Add("caller", "ProductSOP");
  177. OperatResult.AppendText("上传文件【" + imagePath + ".jpg" + "】\n");
  178. string fp_id = UploadFilesToRemoteUrl("https://mes.lihantech.cn/mes/MEScommon/uploadFiles.action?_noc=1", Application.StartupPath + @"\" + ps_prodcode.Text + @"\" + imagename, dic);
  179. string ps_id = dh.getFieldDataByCondition("ProductSOP", "ps_id", "ps_prodcode='" + ps_prodcode.Text + "'").ToString();
  180. dh.ExecuteSql("insert into ProductSOPdetail(psd_id,psd_psid,psd_attach) select ProductSOPdetail_seq.nextval,ps_id,'" + imagename + ";" + fp_id + "' from ProductSOP where ps_prodcode='" + ps_prodcode.Text + "'", "insert");
  181. }
  182. }
  183. catch (Exception ex)
  184. {
  185. OperatResult.AppendText(ex.Message + ex.StackTrace);
  186. }
  187. filename.Add(she.Name + ".jpg");
  188. }
  189. }
  190. }
  191. /// <summary>
  192. /// 请求上传图片到阿里云
  193. /// </summary>
  194. /// <param name="url">上传地址</param>
  195. /// <param name="filepath">本地文件路径</param>
  196. /// <param name="dic">上传的数据信息</param>
  197. /// <returns></returns>
  198. public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic)
  199. {
  200. try
  201. {
  202. ServicePointManager.DefaultConnectionLimit = 50;
  203. string boundary = DateTime.Now.Ticks.ToString("x");
  204. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  205. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  206. request.Method = "POST";
  207. request.Timeout = 10 * 10000;
  208. request.ContentType = "multipart/form-data; boundary=" + boundary;
  209. Stream rs = request.GetRequestStream();
  210. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  211. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  212. if (dic != null)
  213. {
  214. foreach (string key in dic.Keys)
  215. {
  216. rs.Write(boundarybytes, 0, boundarybytes.Length);
  217. string formitem = string.Format(formdataTemplate, key, dic[key]);
  218. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  219. rs.Write(formitembytes, 0, formitembytes.Length);
  220. }
  221. }
  222. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  223. {
  224. rs.Write(boundarybytes, 0, boundarybytes.Length);
  225. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  226. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  227. rs.Write(headerbytes, 0, headerbytes.Length);
  228. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  229. {
  230. var buffer = new byte[1024];
  231. var bytesRead = 0;
  232. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  233. {
  234. rs.Write(buffer, 0, bytesRead);
  235. }
  236. }
  237. var cr = Encoding.UTF8.GetBytes("\r\n");
  238. rs.Write(cr, 0, cr.Length);
  239. }
  240. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  241. var response = request.GetResponse() as HttpWebResponse;
  242. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  243. string Content = newReader.ReadToEnd();
  244. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  245. List<Dictionary<string, object>> dic2 = null;
  246. dic1 = BaseUtil.ToDictionary(Content);
  247. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  248. string fp_id = "";
  249. if (dic2[0]["filepath"] != null)
  250. {
  251. fp_id = dic2[0]["filepath"].ToString();
  252. }
  253. if (response.StatusCode == HttpStatusCode.OK)
  254. {
  255. return fp_id;
  256. }
  257. }
  258. catch (Exception e)
  259. {
  260. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP", "上传失败", ps_prodcode.Text, "");
  261. Console.WriteLine(e.Message + e.StackTrace);
  262. }
  263. return "";
  264. }
  265. private void ChooseFile_Click(object sender, EventArgs e)
  266. {
  267. ChoosePath.Filter = "(*.xls)|*.xls|(*.xlsx)|*.xlsx";
  268. DialogResult result = ChoosePath.ShowDialog();
  269. if (result == DialogResult.OK)
  270. {
  271. FilePath.Text = ChoosePath.FileName;
  272. }
  273. }
  274. private void UploadSOP_Click(object sender, EventArgs e)
  275. {
  276. Thread thread = new Thread(uploadfile);
  277. SetLoadingWindow stw = new SetLoadingWindow(thread, "上传文件");
  278. stw.StartPosition = FormStartPosition.CenterScreen;
  279. stw.ShowDialog();
  280. if (JPG.Checked)
  281. {
  282. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【图片格式】", "上传成功", ps_prodcode.Text, "");
  283. }
  284. else
  285. {
  286. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【PDF格式】", "上传成功", ps_prodcode.Text, "");
  287. }
  288. }
  289. private void OperatResult_TextChanged(object sender, EventArgs e)
  290. {
  291. //OperatResult.SelectionStart = Text.Length;
  292. OperatResult.ScrollToCaret();
  293. }
  294. private void SendSop_Click(object sender, EventArgs e)
  295. {
  296. try
  297. {
  298. if (ps_prodcode.Text == "")
  299. {
  300. MessageBox.Show("线别和SOP文档不能为空");
  301. return;
  302. }
  303. if (SendDGV.Rows.Count > 0)
  304. {
  305. List<Dictionary<string, string>> listr = new List<Dictionary<string, string>>();
  306. JavaScriptSerializer jss = new JavaScriptSerializer();
  307. Dictionary<string, object> map1 = new Dictionary<string, object>();
  308. Dictionary<string, object> map = new Dictionary<string, object>();
  309. string path;
  310. string pathroot = dh.GetConfig("filePathUrl", "sys").ToString();
  311. dh.ExecuteSql("insert into soprelease(SR_ID, sr_pscode, SR_STATUS, SR_MACHINETYPE,sr_releaseman,sr_readman)" +
  312. "select soprelease_seq.nextval,'" + ps_code.Text + "',0,'" + ps_prodcode.Text + "','" + User.UserName + "',em_code from employee ", "insert");
  313. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播成功", ps_prodcode.Text, "");
  314. MessageBox.Show("文档[" + ps_prodcode.Text + "]下放成功");
  315. }
  316. else
  317. {
  318. MessageBox.Show("产品编号" + ps_prodcode.Text + "未维护SOP文档");
  319. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败,未维护SOP文档", ps_prodcode.Text, "");
  320. }
  321. }
  322. catch (Exception ex)
  323. {
  324. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败", ps_prodcode.Text, "");
  325. Console.WriteLine(ex.Message + ex.StackTrace);
  326. }
  327. }
  328. public string encryptBASE64(string key)
  329. {
  330. Console.WriteLine(key);
  331. byte[] bytes = Encoding.Default.GetBytes(key);
  332. return Convert.ToBase64String(bytes);
  333. }
  334. public static string EncodeBase64(string code_type, string code)
  335. {
  336. string encode = "";
  337. byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
  338. try
  339. {
  340. encode = Convert.ToBase64String(bytes);
  341. }
  342. catch
  343. {
  344. encode = code;
  345. }
  346. return encode;
  347. }
  348. private void pr_code_KeyDown(object sender, KeyEventArgs e)
  349. {
  350. if (e.KeyCode == Keys.Enter)
  351. {
  352. LoadPrCode();
  353. }
  354. }
  355. private BindingSource bs = new BindingSource(); // 类成员变量
  356. private void LoadPrCode()
  357. {
  358. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "'", "select");
  359. if (dt.Rows.Count > 0)
  360. {
  361. string ps_id = dt.Rows[0]["ps_id"].ToString();
  362. dt = (DataTable)dh.ExecuteSql(@"select fp_name,fp_path,'' issend,psd_iskey
  363. from ProductSOPdetail
  364. left join filepath on FP_ID=substr(PSD_ATTACH,instr(PSD_ATTACH,';')+1)
  365. where psd_psid=" + ps_id, "select");
  366. if (dt.Rows.Count > 0)
  367. {
  368. // 在 UI 线程安全执行(如果已经在 UI 线程则直接调用)
  369. if (SendDGV.InvokeRequired)
  370. SendDGV.Invoke(new Action(() => BindData(dt)));
  371. else
  372. BindData(dt);
  373. }
  374. }
  375. }
  376. private void BindData(DataTable dt)
  377. {
  378. // 使用 BindingSource 避免直接置 null
  379. if (SendDGV.DataSource == null)
  380. {
  381. bs.DataSource = dt;
  382. SendDGV.DataSource = bs;
  383. }
  384. else
  385. {
  386. bs.DataSource = dt; // 直接替换内部数据,控件不会经历“无数据”状态
  387. }
  388. // 可选:刷新显示
  389. SendDGV.Refresh();
  390. }
  391. private void pr_code_Leave(object sender, EventArgs e)
  392. {
  393. //LoadPrCode();
  394. }
  395. bool AllChecked = false;
  396. private void ChooseALL_Click(object sender, EventArgs e)
  397. {
  398. if (AllChecked)
  399. {
  400. foreach (DataGridViewRow dr in SendDGV.Rows)
  401. dr.Cells[0].Value = false;
  402. AllChecked = false;
  403. }
  404. else
  405. {
  406. foreach (DataGridViewRow dr in SendDGV.Rows)
  407. dr.Cells[0].Value = true;
  408. AllChecked = true;
  409. }
  410. }
  411. private void ps_prodcode_UserControlTextChanged(object sender, EventArgs e)
  412. {
  413. LoadPrCode();
  414. }
  415. private void GetSOP_Click(object sender, EventArgs e)
  416. {
  417. LoadPrCode();
  418. }
  419. private void ChoosePrint_Click(object sender, EventArgs e)
  420. {
  421. ChoosePath.Filter = "(*.png)|*.png";
  422. DialogResult result = ChoosePath.ShowDialog();
  423. if (result == DialogResult.OK)
  424. {
  425. PrintPath.Text = ChoosePath.FileName;
  426. }
  427. }
  428. private void SendDGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
  429. {
  430. if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
  431. }
  432. }
  433. }