WebAPI/Controllers/WebAPIController.cs
@@ -20,6 +20,7 @@
using WebAPI.Models;
using WebAPI.Service;
using SyntacticSugar.constant;
using System.Text.RegularExpressions;
namespace WebAPI.Controllers
{
@@ -340,6 +341,7 @@
        /// <returns></returns>
        [Route("Web/GetUser")]
        [HttpGet]
        [AllowAnonymous]
        public object GetUser(string UserName, string PassWord, string HOrgName)
        {
            try
@@ -384,11 +386,23 @@
                    }
                }
                if (!oSystemParameter.ShowBill(ref DBUtility.ClsPub.sErrInfo))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "登录异常!Token 生成异常,无法获取公司信息!";
                }
                string tokenStr = Utility.JWTHelper.GenerateToken(ds.Tables[0].Rows[0]["Czybm"].ToString(), ds.Tables[0].Rows[0]["Czymc"].ToString());
                objjson.code = "0";
                objjson.count = 1;
                objjson.Message = "[0000-1-073]登录成功!";
                objjson.data = ds.Tables[0];
                return objjson;
                JObject jobjJsonResult = JObject.FromObject(objjson);
                jobjJsonResult["token"] = tokenStr;
                return jobjJsonResult;
            }
            catch (Exception e)
@@ -396,7 +410,7 @@
                objjson.code = "0";
                objjson.count = 0;
                objjson.Message = "[0000-1-074]登录异常!" + e.Message;
                objjson.Message = "[0000-1-074]登录异常!" + e;
                objjson.data = null;
                return objjson; ;
            }
