xwt
2025-10-21 527bed43ea41443fd602305cb673fb4337179d51
StandardInterface/MES.Service/service/QC/SJService.cs
@@ -206,14 +206,14 @@
                IsPass = a.IsPass,
                ItemId = a.ItemId,
                Mnum = b.Mnum,  // 从主表获取MNUM
                Dnum = b.Dnum,  // 从主表获取DNUM
                Dnum = b.Dnum,  // 从子表获取DNUM
                Snum = a.Snum,  // 送检批数
                Remarks = a.Remarks
            }).ToList();
        var array = qsItemIpiItems.Select(s => s.Id).ToArray();
        var qsItemIpiItemDetails = db.Queryable<QsItemIpiItemDetail>()
            .Where(s => array.Contains(s.Pid))
            .Where(s => array.Contains(s.Pid) && s.FcheckResu != "/")
            .GroupBy(s => s.Pid)
            .Select(s => new
            {
@@ -232,12 +232,59 @@
            else
            {
                s.isCheck = find.count;
                if (find.count == s.LevelNum && s.IsPass == 1)
                    s.result = "合格";
                else if (find.count == s.LevelNum && s.IsPass == 0)
                    s.result = "不合格";
                // 计算实际需要检验的数量(排除堵穴)
                int actualRequiredCount = (int)(s.LevelNum ?? 0);
                if (s.HoleNumbers != null && s.HoleNumbers.Count > 0)
                {
                    // 如果有穴号信息,计算非堵穴的数量
                    actualRequiredCount = s.HoleNumbers.Count(h => !h.IsBlocked);
                }
                // 调试信息:结果判定
                Console.WriteLine($"getQSItems: Pid={s.Id}, find.count={find.count}, actualRequiredCount={actualRequiredCount}, IsPass={s.IsPass}");
                // 如果有检验记录,根据合格情况判断状态
                if (find.count > 0)
                {
                    // 获取合格数量
                    var passCount = db.Queryable<QsItemIpiItemDetail>()
                        .Where(a => a.Pid == s.Id && a.Fstand == "√" && a.FcheckResu != "/").Count();
                    // 获取不合格数量
                    var failCount = db.Queryable<QsItemIpiItemDetail>()
                        .Where(a => a.Pid == s.Id && a.Fstand == "×" && a.FcheckResu != "/").Count();
                    // 如果有不合格记录,直接显示不合格
                    if (failCount > 0)
                    {
                        s.result = "不合格";
                    }
                    // 如果全部合格且数量匹配,显示合格
                    else if (passCount == actualRequiredCount && find.count == actualRequiredCount)
                    {
                        s.result = "合格";
                    }
                    // 如果部分完成,显示进行中
                    else if (find.count < actualRequiredCount)
                    {
                        s.result = "进行中";
                    }
                    // 如果全部完成但合格数量不足,显示不合格
                    else if (find.count == actualRequiredCount && passCount < actualRequiredCount)
                    {
                        s.result = "不合格";
                    }
                    // 其他情况显示进行中
                    else
                    {
                        s.result = "进行中";
                    }
                }
                else
                {
                    s.result = "未完成";
                }
            }
        });
@@ -301,7 +348,24 @@
            detail.Fstand = "√";
            detail.FcheckResu = "1";
            detail.UpdateBy = item.From.StatusUser;
            detail.count = (int?)s.LevelNum;
            // 计算默认合格的数量:(检验数 * 开穴数) - (检验数 * 堵穴数)
            if (s.HoleNumbers != null && s.HoleNumbers.Count > 0)
            {
                // 如果有穴号信息,计算开穴数和堵穴数
                int openHoles = s.HoleNumbers.Count(h => !h.IsBlocked);  // 开穴数
                int blockedHoles = s.HoleNumbers.Count(h => h.IsBlocked);  // 堵穴数
                int checkCount = (int)(s.LevelNum ?? 1);  // 检验数
                // 计算:(检验数 * 开穴数) - (检验数 * 堵穴数)
                detail.count = (checkCount * openHoles) - (checkCount * blockedHoles);
            }
            else
            {
                // 否则使用LevelNum
                detail.count = (int?)s.LevelNum;
            }
            SetQSItemDetail(detail);
        });
