From 567aa4ee65af4c2d2c97f7c14aa9181e5eabd852 Mon Sep 17 00:00:00 2001
From: xwt <2740516069@qq.com>
Date: 星期三, 03 九月 2025 14:58:42 +0800
Subject: [PATCH] 来料检排序,巡检FTP附件

---
 StandardInterface/MES.Service/service/QC/LljService.cs          |    4 
 StandardInterface/MES.Service/service/QC/XJService.cs           |  266 +++++++++++++++++++++++++++++++++++--
 StandardInterface/MESApplication/Controllers/QC/XJController.cs |  134 +++++++++++++++++++
 3 files changed, 384 insertions(+), 20 deletions(-)

diff --git a/StandardInterface/MES.Service/service/QC/LljService.cs b/StandardInterface/MES.Service/service/QC/LljService.cs
index 78dc03b..37567ba 100644
--- a/StandardInterface/MES.Service/service/QC/LljService.cs
+++ b/StandardInterface/MES.Service/service/QC/LljService.cs
@@ -88,7 +88,7 @@
                 // 娣诲姞璇勫鐘舵��
                 PSZT = a.PSZT
             })
-            .OrderBy("CASE WHEN EMERGENCY = 1 THEN 0 ELSE 1 END, CASE WHEN STATUS = '宸叉彁浜�' THEN 0 ELSE 1 END, IQC_DATE desc, ID asc")
+            .OrderBy("CASE WHEN EMERGENCY = 1 AND STATUS = '鏈彁浜�' THEN 0 ELSE 1 END, CASE WHEN STATUS = '鏈彁浜�' AND (SELECT COUNT(*) FROM MES_QA_ITEMS_DETECT_DETAIL5 WHERE RELEASE_NO = A.RELEASE_NO) = 0 THEN 0 ELSE 1 END, CASE WHEN STATUS = '鏈彁浜�' THEN A.CREATE_DATE ASC ELSE NULL END, CASE WHEN STATUS = '宸叉彁浜�' THEN A.IQC_DATE DESC ELSE NULL END")
             .ToPageList(queryObj.PageIndex, queryObj.Limit, ref totalCount);
 
         // 鎵归噺鑾峰彇妫�楠岄」鐩暟閲忥紝閬垮厤N+1鏌ヨ闂
@@ -682,7 +682,7 @@
                 FcheckItemDesc = a.FspecRequ,
                 Funit = a.Funit,
                 Meom = a.Meom,
-            }).ToList();
+            }).OrderBy(a => SqlFunc.IIF(a.Fstand != null, 0, 1)).OrderBy(a => a.FcheckItem, OrderByType.Desc).ToList();
     }
 
     public int SetQSItemDetail(MesQaItemsDetectDetail12 detail)
diff --git a/StandardInterface/MES.Service/service/QC/XJService.cs b/StandardInterface/MES.Service/service/QC/XJService.cs
index af5750a..0d1564e 100644
--- a/StandardInterface/MES.Service/service/QC/XJService.cs
+++ b/StandardInterface/MES.Service/service/QC/XJService.cs
@@ -141,38 +141,56 @@
             lineNo = _baseService.getUserLineNo(queryObj.createUser);
 
         var totalCount = 0;