@@ -2619,6 +2633,7 @@
        /// <returns></returns>
        [Route("Web/GetDataBases")]
        [HttpGet]
        [AllowAnonymous]
        public object GetDataBases()
        {
            try
@@ -18965,6 +18980,7 @@
        /// <returns></returns>
        [Route("Web/GetOrganizations")]
        [HttpGet]
        [AllowAnonymous]
        public object GetOrganizations()
        {
            try
@@ -18997,6 +19013,7 @@
        /// <returns></returns>
        [Route("Web/BaseInfo")]
        [HttpGet]
        [AllowAnonymous]
        public object GetBaseInfo()
        {
            try
@@ -20457,7 +20474,7 @@
            {
                objjson.code = "0";
                objjson.count = 0;
                objjson.Message = "获取失败" + ex.ToString();
                objjson.Message = "获取失败" + ex.Message.ToString();
                objjson.data = null;
                return objjson;
            }
@@ -20952,7 +20969,18 @@
                {
                    objjson.code = "0";
                    objjson.count = 0;
                    objjson.Message = "获取失败,明细查无数据";
                    if(Type == "DJ")
                    {
                        objjson.Message = "获取失败,模具无绑定的点检规程";
                    }
                    else if (Type == "BY")
                    {
                        objjson.Message = "获取失败,模具无绑定的保养规程";
                    }
                    else
                    {
                        objjson.Message = "获取失败,明细查无数据";
                    }
                    objjson.data = null;
                    return objjson;
                }
@@ -21153,12 +21181,12 @@
                SQLHelper.ClsCN oCN = new SQLHelper.ClsCN();
                ds = oCN.RunProcReturn("select ManagerFlag from gy_czygl where czymc='" + user.Trim() + "'", "gy_czygl");
                if (!(bool)ds.Tables[0].Rows[0]["ManagerFlag"])  //是否管理员
                {
                    //不是管理员
                    sWhere += " and 制单人 = '" + user + "'";
                }
                //ds = oCN.RunProcReturn("select ManagerFlag from gy_czygl where czymc='" + user.Trim() + "'", "gy_czygl");
                //if (!(bool)ds.Tables[0].Rows[0]["ManagerFlag"])  //是否管理员
                //{
                //    //不是管理员
                //    sWhere += " and 制单人 = '" + user + "'";
                //}
                string sql = string.Format(@"select * from " + HView + " where 1 = 1 " + sWhere + " order by 日期 desc, hmainid desc");
@@ -22836,6 +22864,7 @@
        /// <returns></returns>
        [Route("Web/GetModuleName")]
        [HttpGet]
        [AllowAnonymous]
        public object GetModuleName(string HModuleType)
        {
            try
@@ -23439,6 +23468,7 @@
        #region 用于连接的健康度检验,只要能访问通这个接口,则表明连接可用
        [Route("Health")]
        [HttpGet]
        [AllowAnonymous]
        public IHttpActionResult CheckHealth()
        {
            // 返回 200 状态码 确认健康状态
@@ -23729,5 +23759,462 @@
            }
        }
        #endregion
        #region APP 获取异常反馈单 获取 检验单内容 通用方法
        [Route("Web/getCheckBillStatus")]
        [HttpGet]
        public object getCheckBillStatus(Int64 HInterID, string HBillType)
        {
            try {
                string sql = "";
                List<object> columnNameList = new List<object>();
                if(HBillType == "7505")
                {
                    // 首检
                    sql = $@"SELECT
                          a.HInterID AS hmainid,b.HEntryID hsubid, a.HDate AS 日期, a.HBillNo AS 单据号,
                          a.HRemark AS 表头备注,s.HName 生产资源名称,s.HNumber 生产资源代码, m.HNumber AS 产品内码, m.HName AS 产品名称, m.HModel AS 产品型号,e.HNumber as 检验员代码, e.HName as 检验员名称,
                          a.HMaker AS 制单人, a.HMakeDate AS 制单日期, a.HChecker AS 审核人, a.HCheckDate AS 审核日期, a.HUpDater AS 修改人,
                          a.HUpDateDate AS 修改日期, a.HCloseMan AS 关闭人, a.HCloseDate AS 关闭日期, a.HDeleteMan AS 作废人, a.HDeleteDate AS 作废日期,
                          a.HBillType AS 单据类型,b.HEntryID hsubid, a.HCheckQty 检验数量, a.HSourceID HSourceID,
                        a.HProcExchInterID HProcExchInterID, a.HProcExchEntryID HProcExchEntryID, a.HProcExchBillNo 工序流转卡号,
                        a.HICMOInterID HICMOInterID, a.HICMOEntryID HICMOEntryID, a.HICMOBillNo 生产订单号
                          FROM
                          dbo.QC_FirstPieceCheckBillMain AS a INNER JOIN
                          dbo.QC_FirstPieceCheckBillSub AS b ON a.HInterID = b.HInterID LEFT OUTER JOIN
                        dbo.Gy_Source s on a.HSourceID =s.HItemID LEFT OUTER JOIN
                        dbo.Gy_Material m on a.HMaterID = m.HItemID LEFT OUTER JOIN
                          dbo.Gy_Employee AS e ON a.HFirstCheckEmp = e.HItemID ";
                    sql += $" where a.HInterID = {HInterID}";
                    ds = oCN.RunProcReturn(sql, "QC_FirstPieceCheckBillMain");
                }
                else if (HBillType == "7520")
                {
                    // 巡检
                    sql = $@"SELECT
                          a.HInterID AS hmainid,b.HEntryID hsubid, a.HDate AS 日期, a.HBillNo AS 单据号,
                          a.HRemark AS 表头备注,s.HName 生产资源名称,s.HNumber 生产资源代码, m.HNumber AS 产品内码, m.HName AS 产品名称, m.HModel AS 产品型号,e.HNumber as 检验员代码, e.HName as 检验员名称,
                          a.HMaker AS 制单人, a.HMakeDate AS 制单日期, a.HChecker AS 审核人, a.HCheckDate AS 审核日期, a.HUpDater AS 修改人,
                          a.HUpDateDate AS 修改日期, a.HCloseMan AS 关闭人, a.HCloseDate AS 关闭日期, a.HDeleteMan AS 作废人, a.HDeleteDate AS 作废日期,
                          a.HBillType AS 单据类型,b.HEntryID hsubid, a.HCheckQty 检验数量, a.HSourceID HSourceID,
                        a.HProcExchInterID HProcExchInterID, a.HProcExchEntryID HProcExchEntryID, a.HProcExchBillNo 工序流转卡号,
                        a.HICMOInterID HICMOInterID, a.HICMOEntryID HICMOEntryID, a.HICMOBillNo 生产订单号
                          FROM
                          dbo.QC_PatrolProcCheckOtherBillMain AS a INNER JOIN
                          dbo.QC_PatrolProcCheckOtherBillSub AS b ON a.HInterID = b.HInterID LEFT OUTER JOIN
                        dbo.Gy_Source s on a.HSourceID =s.HItemID LEFT OUTER JOIN
                        dbo.Gy_Material m on a.HMaterID = m.HItemID LEFT OUTER JOIN
                          dbo.Gy_Employee AS e ON a.HFirstCheckEmp = e.HItemID ";
                    sql += $" where a.HInterID = {HInterID}";
                    ds = oCN.RunProcReturn(sql, "QC_PatrolProcCheckOtherBillMain");
                }
                else if(HBillType == "7507")
                {
                    // 末检
                    sql = $@"SELECT
                          a.HInterID AS hmainid,b.HEntryID hsubid, a.HDate AS 日期, a.HBillNo AS 单据号,
                          a.HRemark AS 表头备注,s.HName 生产资源名称,s.HNumber 生产资源代码, m.HNumber AS 产品内码, m.HName AS 产品名称, m.HModel AS 产品型号,e.HNumber as 检验员代码, e.HName as 检验员名称,
                          a.HMaker AS 制单人, a.HMakeDate AS 制单日期, a.HChecker AS 审核人, a.HCheckDate AS 审核日期, a.HUpDater AS 修改人,
                          a.HUpDateDate AS 修改日期, a.HCloseMan AS 关闭人, a.HCloseDate AS 关闭日期, a.HDeleteMan AS 作废人, a.HDeleteDate AS 作废日期,
                          a.HBillType AS 单据类型,b.HEntryID hsubid, a.HCheckQty 检验数量, a.HSourceID HSourceID,
                        a.HProcExchInterID HProcExchInterID, a.HProcExchEntryID HProcExchEntryID, a.HProcExchBillNo 工序流转卡号,
                        a.HICMOInterID HICMOInterID, a.HICMOEntryID HICMOEntryID, a.HICMOBillNo 生产订单号
                          , HRemarkSN 条码
                          FROM
                          dbo.QC_ProcessCheckBillMain AS a INNER JOIN
                          dbo.QC_ProcessCheckBillSub AS b ON a.HInterID = b.HInterID LEFT OUTER JOIN
                        dbo.Gy_Source s on a.HSourceID =s.HItemID LEFT OUTER JOIN
                        dbo.Gy_Material m on a.HMaterID = m.HItemID LEFT OUTER JOIN
                          dbo.Gy_Employee AS e ON a.HFirstCheckEmp = e.HItemID ";
                    sql += $" where a.HInterID = {HInterID}";
                    ds = oCN.RunProcReturn(sql, "QC_ProcessCheckBillMain");
                }
                if(ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "查询数据异常,无检验单!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                //添加列名
                foreach (DataColumn col in ds.Tables[0].Columns)
                {
                    Type dataType = col.DataType;
                    string ColmString = "{\"ColmCols\":\"" + col.ColumnName + "\",\"ColmType\":\"" + dataType.Name + "\"}";
                    columnNameList.Add(JsonConvert.DeserializeObject(ColmString));//获取到DataColumn列对象的列名
                }
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = ds.Tables[0];
                objJsonResult.list = columnNameList;
                return objJsonResult;
            }
            catch (Exception ex)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "查询数据异常,请与管理员联系!" + ex.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
        #region 根据设备id获取设备数采数据
        private class EquipTechParam
        {
            public string TechParamName { get; set; }
            public DateTime CreateTime { get; set; }
            public string Result { get; set; }
        }
        [Route("Web/getSB_EquipTechParamBillListByEquipID")]
        [HttpGet]
        public object getSB_EquipTechParamBillListByEquipID(Int64 HEquipID)
        {
            try
            {
                List<object> columnNameList = new List<object>();
                // 工艺参数分类列表
                List<string> categoryNames = new List<string>();
                ds = oCN.RunProcReturn($"exec h_p_SB_EquipTechParamBillListByEquipID {HEquipID}", "h_p_SB_EquipTechParamBillListByEquipID");
                var ds1 = oCN.RunProcReturn($"select * from h_v_Gy_Technology", "h_v_Gy_Technology");
                if (ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "当前设备没有数采信息";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                // 遍历获取工艺参数分类列表
                if (ds1.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow row in ds1.Tables[0].Rows)
                    {
                        string categoryName = row["工艺参数分类名称"].ToString().Trim();
                        if (!string.IsNullOrEmpty(categoryName))
                        {
                            categoryNames.Add(categoryName);
                        }
                    }
                }
                // 提取原始数据到模型列表
                var rawParams = new List<EquipTechParam>();
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    rawParams.Add(new EquipTechParam
                    {
                        TechParamName = row["HTechParamName"].ToString().Trim(),
                        CreateTime = Convert.ToDateTime(row["HCreateTime"]),
                        Result = row["HResult"].ToString()
                    });
                }
                // 按工艺分类名称分组
                Dictionary<string, List<EquipTechParam>> groupedParams = new Dictionary<string, List<EquipTechParam>>();
                // 初始化所有工艺分类分组
                foreach (string category in categoryNames)
                {
                    groupedParams[category] = new List<EquipTechParam>();
                }
                // 新增“其他参数”兜底分组
                groupedParams["其他参数"] = new List<EquipTechParam>();
                // 匹配参数到对应分组(按参数名包含分类名称子串)
                foreach (var param in rawParams)
                {
                    bool isMatched = false;
                    // 遍历所有工艺分类,判断参数名是以该分类名称开头
                    foreach (string category in categoryNames)
                    {
                        if (param.TechParamName.StartsWith(category))
                        {
                            if(param.TechParamName.Length != category.Length)
                            {
                                param.TechParamName = param.TechParamName.Substring(category.Length);
                            }
                            groupedParams[category].Add(param);
                            isMatched = true;
                            break; // 匹配到第一个分类后停止(避免重复匹配)
                        }
                    }
                    // 无匹配分类则归为“其他参数”
                    if (!isMatched)
                    {
                        groupedParams["其他参数"].Add(param);
                    }
                }
                // 转换为JArray格式(前端可直接解析)
                JArray resultJArray = new JArray();
                foreach (var group in groupedParams)
                {
                    // 过滤空分组(无数据的分类不返回)
                    if (group.Value.Count == 0) continue;
                    JObject groupJObj = new JObject();
                    groupJObj.Add("分组名称", group.Key); // 工艺参数分类名称(如中子、保压)
                    JArray paramsJArray = new JArray();
                    foreach (var param in group.Value.OrderBy(p => p.TechParamName))
                    {
                        JObject paramJObj = new JObject();
                        paramJObj.Add("HTechParamName", param.TechParamName);
                        paramJObj.Add("HCreateTime", param.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                        paramJObj.Add("HResult", param.Result);
                        paramsJArray.Add(paramJObj);
                    }
                    groupJObj.Add("参数列表", paramsJArray);
                    resultJArray.Add(groupJObj);
                }
                // 保留原有列名逻辑(兼容前端)
                foreach (DataColumn col in ds.Tables[0].Columns)
                {
                    Type dataType = col.DataType;
                    string ColmString = "{\"ColmCols\":\"" + col.ColumnName + "\",\"ColmType\":\"" + dataType.Name + "\"}";
                    columnNameList.Add(JsonConvert.DeserializeObject(ColmString));
                }
                // 组装返回结果
                objJsonResult.code = "1";
                objJsonResult.count = resultJArray.Count; // 有效分组数量
                objJsonResult.Message = "Success!";
                objJsonResult.data = resultJArray;
                objJsonResult.list = columnNameList;
                return objJsonResult;
            }
            catch (Exception ex)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "查询数据异常,请与管理员联系!" + ex.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
        #region  APP登录权限验证接口
        /// <summary>
        /// APP登录权限验证接口
        /// </summary>
        [Route("Auth/CheckAppLoginAuth")]
        [HttpPost]
        public object CheckAppLoginAuth()
        {
            try
            {
                // 获取请求参数
                string orgID = HttpContext.Current.Request.Form["orgID"] ?? "";
                string orgName = HttpContext.Current.Request.Form["orgName"] ?? "";
                string serverUrl = HttpContext.Current.Request.Form["serverUrl"] ?? "";
                string phoneType = HttpContext.Current.Request.Form["phoneType"] ?? "";
                string userAccount = HttpContext.Current.Request.Form["userAccount"] ?? "";
                string other = HttpContext.Current.Request.Form["other"] ?? "";
                // 参数验证
                if (string.IsNullOrEmpty(userAccount))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "账号不能为空!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                if (string.IsNullOrEmpty(orgID))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "组织ID不能为空!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                // 参数安全处理(防止注入)
                orgID = orgID.Replace("'", "''");
                orgName = orgName.Replace("'", "''");
                serverUrl = serverUrl.Replace("'", "''");
                phoneType = phoneType.Replace("'", "''");
                userAccount = userAccount.Replace("'", "''");
                // 执行固定存储过程
                string sql = $"EXEC SP_CheckAppLoginAuth '{orgID}', '{orgName}', '{serverUrl}', '{phoneType}','{userAccount}','{other}'";
                ds = oCN.RunProcReturn(sql, "SP_CheckAppLoginAuth");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    int result = Convert.ToInt32(ds.Tables[0].Rows[0]["Result"]);
                    string message = ds.Tables[0].Rows[0]["Message"].ToString();
                    objJsonResult.code = "1";
                    objJsonResult.count = 1;
                    objJsonResult.Message = message;
                    objJsonResult.data = ds.Tables[0];
                }
                else
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "验证接口返回异常!";
                    objJsonResult.data = null;
                }
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
        #region 蓝牙打印机获取打印模板
        public class PrintRequestDto
        {
            public string ptMode { get; set; }
            public string templateName { get; set; }
            public JArray msg { get; set; } // 你的批量数据
        }
        /// <summary>
        /// ptMode: 打印模式,即需要那种打印指令,CPCL,TSPL,ESC,ZPL 中选择
        /// templateName: 模板名,根据模板去指定目录下根据后缀找文件
        /// msg: 打印内容
        /// </summary>
        /// <param name="ptMode"></param>
        /// <param name="templateName"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        [Route("WebAPI/getBLEPrintTemplate")]
        [HttpPost]
        public object getBLEPrintTemplate([FromBody] PrintRequestDto dto)
        {
            var ptMode = dto.ptMode;
            var templateName = dto.templateName;
            var msg = dto.msg;
            if (string.IsNullOrWhiteSpace(ptMode))
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "未选择打印模式,无法生成打印模板!";
                objJsonResult.data = null;
                return objJsonResult;
            }
            if (string.IsNullOrWhiteSpace(templateName))
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "未选择打印模板,无法生成打印模板!";
                objJsonResult.data = null;
                return objJsonResult;
            }
            string suffix = ".txt";
            string folder = "ptTemplate";
            // 匹配 {{ 字段名 }} 所需正则表达式 支持中文
            var regex = new Regex(@"{{\s*([\u4e00-\u9fa5a-zA-Z0-9_\s]+?)\s*}}", RegexOptions.Compiled);
            if (ptMode == "ZPL")
            {
                suffix = ".zpl";
                folder = "ZPLTemplate";
            }
            try
            {
                // 读取模板文件
                string rootPath = System.Web.HttpContext.Current.Server.MapPath("~/");
                string templateDir = Path.Combine(rootPath, folder);
                string templateFile = Path.Combine(templateDir, templateName+suffix);
                // 如果目录不存在
                if (!Directory.Exists(templateDir))
                {
                    Directory.CreateDirectory(templateDir);
                }
                // 如果文件不存在
                if (!File.Exists(templateFile))
                {
                    objJsonResult.code = "0";
                    objJsonResult.Message = $"模板文件不存在:{templateFile}";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                // 读取模板(UTF8 支持中文)
                string templateContent = File.ReadAllText(templateFile, Encoding.UTF8);
                // 逐行读取模板文件
                var lines = templateContent.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
                var sb = new StringBuilder();
                foreach(JToken JOneKVP in msg)
                {
                    if(JOneKVP is JObject item)
                    {
                        foreach (var line in lines)
                        {
                            string currentLine = line;
                            // 跳过注释行 //
                            if (currentLine.TrimStart().StartsWith("//"))
                            {
                                continue;
                            }
                            // 正则表达式匹配 {{ 字段名 }} 所在行的字段,如果有,则进行替换,没有,则默认为空字符串
                            currentLine = regex.Replace(currentLine, match =>
                            {
                                string fieldName = match.Groups[1].Value.Trim();
                                if (msg != null && item.ContainsKey(fieldName))
                                {
                                    return item[fieldName]?.ToString() ?? "";
                                }
                                return "";
                            });
                            // 将所有 \n 的换行符 替换为 \r\n
                            sb.Append(currentLine);
                            sb.Append("\r\n"); // 标准换行
                        }
                    }
                }
                string result = sb.ToString().TrimEnd();
                // 返回渲染后的打印指令
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = $"模板渲染成功";
                objJsonResult.data = result;
                return objJsonResult;
            }
            catch (Exception ex)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = $"模板渲染失败:{ex.Message}";
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
    }
}