@@ -337,7 +401,24 @@
            detail.Fstand = "√";
            detail.FcheckResu = "1";
            detail.UpdateBy = item.StatusUser;
            detail.count = (int?)s.LevelNum;
            // 计算默认合格的数量:(检验数 * 开穴数) - (检验数 * 堵穴数)
            if (s.HoleNumbers != null && s.HoleNumbers.Count > 0)
            {
                // 如果有穴号信息,计算开穴数和堵穴数
                int openHoles = s.HoleNumbers.Count(h => !h.IsBlocked);  // 开穴数
                int blockedHoles = s.HoleNumbers.Count(h => h.IsBlocked);  // 堵穴数
                int checkCount = (int)(s.LevelNum ?? 1);  // 检验数
                // 计算:(检验数 * 开穴数) - (检验数 * 堵穴数)
                detail.count = (checkCount * openHoles) - (checkCount * blockedHoles);
            }
            else
            {
                // 否则使用LevelNum
                detail.count = (int?)s.LevelNum;
            }
            SetQSItemDetail(detail);
        });
@@ -402,17 +483,38 @@
        if (qsItemIpiItem == null) return 0;
        var count = db.Queryable<QsItemIpiItemDetail>()
            .Where(s => s.Pid == detail.Pid).Count();
            .Where(s => s.Pid == detail.Pid && s.FcheckResu != "/").Count();
        // 计算实际需要检验的数量(排除堵穴)
        var actualRequiredCount = qsItemIpiItem.LevelNum;
        if (qsItemIpiItem.HoleNumbers != null && qsItemIpiItem.HoleNumbers.Count > 0)
        {
            // 如果有穴号信息,计算非堵穴的数量
            actualRequiredCount = qsItemIpiItem.HoleNumbers.Count(h => !h.IsBlocked);
        }
        var result = 0;
        if (qsItemIpiItem.LevelNum != count) return 0;
        // 比较实际需要检验的数量和实际检验记录数量
        if (actualRequiredCount != count)
        {
            // 调试信息:记录数量不匹配
            Console.WriteLine($"autoResult: actualRequiredCount={actualRequiredCount}, count={count}, Pid={detail.Pid}");
            // 即使数量不匹配,也要继续执行后续逻辑来更新IS_PASS字段
            // return 0; // 注释掉这行,让方法继续执行
        }
        var passCount = db.Queryable<QsItemIpiItemDetail>()
            .Where(s => s.Pid == detail.Pid && s.Fstand == "√").Count();
            .Where(s => s.Pid == detail.Pid && s.Fstand == "√" && s.FcheckResu != "/").Count();
        if (count == passCount) result = 1;
        // 调试信息:统计信息
        Console.WriteLine($"autoResult: count={count}, passCount={passCount}, Pid={detail.Pid}");
        // 只有在数量匹配时才进行合格性判断
        if (actualRequiredCount == count && count == passCount)
        {
            result = 1;
        }
        var useTransactionWithOracle = SqlSugarHelper.UseTransactionWithOracle(
            db =>
@@ -427,14 +529,30 @@
        //自动判定是否合格
        //获取检验单的检验项目理论个数
        var sum = db.Queryable<QsItemIpiItem>()
            .Where(s => s.Pid == detail.Gid).Sum(it => it.LevelNum);
        if (sum == null || sum == 0) return 1;
        //获取检验单的检验项目实际需要检验个数(排除堵穴)
        var sum = 0;
        var qsItems = db.Queryable<QsItemIpiItem>()
            .Where(s => s.Pid == detail.Gid).ToList();
        foreach (var item in qsItems)
        {
            if (item.HoleNumbers != null && item.HoleNumbers.Count > 0)
            {
                // 如果有穴号信息,计算非堵穴的数量
                sum += item.HoleNumbers.Count(h => !h.IsBlocked);
            }
            else
            {
                // 否则使用LevelNum
                sum += (int)(item.LevelNum ?? 0);
            }
        }
        if (sum == 0) return 1;
        //获取检验单下的检验项目实际个数
        //获取检验单下的检验项目实际个数(排除堵穴)
        var icount = db.Queryable<QsItemIpiItemDetail>()
            .Where(s => s.Gid == detail.Gid).Count();
            .Where(s => s.Gid == detail.Gid && s.FcheckResu != "/").Count();
        if (icount == 0) return 1;
@@ -548,7 +666,7 @@
        return withOracle;
    }
    //刷新检验项目
    public (int result, string message) GenUpdate(decimal? id, string? no, string? user)
    public (int result, string message) GenUpdate(decimal? id, string? no, string? user, decimal? mnum = null, string? dnum = null)
    {
        var outputResult = new SugarParameter("PO_RESULT", null, System.Data.DbType.Int32, ParameterDirection.Output, 4000);
        var outputMessage = new SugarParameter("PO_TEXT", null, System.Data.DbType.String, ParameterDirection.Output, 4000);
@@ -558,13 +676,15 @@
        new("P_ID", id, System.Data.DbType.Decimal, ParameterDirection.Input),
        new("P_NO", no, System.Data.DbType.String, ParameterDirection.Input),
        new("P_USER", user, System.Data.DbType.String, ParameterDirection.Input),
        new("P_MNUM", mnum, System.Data.DbType.Decimal, ParameterDirection.Input),
        new("P_DNUM", dnum, System.Data.DbType.String, ParameterDirection.Input),
        outputResult,
        outputMessage
    };
        var db = SqlSugarHelper.GetInstance();
        db.Ado.ExecuteCommand(
            "BEGIN PRC_GEN_UPDATE(:P_ID, :P_NO, :P_USER, :PO_RESULT, :PO_TEXT); END;",
            "BEGIN PRC_GEN_UPDATE(:P_ID,:P_NO,:P_MNUM,:P_DNUM,:P_USER, :PO_RESULT, :PO_TEXT); END;",
            parameters.ToArray());
        int result = outputResult.Value == null ? -1 : Convert.ToInt32(outputResult.Value);
