chenhaozhe
21 小时以前 62c1c41aab86ad3bf8967149769f9c2a40ac4313
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 状态码 确认健康状态
@@ -23539,7 +23569,7 @@
                {
                    objjson.code = "0";
                    objjson.count = 0;
                    objjson.Message = "获取失败, 单据无返回值!";
                    objjson.Message = "无待上模单据!";
                    objjson.data = null;
                    return objjson;
                }else
@@ -23594,7 +23624,7 @@
                {
                    objjson.code = "0";
                    objjson.count = 0;
                    objjson.Message = "获取失败, 单据无返回值!";
                    objjson.Message = "无待开工单据!";
                    objjson.data = null;
                    return objjson;
                }
@@ -23651,7 +23681,7 @@
                {
                    objjson.code = "0";
                    objjson.count = 0;
                    objjson.Message = "获取失败, 单据无返回值!";
                    objjson.Message = "无待下模单据!";
                    objjson.data = null;
                    return objjson;
                }
@@ -23975,5 +24005,409 @@
            }
        }
        #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.Singleline);
            // 匹配 矩形框 位置 宽高 所需正则表达式
            var RectRegex = new Regex(@"^\^FO(\d+),(\d+)\^GB(\d+),(\d+)", RegexOptions.Singleline);
            // 匹配 模板字符串 所在行 位置 宽高 所需正则表达式 支持中文
            var fieldRegex = new Regex(@"\^FO(\d+),(\d+)\^A[A-Z]+,(\d+),(\d+).*?\{\{\s*([\u4e00-\u9fa5a-zA-Z0-9_\s]+?)\s*\}\}", RegexOptions.Singleline);
            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"); // 标准换行
                        //}
                        for(int i = 0; i<lines.Length; i++)
                        {
                            string currentLine = lines[i];
                            string preLine = "";
                            string concatStr = "";
                            if(i>0)
                            {
                                // 获取当前行的上一行,用于判断是否是矩形框
                                preLine = lines[i - 1];
                            }
                            // 跳过注释行 //
                            if (currentLine.TrimStart().StartsWith("//"))
                            {
                                continue;
                            }
                            // 判断矩形框,如果前一行是矩形框,则需判断该行字符串长度是否超长
                            if(!getConcatStr(rectRegex: RectRegex, fieldRegex: fieldRegex,
                                PreLine: preLine, CurrLine: currentLine, fieldObject: item,
                                templateRegex: regex,
                                ref concatStr))
                            {
                                // 正则表达式匹配 {{ 字段名 }} 所在行的字段,如果有,则进行替换,没有,则默认为空字符串
                                concatStr = regex.Replace(currentLine, match =>
                                {
                                    string fieldName = match.Groups[1].Value.Trim();
                                    if (msg != null && item.ContainsKey(fieldName))
                                    {
                                        return item[fieldName]?.ToString() ?? "";
                                    }
                                    return "";
                                });
                            }
                            if(string.IsNullOrWhiteSpace(concatStr))
                            {
                                concatStr = currentLine;
                            }
                            // 将所有 \n 的换行符 替换为 \r\n
                            sb.Append(concatStr);
                            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}";
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        private bool getConcatStr(Regex rectRegex, Regex fieldRegex,
            string PreLine, string CurrLine, JObject fieldObject, Regex templateRegex, ref string concatStr)
        {
            var rectRegexResult = rectRegex.Match(PreLine);
            var fieldRegexResult = fieldRegex.Match(CurrLine);
            var templateRegexResult = templateRegex.Match(CurrLine);
            if (!rectRegexResult.Success)
            {
                return false;
            }
            if(!fieldRegexResult.Success)
            {
                return false;
            }
            if(!templateRegexResult.Success)
            {
                return false;
            }
            // 矩形 位置 宽高
            int rectLocationX = int.Parse(rectRegexResult.Groups[1].Value);
            int rectLocationY = int.Parse(rectRegexResult.Groups[2].Value);
            int rectWidth = int.Parse(rectRegexResult.Groups[3].Value);
            int rectHeight = int.Parse(rectRegexResult.Groups[4].Value);
            var fiEnum = fieldRegexResult.Groups;
            // 模板字符串 位置 字符宽高
            int fieldLocationX = int.Parse(fieldRegexResult.Groups[1].Value);
            int fieldLocationY = int.Parse(fieldRegexResult.Groups[2].Value);
            int fieldWidth = int.Parse(fieldRegexResult.Groups[3].Value);
            int fieldHeight = int.Parse(fieldRegexResult.Groups[4].Value);
            var fieldName = fieldRegexResult.Groups[5].Value;
            JToken fieldValueToken = "";
            fieldObject.TryGetValue(fieldName, out fieldValueToken);
            if (string.IsNullOrWhiteSpace(fieldValueToken?.ToString()))
            {
                return false;
            }
            string fieldValue = fieldValueToken.ToString();
            if (fieldValue.Length * fieldWidth > rectWidth)
            {
                // 字符串长度大于矩形的最大长度 则文本需要从矩形的Y位置开始渲染
                fieldLocationY = rectLocationY;
                // 获取换行所需的行数
                int lineCount = int.Parse(Math.Ceiling((float)fieldValue.Length / fieldWidth).ToString());
                // 计算换行后的最大行数 * 字符高度 是否大于矩形最大高度
                if(lineCount * fieldHeight > rectHeight)
                {
                    fieldHeight = int.Parse(Math.Floor((float)rectHeight / lineCount).ToString());
                    fieldWidth = fieldHeight;
                }
                // 计算每行应该放多少字符(正确算法)
                int maxCharsPerLine = (int)Math.Ceiling((double)fieldValue.Length / lineCount);
                for (int i = 0; i < lineCount; i++)
                {
                    // 起始位置
                    int start = i * maxCharsPerLine;
                    // 剩余多少字符(核心:保证不越界)
                    int remaining = fieldValue.Length - start;
                    if (remaining <= 0)
                        break;
                    // 本次取几个字符(绝对安全)
                    int take = Math.Min(maxCharsPerLine, remaining);
                    // 截取当前行文本
                    string lineText = fieldValue.Substring(start, take);
                    // 计算新行坐标
                    int newY = fieldLocationY + i * fieldHeight;
                    // 替换拼接
                    concatStr += fieldRegex.Replace(CurrLine, m =>
                        $"^FO{fieldLocationX},{newY}^AJN,{fieldWidth},{fieldHeight}^CI28^FD{lineText}^FS"
                    );
                }
                return true;
            }
            return false;
        }
        #endregion
        [HttpGet]
        [Route("Web/getSysParameter")]
        public object getSysParameter(string HClientID)
        {
            var HValue = oSystemParameter.GetSingleSystemParameter("uni-app_savelogin", ref DBUtility.ClsPub.sExeReturnInfo);
            if (HValue == "3" && HClientID != null)
            {
                DataSet ds = oCN.RunProcReturn("select * from Gy_UserClientIdRelation where HClientID= '" + HClientID + "'", "Gy_UserClientIdRelation");
                if (ds != null && ds.Tables.Count > 0)
                {
                    objJsonResult.code = "1";
                    objJsonResult.count = 1;
                    objJsonResult.Message = "根据设备自动登录";
                    objJsonResult.data = HValue;
                    return objJsonResult;
                }
                else
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "系统参数不存在,请联系管理";
                    objJsonResult.data = 0;
                    return objJsonResult;
                }
            }
            else if (HValue == "2" || HValue == "1")
            {
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "保存成功";
                objJsonResult.data = HValue;
                return objJsonResult;
            }
            else
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "系统参数不存在,请联系管理";
                objJsonResult.data = 0;
                return objJsonResult;
            }
        }
    }
}