333
schangxiang@126.com
2025-09-19 18966e02fb573c7e2bb0c6426ed792b38b910940
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
using Aspose.Cells;
using Newtonsoft.Json;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WIP_BLL;
using WIP_DAL;
using WIP_Models;
using WIP_common;
using System.Reflection;
 
namespace WIP_Print
{
    public class PrintMgr
    {
        public XSSFWorkbook workbook;
        public string strPrintType = "";//打印类型值
        public string namespaceName = "WIP_Print.PrintMgr";
        private readonly string wipSource = WipSource.PrintService;
 
        public PrintMgr(PrintType printType)
        {
            this.strPrintType = Convert.ToInt32(printType).ToString();
        }
 
        /// <summary>
        /// 将要打印的实体对象转为Cell集合对象的JSON字符串
        /// </summary>
        /// <param name="printJson">要打印的实体对象</param>
        /// <param name="tempFileName">模板名称</param>
        /// <returns>Cell集合对象的JSON字符串</returns>
        public virtual string GetJsonDataAsExcelCellModel(string printJson, string tempFileName)
        {
            return "";
        }
 
        /// <summary>
        /// 转模板文件为JSON数据
        /// </summary>
        /// <returns></returns>
        public string TempleteFileToJSON()
        {
            List<ExcelCellModel> dataList = ExcelUtil.GetCellListByTemplateFile(workbook);
            string json_templete_dataList = JsonConvert.SerializeObject(dataList);
            //记录模板的JSON数据
            if (!ExcelUtil.printTypeDict.ContainsKey(strPrintType))
            {
                ExcelUtil.printTypeDict.Add(strPrintType, json_templete_dataList);
            }
            return json_templete_dataList;
        }
 