@@ -615,6 +735,234 @@
        {
            throw new Exception(ex.Message);
        }
    }
    /// <summary>
    /// 获取附件信息
    /// </summary>
    /// <param name="itemNo">物料编码</param>
    /// <returns>附件列表</returns>
    public List<QamftpDto> GetAttachments(string itemNo, string projName = null)
    {
        var db = SqlSugarHelper.GetInstance();
        try
        {
            var query = db.Queryable<MesQamftp>()
                .Where(x => x.ItemNo == itemNo)
                .Where(x => x.Ftype == "首检");
            // 如果传入了projName,则按Fversion过滤
            if (!string.IsNullOrEmpty(projName))
            {
                query = query.Where(x => x.Fversion == projName);
            }
            return query.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,
                    Pid = x.Pid
                }).ToList();
        }
        catch (Exception ex)
        {
            throw new Exception($"查询附件信息失败: {ex.Message}");
        }
    }
    /// <summary>
    /// 从FTP服务器获取文件(首检使用OPC目录)
    /// </summary>
    /// <param name="itemNo">物料编码</param>
    /// <param name="fileName">文件名</param>
    /// <param name="ftpServer">FTP服务器地址</param>
    /// <param name="projName">项目名称</param>
    /// <returns>文件字节数组</returns>
    public byte[] GetFtpFile(string itemNo, string fileName, string ftpServer, string projName = null)
    {
        // 参数验证
        if (string.IsNullOrEmpty(itemNo) || string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(ftpServer))
        {
            throw new ArgumentException("参数不能为空: itemNo, fileName, ftpServer");
        }
        string ftpUser = "hm_ftp";
        string ftpPwd = "dell_123";
        // 标准化FTP服务器地址
        string normalizedServer = NormalizeFtpServer(ftpServer);
        // 构建FTP文件路径 - 首检使用OPC目录,如果传入了projName则使用新格式
        string ftpPath;
        if (!string.IsNullOrEmpty(projName))
        {
            ftpPath = $"{normalizedServer}/OPC/{itemNo}/{projName}/{fileName}";
        }
        else
        {
            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>
    /// 标准化FTP服务器地址
    /// </summary>
    /// <param name="ftpServer">FTP服务器地址</param>
    /// <returns>标准化后的FTP服务器地址</returns>
    private string NormalizeFtpServer(string ftpServer)
    {
        if (string.IsNullOrEmpty(ftpServer))
        {
            throw new ArgumentException("FTP服务器地址不能为空");
        }
        // 确保以ftp://开头
        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"
        };
    }
    /// <summary>
@@ -680,4 +1028,127 @@
        return result;
    }
    /// <summary>
    /// 上传图片到检验项目的PICTURE字段
    /// </summary>
    /// <param name="id">检验项目ID</param>
    /// <param name="imageBytes">图片字节数组</param>
    /// <param name="fileName">原始文件名</param>
    /// <param name="createBy">创建人</param>
    /// <returns>操作结果</returns>
    public (int status, string message) UploadImageToPicture(decimal id, byte[] imageBytes, string fileName, string createBy)
    {
        try
        {
            if (imageBytes == null || imageBytes.Length == 0)
            {
                return (1, "图片数据为空");
            }
            if (string.IsNullOrEmpty(fileName))
            {
                return (1, "文件名为空");
            }
            // 验证图片格式
            var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp" };
            var extension = System.IO.Path.GetExtension(fileName).ToLower();
            if (!allowedExtensions.Contains(extension))
            {
                return (1, "不支持的图片格式,仅支持:jpg, jpeg, png, gif, bmp, webp");
            }
            // 验证图片大小(限制为5MB)
            if (imageBytes.Length > 5 * 1024 * 1024)
            {
                return (1, "图片大小不能超过5MB");
            }
            // 生成时间戳文件名,格式:1746945271304.jpg
            var timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
            var timestampFileName = $"{timestamp}{extension}";
            var result = SqlSugarHelper.UseTransactionWithOracle(db =>
            {
                // 检查检验项目是否存在
                var exists = db.Queryable<QsItemIpiItem>()
                    .Where(s => s.Id == id)
                    .Any();
                if (!exists)
                {
                    throw new Exception("检验项目不存在");
                }
                // 更新PICTURE字段(LONG RAW类型)和PICTURENAME字段(时间戳文件名)
                var updateResult = db.Updateable<QsItemIpiItem>()
                    .SetColumns(s => s.Picture == imageBytes)
                    .SetColumns(s => s.Picturename == timestampFileName)
                    .Where(s => s.Id == id)
                    .ExecuteCommand();
                return updateResult;
            });
            if (result > 0)
            {
                return (0, "图片保存成功");
            }
            else
            {
                return (1, "图片保存失败,未找到对应的检验项目");
            }
        }
        catch (Exception ex)
        {
            return (1, $"图片保存失败:{ex.Message}");
        }
    }
    /// <summary>
    /// 删除检验项目的图片
    /// </summary>
    /// <param name="id">检验项目ID</param>
    /// <returns>操作结果</returns>
    public (int status, string message) DeleteImageFromPicture(decimal id)
    {
        try
        {
            var result = SqlSugarHelper.UseTransactionWithOracle(db =>
            {
                // 检查检验项目是否存在
                var exists = db.Queryable<QsItemIpiItem>()
                    .Where(s => s.Id == id)
                    .Any();
                if (!exists)
                {
                    throw new Exception("检验项目不存在");
                }
                // 清空PICTURE字段和PICTURENAME字段
                var updateResult = db.Updateable<QsItemIpiItem>()
                    .SetColumns(s => s.Picture == null)
                    .SetColumns(s => s.Picturename == null)
                    .Where(s => s.Id == id)
                    .ExecuteCommand();
                return updateResult;
            });
            if (result > 0)
            {
                return (0, "图片删除成功");
            }
            else
            {
                return (1, "图片删除失败,未找到对应的检验项目");
            }
        }
        catch (Exception ex)
        {
            return (1, $"图片删除失败:{ex.Message}");
        }
    }
}