-        var data = db
+        
+        // 鏋勫缓鍩虹鏌ヨ - 浣跨敤LEFT JOIN閬垮厤鍥犲叧鑱旀暟鎹己澶卞鑷存煡璇笉鍒�
+        var query = db
             .Queryable<QsQaItemXj, Womdaa, MesLine,
                 MesItems>((s, a, c, b) =>
                 new JoinQueryInfos(
-                    JoinType.Inner, s.BillNo == a.Daa001,
+                    JoinType.Left, s.BillNo == a.Daa001,
                     JoinType.Left, a.Daa015 == c.LineNo,
                     JoinType.Left, s.ItemId == b.Id
                 )
-            )
-            .WhereIF(lineNo != null && lineNo.Length > 0,
-                (s, a, c, b) => lineNo.Contains(c.LineNo))
-            .WhereIF(
-                StringUtil.IsNotNullOrEmpty(queryObj.result) &&
-                "鏈畬鎴�".Equals(queryObj.result),
-                (s, a, c, b) => s.Fsubmit == 0)
-            .WhereIF(
-                StringUtil.IsNotNullOrEmpty(queryObj.result) &&
-                !"鏈畬鎴�".Equals(queryObj.result),
-                (s, a, c, b) => s.Fsubmit == 1)
-            .WhereIF(id > 0, (s, a, c, b) => s.Id == id)
+            );
+            
+        // 娣诲姞绾夸綋绛涢�夋潯浠�
+        if (lineNo != null && lineNo.Length > 0)
+        {
+            query = query.Where((s, a, c, b) => lineNo.Contains(c.LineNo));
+        }
+        
+        // 娣诲姞鐘舵�佺瓫閫夋潯浠� - 鏄庣‘鍖归厤鍓嶇浼犻�掔殑鍊�
+        if (StringUtil.IsNotNullOrEmpty(queryObj.result))
+        {
+            if ("鏈畬鎴�".Equals(queryObj.result))
+            {
+                query = query.Where((s, a, c, b) => s.Fsubmit == 0);
+            }
+            else if ("宸插畬鎴�".Equals(queryObj.result))
+            {
+                query = query.Where((s, a, c, b) => s.Fsubmit == 1);
+            }
+        }
+        
+        // 娣诲姞ID绛涢�夋潯浠�
+        if (id > 0)
+        {
+            query = query.Where((s, a, c, b) => s.Id == id);
+        }
+        
+        var data = query
             .Select((s, a, c, b) => new QsQaItemXj
             {
-                Daa020 = c.LineNo,
+                Daa020 = SqlFunc.IsNull(c.LineNo, ""),
                 Id = s.Id,
-                PlanQty = a.Daa008,
+                PlanQty = SqlFunc.IsNull(a.Daa008, 0),
                 CreateBy = s.CreateBy,
                 CreateDate = s.CreateDate,
                 ReleaseNo = s.ReleaseNo,
                 ItemNo = s.ItemNo,
                 BillNo = s.BillNo,
-                ItemName = b.ItemName,
-                ItemModel = b.ItemModel,
+                ItemName = SqlFunc.IsNull(b.ItemName, ""),
+                ItemModel = SqlFunc.IsNull(b.ItemModel, ""),
                 FcheckBy = s.FcheckBy,
                 FcheckResu = s.FcheckResu,
                 Remarks = s.Remarks
@@ -685,4 +703,216 @@
             .OrderBy(line => line.LineNo)
             .ToList();
     }
+
+    /// <summary>
+    /// 鑾峰彇闄勪欢淇℃伅
+    /// </summary>
+    /// <param name="itemNo">鐗╂枡缂栫爜</param>
+    /// <returns>闄勪欢鍒楄〃</returns>
+    public List<QamftpDto> GetAttachments(string itemNo)
+    {
+        var db = SqlSugarHelper.GetInstance();
+        try
+        {
+            return db.Queryable<MesQamftp>()
+                .Where(x => x.ItemNo == itemNo)
+                .OrderBy(x => x.Fdate, OrderByType.Desc)
+                .Select(x => new QamftpDto
+                {
+                    Id = x.Id,
+                    itemNo = x.ItemNo,
+                    Ftype = x.Ftype,
+                    Fattach = x.Fattach,
+                    Fversion = x.Fversion,
+                    Fdate = x.Fdate,
+                    CreateBy = x.CreateBy,
+                    CreateDate = x.CreateDate,
+                    Company = x.Company,
+                    Factory = x.Factory,
+                    F_type = x.F_type,
+                    LastupdateBy = x.LastupdateBy,
+                    LastupdateDate = x.LastupdateDate,
+                    ItemId = x.ItemId
+                }).ToList();
+        }
+        catch (Exception ex)
+        {
+            throw new Exception($"鏌ヨ闄勪欢淇℃伅澶辫触: {ex.Message}");
+        }
+    }
+
+    /// <summary>
+    /// 浠嶧TP鏈嶅姟鍣ㄨ幏鍙栨枃浠讹紙宸℃浣跨敤OPC鐩綍锛�
+    /// </summary>
+    /// <param name="itemNo">鐗╂枡缂栫爜</param>
+    /// <param name="fileName">鏂囦欢鍚�</param>
+    /// <param name="ftpServer">FTP鏈嶅姟鍣ㄥ湴鍧�</param>
+    /// <returns>鏂囦欢瀛楄妭鏁扮粍</returns>
+    public byte[] GetFtpFile(string itemNo, string fileName, string ftpServer)
+    {
+        // 鍙傛暟楠岃瘉
+        if (string.IsNullOrEmpty(itemNo) || string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(ftpServer))
+        {
+            throw new ArgumentException("鍙傛暟涓嶈兘涓虹┖: itemNo, fileName, ftpServer");
+        }
+        
+        string ftpUser = "hm_ftp";
+        string ftpPwd = "dell_123";
+        
+        // 鏍囧噯鍖朏TP鏈嶅姟鍣ㄥ湴鍧�
+        string normalizedServer = NormalizeFtpServer(ftpServer);
+        
+        // 鏋勫缓FTP鏂囦欢璺緞 - 宸℃浣跨敤OPC鐩綍
+        string ftpPath = $"{normalizedServer}/OPC/{itemNo}/{fileName}";
+        
+        try
+        {
+            var request = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(ftpPath);
+            request.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
+            request.Credentials = new System.Net.NetworkCredential(ftpUser, ftpPwd);
+            request.UseBinary = true;
+            request.UsePassive = false;
+            request.Timeout = 30000; // 30绉掕秴鏃�
+            request.ReadWriteTimeout = 30000;
+            
+            using (var response = (System.Net.FtpWebResponse)request.GetResponse())
+            using (var ftpStream = response.GetResponseStream())
+            using (var ms = new System.IO.MemoryStream())
+            {
+                if (ftpStream == null)
+                {
+                    throw new Exception("FTP鍝嶅簲娴佷负绌�");
+                }
+                
+                ftpStream.CopyTo(ms);
+                var fileBytes = ms.ToArray();
+                
+                if (fileBytes.Length == 0)
+                {
+                    return null; // 鏂囦欢涓虹┖鎴栦笉瀛樺湪
+                }
+                
+                return fileBytes;
+            }
+        }
+        catch (System.Net.WebException ex)
+        {
+            if (ex.Response is System.Net.FtpWebResponse ftpResponse)
+            {
+                switch (ftpResponse.StatusCode)
+                {
+                    case System.Net.FtpStatusCode.ActionNotTakenFileUnavailable:
+                        return null; // 鏂囦欢涓嶅瓨鍦�
+                    case System.Net.FtpStatusCode.NotLoggedIn:
+                        throw new Exception("FTP璁よ瘉澶辫触锛岃妫�鏌ョ敤鎴峰悕鍜屽瘑鐮�");
+                    case System.Net.FtpStatusCode.ActionNotTakenFilenameNotAllowed:
+                        throw new Exception("鏂囦欢鍚嶄笉琚厑璁告垨璺緞鏃犳晥");
+                    default:
+                        throw new Exception($"FTP閿欒 ({ftpResponse.StatusCode}): {ftpResponse.StatusDescription}");
+                }
+            }
+            
+            // 澶勭悊瓒呮椂鍜岀綉缁滈敊璇�
+            if (ex.Status == System.Net.WebExceptionStatus.Timeout)
+            {
+                throw new Exception("FTP杩炴帴瓒呮椂锛岃绋嶅悗閲嶈瘯");
+            }
+            
+            throw new Exception($"FTP杩炴帴澶辫触: {ex.Message}");
+        }
+        catch (Exception ex)
+        {
+            throw new Exception($"鑾峰彇鏂囦欢澶辫触: {ex.Message}");
+        }
+    }
+    
+    /// <summary>
+    /// 鏍囧噯鍖朏TP鏈嶅姟鍣ㄥ湴鍧�
+    /// </summary>
+    /// <param name="ftpServer">FTP鏈嶅姟鍣ㄥ湴鍧�</param>
+    /// <returns>鏍囧噯鍖栧悗鐨凢TP鏈嶅姟鍣ㄥ湴鍧�</returns>
+    private string NormalizeFtpServer(string ftpServer)
+    {
+        if (string.IsNullOrEmpty(ftpServer))
+        {
+            throw new ArgumentException("FTP鏈嶅姟鍣ㄥ湴鍧�涓嶈兘涓虹┖");
+        }
+        
+        // 纭繚浠tp://寮�澶�
+        string normalizedServer = ftpServer.StartsWith("ftp://") ? ftpServer : $"ftp://{ftpServer}";
+        
+        // 鐗规畩澶勭悊宸茬煡鏈嶅姟鍣ㄥ湴鍧�
+        if (normalizedServer == "ftp://36.26.21.214")
+        {
+            normalizedServer = "ftp://36.26.21.214:21";
+        }
+        else if (!normalizedServer.Contains(":") && normalizedServer.StartsWith("ftp://"))
+        {
+            normalizedServer += ":21"; // 榛樿FTP绔彛
+        }
+        
+        // 寮�鍙戠幆澧冧娇鐢ㄦ湰鍦版湇鍔″櫒
+        normalizedServer = "ftp://192.168.1.22:21";
+        
+        return normalizedServer;
+    }
+
+    /// <summary>
+    /// 鑾峰彇鏂囦欢鐨勫唴瀹圭被鍨�
+    /// </summary>
+    /// <param name="fileName">鏂囦欢鍚�</param>
+    /// <returns>MIME绫诲瀷</returns>
+    public string GetContentType(string fileName)
+    {
+        if (string.IsNullOrEmpty(fileName))
+            return "application/octet-stream";
+            
+        var extension = System.IO.Path.GetExtension(fileName).ToLower();
+        
+        return extension switch
+        {
+            // PDF鏂囦欢
+            ".pdf" => "application/pdf",
+            
+            // 鍥剧墖鏂囦欢
+            ".jpg" or ".jpeg" => "image/jpeg",
+            ".png" => "image/png",
+            ".gif" => "image/gif",
+            ".bmp" => "image/bmp",
+            ".webp" => "image/webp",
+            ".svg" => "image/svg+xml",
+            ".ico" => "image/x-icon",
+            
+            // 鏂囨湰鏂囦欢
+            ".txt" => "text/plain",
+            ".log" => "text/plain",
+            ".md" => "text/markdown",
+            ".html" or ".htm" => "text/html",
+            ".css" => "text/css",
+            ".js" => "application/javascript",
+            ".json" => "application/json",
+            ".xml" => "application/xml",
+            
+            // Office鏂囨。
+            ".doc" => "application/msword",
+            ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+            ".xls" => "application/vnd.ms-excel",
+            ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+            ".ppt" => "application/vnd.ms-powerpoint",
+            ".pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+            
+            // 鍏朵粬甯歌鏍煎紡
+            ".csv" => "text/csv",
+            ".zip" => "application/zip",
+            ".rar" => "application/x-rar-compressed",
+            ".7z" => "application/x-7z-compressed",
+            ".tar" => "application/x-tar",
+            ".gz" => "application/gzip",
+            
+            // 榛樿
+            _ => "application/octet-stream"
+        };
+    }
+
+    
 }
