using Kingdee.BOS.Core.DynamicForm.PlugIn; using Kingdee.BOS.Core.DynamicForm.PlugIn.Args; using Kingdee.BOS.JSON; using Kingdee.BOS.Util; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Kingdee.BOS.WebApi.FormService; using System.Web; using Kingdee.BOS.Core; using Kingdee.BOS.Orm.DataEntity; using System.IO; using OpenCvSharp.Extensions; using OpenCvSharp; using Spire.Pdf.Fields; using Spire.Pdf; using System.Drawing.Imaging; using System.Drawing; using Kingdee.BOS; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Kingdee.BOS.ServiceHelper; using OpenCvSharp.Aruco; namespace GZ.LJY000.PiLot.SAL_OUTSTOCK.UploadExtension { [HotUpdate, Description("上传附件界面")] public class BillEventPlugInEx : AbstractDynamicFormPlugIn { private string FormId = ""; private bool IsDoUploaded = false; public override void OnInitialize(InitializeEventArgs e) { base.OnInitialize(e); //FormId = e.Paramter.FormId; } public override void ButtonClick(ButtonClickEventArgs e) { base.ButtonClick(e); if (!fileUploaded) { this.View.ShowErrMessage("文件未加载完毕!"); return; } if (e.Key.EndsWith("FDoUpLoad", StringComparison.OrdinalIgnoreCase)) { var entity = this.View.Model.BillBusinessInfo.GetEntryEntity("FEntity"); var rows = this.View.Model.GetEntityDataObject(entity); if (rows != null && rows.Any()) { var path = HttpContext.Current.Request.PhysicalApplicationPath + @"\FileUpLoadServices\UploadFiles\"; if (!this.Context.DBId.Equals("6735f10547df64")) path = "D:/Program Files (x86)/Kingdee/K3Cloud/WebSite/FileUpLoadServices/UploadFiles/"; foreach (var row in rows) { var isSucceed = row["FisSucceed"].ToString() == "1"; if (isSucceed) continue; var fileName = row["FFileName"].ToString(); var serverFileName = row["FServerFileName"].ToString(); var fileSuffix = row["FFileSuffix"].ToString(); var fileBytesLength = row["FFileBytesLength"].Long2Int(); AnalyzeResult resData = null; //文件地址 var fullName = path + serverFileName; if (fileSuffix.ToUpper().Equals(".PDF")) { // 创建 PdfDocument 类的实例 using (PdfDocument document = new PdfDocument()) { // 加载 PDF 文档 document.LoadFromFile(fullName); // 将页面转换为图片 using (Image image = document.SaveAsImage(0, 200, 200)) { // 创建流来保存图片数据 using (MemoryStream stream = new MemoryStream()) { // 将图片以 PNG 格式保存到流中 image.Save(stream, ImageFormat.Png); stream.Position = 0; using (Mat src = BitmapConverter.ToMat(new Bitmap(image))) { var srcWidth = src.Width; var srcHeight = src.Height; int x = srcWidth / 2; int y = 0; int width = srcWidth / 2; int height = srcHeight / 2; Rect region = new Rect(x, y, width, height); resData = DecodeQRCodes(src, region, false); } } } } } else if (fileSuffix.ToUpper().Equals(".JPG")) { Mat src = new Mat(fullName); var srcWidth = src.Width; var srcHeight = src.Height; int x = srcWidth / 2; int y = 0; int width = srcWidth / 2; int height = srcHeight / 2; Rect region = new Rect(x, y, width, height); resData = DecodeQRCodes(src, region, false); } if (resData != null) { var isSuccess = false; var resMsg = string.Empty; row["FBillNo"] = resData.name; if (!resData.name.IsNullOrEmptyOrWhiteSpace()) { var base64 = FileToBase64String(fullName); var resultJson = DoAttachmentUpload("SAL_OUTSTOCK", fileName, resData.name, fileBytesLength, fileSuffix, base64); var result = JsonConvert.DeserializeObject(resultJson); //var result = resultJson as JObject; var responseData = result["Result"]["ResponseStatus"]; isSuccess = responseData["IsSuccess"].Value(); resMsg = JsonConvert.SerializeObject(responseData); } if (isSuccess) { row["FisSucceed"] = true; row["FResultMsg"] = "上传完毕"; this.View.GetControl("FFileName").SetCustomPropertyValue("ForeColor", "#00994C"); } else { if (resMsg.IsNullOrEmpty()) resMsg = "识别失败!"; row["FisSucceed"] = false; row["FResultMsg"] = resMsg; this.View.GetControl("FFileName").SetCustomPropertyValue("ForeColor", "#FF3300"); } } } //fileUploaded = false; this.View.UpdateView("FEntity"); } } } /// /// 文件转base64 /// /// base64字符串 public string FileToBase64String(string fullName) { //FileStream fsForRead = new FileStream(fullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//文件路径 string base64Str = ""; try { ////读写指针移到距开头10个字节处 //fsForRead.Seek(0, SeekOrigin.Begin); //byte[] bs = new byte[fsForRead.Length]; //int log = Convert.ToInt32(fsForRead.Length); ////从文件中读取10个字节放到数组bs中 //fsForRead.Read(bs, 0, log); //base64Str = Convert.ToBase64String(bs); //return base64Str; var fileBytes = File.ReadAllBytes(fullName); return Convert.ToBase64String(fileBytes); } catch (Exception ex) { Console.Write(ex.Message); Console.ReadLine(); return base64Str; } finally { //fsForRead.Close(); } } /// /// 识别二维码 /// /// /// /// /// private static AnalyzeResult DecodeQRCodes(Mat src, Rect region, bool isReturn) { AnalyzeResult analyzeResult = null; // 裁剪指定区域 using (Mat roi = new Mat(src, region)) { // 转为灰度图像 using (Mat gray = new Mat()) { Cv2.CvtColor(roi, gray, ColorConversionCodes.BGR2GRAY); // 二值化处理 using (Mat binary = new Mat()) { Cv2.Threshold(gray, binary, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu); //二维码识别 using (QRCodeDetector qRCodeDetector = new QRCodeDetector()) { Point2f[] points; var hasQRCode = qRCodeDetector.DetectMulti(binary, out points); if (hasQRCode) { qRCodeDetector.DecodeMulti(binary, points, out string[] qrCodeTexts); analyzeResult = new AnalyzeResult(); analyzeResult.name = qrCodeTexts[0]; analyzeResult.points = points; } else { if (isReturn) return null; var srcWidth = roi.Width; var srcHeight = roi.Height; int x = srcWidth / 2; int y = 0; int width = srcWidth / 2; int height = srcHeight / 2; var newRegion = new Rect(x, y, width, height); analyzeResult = DecodeQRCodes(roi, newRegion, true); } } } } } return analyzeResult; } public class AnalyzeResult { public string fileName { get; set; } public string name { get; set; } public Point2f[] points { get; set; } } /// /// /// /// /// /// /// /// /// /// private string DoAttachmentUpload(string formId, string fileName, string billNo, int fileBytesLength, string fileSuffix, string base64) { if (this.Context.DBId.Equals("6735f10547df64")) billNo = "ZHBR-XSCKD240911002"; var InterId = 0L; var sqlL = $@"/*dialect*/ SELECT t0.FBILLNO,t0.FID FROM T_SAL_OUTSTOCK t0 WHERE t0.FBILLNO = '{billNo}' "; var data = DBServiceHelper.ExecuteDynamicObject(this.Context, sqlL); if (data != null && data.Any()) InterId = data[0]["FID"].Long2Int(); var fileSql = @"/*dialect*/ SELECT * FROM T_BAS_FILESERVERINFO WHERE FUSED = 1 ORDER BY FENABLE DESC"; var fileServerInfo = DBServiceHelper.ExecuteDynamicObject(this.Context, fileSql); if (fileServerInfo != null && fileServerInfo.Count > 0) { string jsonData = $@" {{ ""FileName"": ""{fileName}"", ""FEntryKey"": "" "", ""FormId"": ""{formId}"", ""IsLast"": true, ""InterId"": {InterId}, ""BillNO"": ""{billNo}"", ""AliasFileName"": """", ""SendByte"": ""{base64}"" }} "; var resultJson = WebApiServiceCall.AttachmentUpload(this.Context, jsonData); return JsonConvert.SerializeObject(resultJson); } else { var jsonData = $@" {{ ""Model"": {{ ""FAttachmentName"": ""{fileName}"", ""FBillType"": ""{formId}"", ""FInterID"": ""{InterId}"", ""FBillNo"": ""{billNo}"", ""FAttachmentSize"": {fileBytesLength}, ""FAttachment"":""{base64}"", ""FFILESTORAGE"":0, ""FExtName"": ""{fileSuffix}"", ""FEntryinterId"": ""-1"", ""FEntrykey"": "" "", ""FaliasFileName"": ""{fileName}"", ""FCreateMen"": {{ ""FUserID"": ""{this.Context.UserId}"" }}, ""FCreateTime"":""{DateTime.Now:F}"" }} }} "; var resultJson = WebApiServiceCall.Save(this.Context, "BOS_Attachment", jsonData); return JsonConvert.SerializeObject(resultJson); } } //K3CloudApi clienter = null; bool fileUploaded = false; public override void CustomEvents(CustomEventsArgs e) { base.CustomEvents(e); if (e.EventName.ToUpper().Equals("FILECHANGED") && e.Key.ToUpper().Equals("FFILEUPDATECLIENT")) { fileUploaded = false; var postData = KDObjectConverter.DeserializeObject(e.EventArgs); if (postData != null) { var uploadInfo = new JSONArray(postData["NewValue"].ToString()); var entity = this.View.Model.BillBusinessInfo.GetEntryEntity("FEntity"); var rows = this.View.Model.GetEntityDataObject(entity); rows.Clear(); if (uploadInfo.Count > 0) { foreach (Dictionary fileInfo in uploadInfo) { var row = new DynamicObject(entity.DynamicObjectType); var fileName = fileInfo["FileName"].ToString(); var suffix = Path.GetExtension(fileName); if (suffix.ToUpper().Equals(".PDF")|| suffix.ToUpper().Equals(".JPG")) { row["FFileName"] = fileName; row["FServerFileName"] = fileInfo["ServerFileName"]; row["FFileSuffix"] = suffix; row["FFileBytesLength"] = fileInfo["FileBytesLength"]; rows.Add(row); } } this.View.UpdateView("FEntity"); fileUploaded = true; } } //if (e.Key.ToUpper() == "FFileUpdate".ToUpper()) //{ //触发事件是上传文件有变化 // if (e.EventName.ToUpper() == "FILECHANGED") // { // JSONObject jSONObject = KDObjectConverter.DeserializeObject(e.EventArgs); // if (jSONObject != null) // { // JSONArray jSONArray = new JSONArray(jSONObject["NewValue"].ToString()); if (jSONArray.Count > 0) // { // //获取上传的文件名 // string text = (jSONArray[0] as Dictionary)["ServerFileName"].ToString(); // //文件上传到服务端的临时目录 // string directory = "FileUpLoadServices\\UploadFiles"; // //文件的完整路径 // string fileFullPath = PathUtils.GetPhysicalPath(directory, text); // } // } // } //} base.CustomEvents(e); return; } } } }