        /// <summary>
        /// 获取要打印模块的XSSFWorkbook
        /// </summary>
        /// <param name="tempFileName">模板名称</param>
        /// <returns></returns>
        public XSSFWorkbook CreateWorkbook(string tempFileName)
        {
            string filePath = System.Threading.Thread.GetDomain().BaseDirectory + "\\";
            string filePostfix = ".xlsx";
            using (FileStream fs = new FileStream(filePath + @"PrintTemplete\" + tempFileName + filePostfix, FileMode.Open, FileAccess.Read))
            {
                workbook = new XSSFWorkbook(fs);
                fs.Close();
            }
 
            return workbook;
        }
 
        /// <summary>
        /// 初始化模板的JSON数据
        /// </summary>
        /// <param name="tempFileName"></param>
        /// <returns></returns>
        public string InitTempleteFileJsonData(string tempFileName)
        {
            this.workbook = this.CreateWorkbook(tempFileName);
 
            string json_dataList = "";
            //判断是否已经有了模板的JSON数据
            if (ExcelUtil.printTypeDict.ContainsKey(strPrintType))
            {
                json_dataList = ExcelUtil.printTypeDict[strPrintType];
            }
            else
            {
                json_dataList = this.TempleteFileToJSON();
            }
            return json_dataList;
        }
 
        /// <summary>
        /// 打印操作
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="printInfo"></param>
        /// <returns></returns>
        public void Print(string json_cellList, PrintInfo printInfo, PageOrientationType orientation)
        {
            IDictionary<string, object> logDict = new Dictionary<string, object>();
            logDict.Add("json_cellList", json_cellList);
            logDict.Add("printInfo", printInfo);
            logDict.Add("orientation", orientation);
            UdtWip_ExceptionInfo exception = WipLogHelper.GetNewExceptionInfo<IDictionary<string, object>>(namespaceName, "Print", logDict
                , "", printInfo == null ? "" : printInfo.processCardNumber, ExceptionSource.WIPPost, ExceptionLevel.BusinessError, wipSource);
            try
            {
                //创建文件
                List<ExcelSheetModel> sheetModelList = new List<ExcelSheetModel>();
                List<ExcelCellModel> cellModelList = JsonConvert.DeserializeObject<List<ExcelCellModel>>(json_cellList);
                ExcelSheetModel sheetModel = new ExcelSheetModel()
                {
                    sheetName = this.workbook.GetSheetAt(0).SheetName,
                    dataList = cellModelList,
                    sheetType = "",
                };
                sheetModelList.Add(sheetModel);
                byte[] bytes = ExcelUtil.writeExcelToFile(this.workbook, sheetModelList, printInfo.tempName);
 
                //修改为“打印中”
                var result = UpdatePrintStatusToPrinting(printInfo.id);
                if (!result)
                    throw new Exception("更新状态为打印中失败,printInfo.id:" + printInfo.id.ToString());
 
                PrintHelper.PrintExcel(bytes, printInfo.printerName, orientation);
 
                //打印成功
                this.DoByPrintResultSuccess(printInfo);
 
            }
            catch (Exception ex)
            {
                WipLogHelper.GetExceptionInfoForError(ex, ref exception);
                WipLogHelper.WriteExceptionInfo(exception);
 
                //打印失败
                this.DoByPrintResultFailure(printInfo, ex);
            }
        }
 
 
        /// <summary>
        /// 替换打印的占位符
        /// </summary>
        /// <typeparam name="T">要取值的实体对象</typeparam>
        /// <param name="obj">要取值的实体对象值</param>
        /// <param name="json_dataList"></param>
        /// <returns></returns>
        public string Replace<T>(T obj, string json_dataList)
        {
            PropertyInfo[] properArray = typeof(T).GetProperties();
            Object value = null;
            string str = "";
            foreach (var proper in properArray)
            {
                if (proper.GetCustomAttribute(typeof(PrintAttribute), false) != null)
                {
                    value = proper.GetValue(obj, null);
                    if (value == null)
                        value = "";
                    if (proper.PropertyType == typeof(string))
                    {
                        str = WIPCommon.NullToEmpty(value.ToString());
                    }
                    else if (proper.PropertyType == typeof(int?) || proper.PropertyType == typeof(int))
                    {
                        str = WIPCommon.NullToEmpty(value == null ? "" : value.ToString());
                    }
                    else if (proper.PropertyType == typeof(DateTime) || proper.PropertyType == typeof(DateTime?))
                    {
                        str = WIPCommon.FormatDateTime((DateTime?)value);
                    }
                    //替换
                    json_dataList = json_dataList.Replace("[" + proper.Name + "]", str);
                }
            }
            return json_dataList;
        }
 
 
        #region 私有方法
 
        /// <summary>
        /// 打印成功的操作
        /// </summary>
        /// <param name="printInfo"></param>
        private void DoByPrintResultSuccess(PrintInfo printInfo)
        {
            if (printInfo.delFlag == false)
            {
                DoByPrintResult(true, printInfo);
            }
            else
            {//只打印 
                var processCardPrintQueueId = ProcessCardPrintQueueBLL.GetInstance().GetProcessCardPrintQueueId(printInfo);
                if (processCardPrintQueueId > 0)
                {
                    ProcessCardPrintQueueDAL.GetInstance().UpdateProcessCardPrintQueuePrintCount(processCardPrintQueueId);
                }
            }
        }
 
        /// <summary>
        /// 打印失败的操作
        /// </summary>
        /// <param name="printInfo"></param>
        /// <param name="ex"></param>
        private void DoByPrintResultFailure(PrintInfo printInfo, Exception ex)
        {
            if (printInfo.delFlag == false)
            {
                DoByPrintResult(false, printInfo, ex.Message);
            }
        }
 
        /// <summary>
        /// 更新状态为“打印中”
        /// </summary>
        /// <param name="printId"></param>
        /// <returns></returns>
        private bool UpdatePrintStatusToPrinting(int printId)
        {
            var nowTime = DateTime.Now;
            List<PropertyParam> list = new List<PropertyParam>() {
                new PropertyParam(){ PropertyName="lastModifyTime",ObjectValue=nowTime,dbType=SqlDbType.DateTime},
                new PropertyParam() { PropertyName = "printFlag", ObjectValue = Convert.ToInt32(PrintStatus.Printing).ToString(), dbType = SqlDbType.NVarChar, size = 10 }
            };
            list.Add(new PropertyParam()
            {
                IsWhereFilter = true,
                PropertyName = "id",
                ObjectValue = printId,
                dbType = SqlDbType.Int
            });
            var result = DALCommon.UpdateExtend(list, Table.PrintInfo);
            return result;
        }
 
        /// <summary>
        /// 打印结果处理
        /// </summary>
        /// <param name="printResult">打印结果</param>
        /// <param name="printInfo">打印信息</param>
        /// <param name="errMsg">错误信息</param>
        /// <returns></returns>
        private bool DoByPrintResult(bool printResult, PrintInfo printInfo, string errMsg = "")
        {
 
            var retResult = false;//返回结果 
            IDictionary<string, object> logDict = new Dictionary<string, object>();
            logDict.Add("printResult", printResult);
            logDict.Add("printInfo", printInfo);
            UdtWip_ExceptionInfo exception = WipLogHelper.GetNewExceptionInfo<IDictionary<string, object>>(namespaceName, "DoByPrintResult", logDict
                , "", printInfo == null ? "" : printInfo.processCardNumber, ExceptionSource.WIPPost, ExceptionLevel.BusinessError, wipSource);
            try
            {
 
                #region 准备数据
 
                SqlParameter[] parameters_UpdatePrintResult = this.GetSqlParamForUpdatePrintResult(printResult, printInfo, errMsg);
                //是否是后道缓冲区或者抛丸区,正在待打印队列里打印成功操作
                var isPrintProcessCardSuccessByWaitPrintQueue = ValidateIsPrintProcessCardSuccessByWaitPrintQueue(printResult, printInfo);
 
                #endregion
 
                #region 事务处理
 
                using (SqlConnection conn = new SqlConnection(DbHelperSQL.connectionString))
                {
                    conn.Open();
                    using (SqlTransaction trans = conn.BeginTransaction())
                    {
                        TransactionModel transModel = new TransactionModel()
                        {
                            conn = conn,
                            trans = trans
                        };
                        try
                        {
                            var execResult = PrintInfoDAL.GetInstance().UpdatePrintResult(parameters_UpdatePrintResult, transModel);
                            if (execResult != 1)
                            {//返回1代表执行成功,返回-1代表失败
                                throw new Exception("处理打印结果失败,parameters:" + JsonConvert.SerializeObject(parameters_UpdatePrintResult)
                                    + ",execResult:" + execResult.ToString());
                            }
 
                            if (isPrintProcessCardSuccessByWaitPrintQueue)
                            {//执行成功,更新 流转卡队列的打印状态=下料中。
                                var result = ProcessCardPrintQueueDAL.GetInstance().UpdateProcessCardPrintQueueStatus(printInfo.processCardNumber,
                                    PrintStatus.Blanking, "下料中", false, transModel);
                                if (!result)
                                {
                                    throw new Exception("更新 流转卡队列的打印状态=下料中 失败,processCardNumber:" + printInfo.processCardNumber);
                                }
                            }
 
                            trans.Commit();
                            retResult = true;
                        }
                        catch
                        {
                            retResult = false;
                            trans.Rollback();
                            throw;
                        }
                    }
                }
 
                #endregion
 
                #region 打印成功,如果满足条件,要通知WCS料道滚动,下料
 
                this.BufferLayingOffToWCSWithRetry(retResult, isPrintProcessCardSuccessByWaitPrintQueue, printInfo);
 
                #endregion
 
            }
            catch (Exception ex)
            {
                retResult = false;
                WipLogHelper.GetExceptionInfoForError(ex, ref exception);
                WipLogHelper.WriteExceptionInfo(exception);
            }
            return retResult;
        }
 
        /// <summary>
        /// 验证是否是后道缓冲区或者抛丸区,正在待打印队列里打印成功操作
        /// 这里的操作打印成功后需要更新打印状态为下料中,同时要通知立库下料
        /// </summary>
        /// <param name="printResult">打印结果</param>
        /// <param name="printInfo">打印信息</param>
        /// <returns></returns>
        private bool ValidateIsPrintProcessCardSuccessByWaitPrintQueue(bool printResult, PrintInfo printInfo)
        {
            if (printResult && printInfo.delFlag == false &&
                  (printInfo.printType == Convert.ToInt32(PrintType.ProcessCardForBuffer).ToString() ||
                   printInfo.printType == Convert.ToInt32(PrintType.ProcessCardForPostHeatStorageOut).ToString()))
            {
                return true;
            }
            return false;
        }
 
 
        /// <summary>
        /// 打印成功,要通知WCS料道滚动,下料
        /// </summary>
        /// <param name="retResult">事务执行结果</param>
        /// <param name="isPrintProcessCardSuccessByWaitPrintQueue">是否是后道缓冲区或者抛丸区,正在待打印队列里打印成功操作</param>
        private void BufferLayingOffToWCSWithRetry(bool retResult, bool isPrintProcessCardSuccessByWaitPrintQueue, PrintInfo printInfo)
        {
            if (retResult && isPrintProcessCardSuccessByWaitPrintQueue)
            {
                BufferLayingOffParam bufferLayingOffParam = new BufferLayingOffParam()
                {
                    sysCode = SysCode.WIP,
                    equipId = printInfo.printArea,
                    processCardNumber = printInfo.processCardNumber,
                    timestamp = WIPCommon.ForamtCurDateTime()
                };
                MethodReturnResultModel ret = WCS.BufferLayingOffToWCSWithRetry(bufferLayingOffParam);
                if (!ret.IsSuccess)
                {
                    //更新打印状态为“下料错误”
                    var result = ProcessCardPrintQueueDAL.GetInstance().UpdateProcessCardPrintQueueStatus(printInfo.processCardNumber,
                             PrintStatus.BlankFailure, "下料错误:" + ret.ErrMsg, false);
                    if (!result)
                    {
                        throw new Exception("更新 流转卡队列的打印状态=下料中 失败,processCardNumber:" + printInfo.processCardNumber);
                    }
                }
            }
        }
 
        /// <summary>
        /// 获取更新打印结果的sql参数
        /// </summary>
        /// <param name="printResult"></param>
        /// <param name="printInfo"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        private SqlParameter[] GetSqlParamForUpdatePrintResult(bool printResult, PrintInfo printInfo, string errMsg)
        {
            var isPrintProcessCard = "0";//是否是打印流转卡
            var isPrintSuccess = "0";//是否打印成功
            var processCardPrintQueueId = 0;
            if (printInfo.delFlag == false && printInfo.printType == Convert.ToInt32(PrintType.ProcessCardForBuffer).ToString()
                 || printInfo.printType == Convert.ToInt32(PrintType.ProcessCardForPostHeatStorageOut).ToString())
            {
                isPrintProcessCard = "1";
                processCardPrintQueueId = ProcessCardPrintQueueBLL.GetInstance().GetProcessCardPrintQueueId(printInfo);
            }
            if (printResult)
            {//打印成功 
                isPrintSuccess = "1";
            }
 
            SqlParameter[] parameters = { 
                  new SqlParameter("@printResult",SqlDbType.VarChar,2),
                  new SqlParameter("@printInfoId",SqlDbType.Int),
                  new SqlParameter("@printErrMsg",SqlDbType.NVarChar,100),
                  new SqlParameter("@isPrintProcessCard",SqlDbType.VarChar,2),
                  new SqlParameter("@processCardPrintQueueId",SqlDbType.Int),
                  new SqlParameter("@printTime",SqlDbType.DateTime),
                  new SqlParameter("@processCardNumber",SqlDbType.NVarChar,50)
                };
            parameters[0].Value = isPrintSuccess;
            parameters[1].Value = printInfo.id;
            parameters[2].Value = errMsg;
            parameters[3].Value = isPrintProcessCard;
            parameters[4].Value = processCardPrintQueueId;
            parameters[5].Value = DateTime.Now;
            parameters[6].Value = printInfo.processCardNumber;
            return parameters;
        }
 
 
 
        #endregion
 
    }
}