\ No newline at end of file
diff --git a/StandardInterface/MESApplication/Controllers/QC/XJController.cs b/StandardInterface/MESApplication/Controllers/QC/XJController.cs
index e515b8c..f1e703c 100644
--- a/StandardInterface/MESApplication/Controllers/QC/XJController.cs
+++ b/StandardInterface/MESApplication/Controllers/QC/XJController.cs
@@ -5,6 +5,7 @@
 using MES.Service.util;
 using Microsoft.AspNetCore.Mvc;
 using Newtonsoft.Json.Linq;
+using System.Web;
 
 namespace MESApplication.Controllers.QC;
 
@@ -599,4 +600,137 @@
             return ResponseResult.ResponseError(ex);
         }
     }
+
+    /// <summary>
+    /// 鑾峰彇闄勪欢淇℃伅
+    /// </summary>
+    /// <param name="data">鍖呭惈itemNo鐨凧SON瀵硅薄</param>
+    /// <returns>闄勪欢鍒楄〃</returns>
+    [HttpPost("getAttachments")]
+    public ResponseResult GetAttachments([FromBody] JObject data)
+    {
+        var itemNo = data["itemNo"]?.ToString();
+        try
+        {
+            dynamic resultInfos = new System.Dynamic.ExpandoObject();
+            var tbBillList = new XJService().GetAttachments(itemNo);
+            if (tbBillList == null || tbBillList.Count == 0)
+            {
+                return new ResponseResult
+                {
+                    status = 1,
+                    message = "璇ユ楠屽崟鏈笂浼犻檮浠朵俊鎭紒",
+                    data = null
+                };
+            }
+            resultInfos.tbBillList = tbBillList;
+            return new ResponseResult
+            {
+                status = 0,
+                message = "OK",
+                data = resultInfos
+            };
+        }
+        catch (Exception ex)
+        {
+            return ResponseResult.ResponseError(ex);
+        }
+    }
+
+    /// <summary>
+    /// 棰勮FTP鏂囦欢
+    /// </summary>
+    /// <param name="itemNo">鐗╂枡缂栫爜</param>
+    /// <param name="fileName">鏂囦欢鍚�</param>
+    /// <param name="ftpServer">FTP鏈嶅姟鍣ㄥ湴鍧�</param>
+    /// <returns>鏂囦欢鍐呭</returns>
+    [HttpGet("PreviewFtpFile")]
+    public IActionResult PreviewFtpFile([FromQuery] string itemNo, [FromQuery] string fileName, [FromQuery] string ftpServer)
+    {
+        try
+        {
+            // 娣诲姞CORS鍝嶅簲澶�
+            Response.Headers.Add("Access-Control-Allow-Origin", "*");
+            Response.Headers.Add("Access-Control-Allow-Methods", "GET, OPTIONS");
+            Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
+            Response.Headers.Add("Access-Control-Expose-Headers", "Content-Type, Content-Length");
+            
+            var service = new XJService();
+            var fileBytes = service.GetFtpFile(itemNo, fileName, ftpServer);
+            
+            if (fileBytes == null || fileBytes.Length == 0)
+            {
+                return NotFound("鏂囦欢鍦‵TP鏈嶅姟鍣ㄤ笂涓嶅瓨鍦�");
+            }
+            
+            var contentType = service.GetContentType(fileName);
+            fileName = fileName?.Trim().Replace("\r", "").Replace("\n", "");
+            
+            return File(fileBytes, contentType);
+        }
+        catch (Exception ex)
+        {
+            return StatusCode(500, $"棰勮鏂囦欢澶辫触锛歿ex.Message}");
+        }
+    }
+
+    /// <summary>
+    /// 涓嬭浇FTP鏂囦欢
+    /// </summary>
+    /// <param name="itemNo">鐗╂枡缂栫爜</param>
+    /// <param name="fileName">鏂囦欢鍚�</param>
+    /// <param name="ftpServer">FTP鏈嶅姟鍣ㄥ湴鍧�</param>
+    /// <returns>鏂囦欢涓嬭浇</returns>
+    [HttpGet("DownloadFtpFile")]
+    public IActionResult DownloadFtpFile([FromQuery] string itemNo, [FromQuery] string fileName, [FromQuery] string ftpServer)
+    {
+        try
+        {
+            // 娣诲姞CORS鍝嶅簲澶� - 鍏抽敭閰嶇疆鐢ㄤ簬瑙e喅璺ㄥ煙闂
+            Response.Headers.Add("Access-Control-Allow-Origin", "*");
+            Response.Headers.Add("Access-Control-Allow-Methods", "GET, OPTIONS");
+            Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization");
+            Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition, Content-Length, Content-Type");
+            
+            var service = new XJService();
+            var fileBytes = service.GetFtpFile(itemNo, fileName, ftpServer);
+            
+            if (fileBytes == null || fileBytes.Length == 0)
+            {
+                return NotFound("鏂囦欢鍦‵TP鏈嶅姟鍣ㄤ笂涓嶅瓨鍦�");
+            }
+            
+            var contentType = service.GetContentType(fileName);
+            fileName = fileName?.Trim().Replace("\r", "").Replace("\n", "");
+            
+            // 璁剧疆姝g‘鐨凜ontent-Disposition鍝嶅簲澶翠互鏀寔鏂囦欢涓嬭浇
+            var result = File(fileBytes, "application/octet-stream", fileName);
+            
+            // 纭繚Content-Disposition澶存纭缃紝鏀寔涓枃鏂囦欢鍚�
+            if (!string.IsNullOrEmpty(fileName))
+            {
+                var encodedFileName = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
+                Response.Headers.Add("Content-Disposition", $"attachment; filename*=UTF-8''{encodedFileName}");
+            }
+            
+            return result;
+        }
+        catch (Exception ex)
+        {
+            return StatusCode(500, $"涓嬭浇鏂囦欢澶辫触锛歿ex.Message}");
+        }
+    }
+
+    [HttpOptions("PreviewFtpFile")]
+    [HttpOptions("DownloadFtpFile")]
+    public IActionResult HandleOptions()
+    {
+        Response.Headers.Add("Access-Control-Allow-Origin", "*");
+        Response.Headers.Add("Access-Control-Allow-Methods", "GET, OPTIONS");
+        Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization");
+        Response.Headers.Add("Access-Control-Max-Age", "86400");
+        return Ok();
+    }
+
+
 }
\ No newline at end of file

--
Gitblit v1.9.3