严智鑫
2025-11-13 945bc394f40d8af1072a53da9a94f24207124e6d
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
package com.northglass.service.countmachine;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
 
import com.northglass.constants.StateConstants.ConnectState;
import com.northglass.constants.StateConstants.CountMachineState;
import com.northglass.constants.StateConstants.CountMachineTaskState;
import com.northglass.constants.StateConstants.RawPackageTxtState;
import com.northglass.constants.StateConstants.ShelfTaskState;
import com.northglass.entity.CountMachine;
import com.northglass.entity.CountMachineTask;
import com.northglass.entity.Glass;
import com.northglass.entity.OptPattern;
import com.northglass.entity.RawPackageTxt;
import com.northglass.listener.CountMachineClientListener;
import com.northglass.listener.CountMachineServerListener;
import com.northglass.listener.ShelfClientListener;
import com.northglass.repository.CountMachineDao;
import com.northglass.repository.CountMachineTaskDao;
import com.northglass.repository.GlassDao;
import com.northglass.repository.OptPatternDao;
import com.northglass.repository.RawPackageTxtDao;
import com.northglass.service.message.CountMachineMessageProcessor;
import com.northglass.web.gaoliwei.GaoliweiController;
 
@Component
@Transactional
public class CountMachineService {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(CountMachineService.class);
    
    @Autowired
    private CountMachineDao countMachineDao;
    
    @Autowired
    private CountMachineTaskDao countMachineTaskDao;
    
    @Autowired
    private CountMachineMessageProcessor messageProcessor;
    
    @Autowired
    private GlassDao glassDao;
    
    @Autowired
    private RawPackageTxtDao rawPackageTxtDao;
    
    @Autowired
    private OptPatternDao optPatternDao;
    
    public void setConnectState(CountMachine countMachine, String connectState) {
        countMachine.setConnectState(connectState);
        countMachine.setModifyTime(new Date());
        countMachineDao.save(countMachine);
    }
  
      
    public CountMachine getById(Long id) {
        return countMachineDao.findOne(id);
    }
    
  //根据ID获得呼叫机对象
    
    public List<CountMachine> getAll() {
        return countMachineDao.findAll();
    }
    
    public void connect() {
        LOGGER.debug("> Start connect");
        
        List<CountMachine> machineList = countMachineDao.findAll();
       
        // 若监听线程为空,则新建监听线程
        for (CountMachine countMachine : machineList) {
            if (countMachine.getServerConnection().getThread() == null) {
                LOGGER.debug("创建新的下片机【" + countMachine.getNumber() + "】监听线程!");
                Thread thread = new Thread(new CountMachineClientListener(countMachine, this));
                thread.start();
                
                setConnectState(countMachine, ConnectState.CONNECTING);
                countMachine.getServerConnection().setThread(thread);
                LOGGER.debug("> End connect");
            }
        }
    }
    
    public void resetState() {
        List<CountMachine> machineList = countMachineDao.findAll();
        
        for (CountMachine countMachine : machineList) {
            countMachine.setConnectState(ConnectState.NO_CONNECT);
            countMachine.setState(CountMachineState.STOPPED);
        }
        
        countMachineDao.save(machineList);
      
    }
    
    public String processMessage(String sendMessageHex, CountMachine countMachine) {
        return messageProcessor.generateReturnMessage(sendMessageHex, countMachine);
    }
    
    public CountMachine saveCountMachine(CountMachine countMachine) {
        return countMachineDao.save(countMachine);
    }
    
    public CountMachineTask saveCountMachineTask(CountMachineTask countMachineTask) {
        return countMachineTaskDao.save(countMachineTask);
    }
    
    public List<CountMachineTask> findTask(CountMachine countMachine) {
        return countMachineTaskDao.findWaitingTasksByCountMachine(countMachine.getId());
    }
    
    public List<CountMachineTask> findInWorkTask(CountMachine countMachine) {
        return countMachineTaskDao.findInWorkTaskByCountMachine(countMachine.getId());
    }
    
    public Map<String, Object> showAllGlass(){
        Map<String, Object> param=new HashMap<String, Object>();
        RawPackageTxt rawPackageTxt = rawPackageTxtDao.findCutFinishByGroup("1");
        if (rawPackageTxt == null) {
             rawPackageTxt = rawPackageTxtDao.findAcceptedByGroup("1");
        }
        List<Glass> allGlasses = new ArrayList<Glass>();
        if(rawPackageTxt!=null){
            allGlasses=glassDao.findByBatch(rawPackageTxt.getTxt_name());
            int sum =0;
            int finishoieces =0;
            int warning =0;
            if (allGlasses.size() > 0) {
                for(Glass glass:allGlasses){
                    sum +=glass.getPieces();
                    finishoieces += glass.getCompletePieces();
                    warning += glass.getDamagePieces();
                }
                 param.put("sum", sum);
                 param.put("finishoieces", finishoieces);
                 param.put("warning", warning);
            }
            double temp = 100;
            //查找最小误差值allGlasses
            for (int i = 0; i < allGlasses.size(); i++) {
                Glass glass1 = allGlasses.get(i);
                for (int j = i+1; j < allGlasses.size(); j++) {
                    Glass glass2 = allGlasses.get(j);
                    if ((glass1.getWidth() == glass2.getWidth()&&glass1.getLength() == glass2.getLength())
                            ||(glass1.getWidth() == glass2.getLength() && glass1.getLength() == glass2.getWidth())) {
                        break;
                    }
                    double s = Math.abs(glass1.getLength() - glass2.getLength()); 
                    if (Math.abs(glass1.getWidth() - glass2.getWidth()) > s) {
                        s = Math.abs(glass1.getWidth() - glass2.getWidth());
                    }
                    if (temp>s) {
                        temp = s;
                    }
                }
            }
            param.put("temp", temp);
            
            StringBuffer html = new StringBuffer();
            List<Glass> glasses = glassDao.findByBatch(rawPackageTxt.getTxt_name());
 
            if (glasses.size() > 0) {
                for (Glass glass : glasses) {
                    if (glass.getPieces() == glass.getCompletePieces()) {
                        html.append("<tr>");
                    } else {
                        html.append("<tr style='color:red'>");
                    }
                    html.append("<td>").append(glass.getId()).append("</td>");
                    html.append("<td>").append(glass.getManufacture_batch()).append("</td>");
                    html.append("<td>").append(glass.getLength()).append("</td>");
                    html.append("<td>").append(glass.getWidth()).append("</td>");
                    html.append("<td>").append(glass.getThickness()).append("</td>");
                    html.append("<td>").append(glass.getColor()).append("</td>");
                    html.append("<td>").append(glass.getPieces()).append("</td>");
                    html.append("<td>").append(glass.getCompletePieces()).append("</td>");
                    html.append("<td>").append(glass.getDamagePieces()).append("</td>");
                    //html.append("<td>").append(glass.getSendState()).append("</td>");
                    //html.append("<td>").append(glass.getSendStates()).append("</td>");
                    html.append("</tr>");
                }
            }
            param.put("allGlasseshtml", html.toString());
        }
        param.put("allGlasses", allGlasses);
        return param;
    }
    
    public Long clearProcessGlass(Long machineId){
        List<CountMachineTask> waitingTasks = countMachineTaskDao.findWaitingTasksByCountMachine(machineId);
        if(waitingTasks.size()>0){
            for(CountMachineTask countMachineTask : waitingTasks){
                countMachineTask.setState(CountMachineTaskState.COMPLETED);
                countMachineTaskDao.save(countMachineTask);
            }
        }
        return machineId;
    }
    
//    public void exportAllGlass(HttpServletResponse response) {
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
//        String fileName = "report_" + format.format(new Date()) + ".xls";
//        response.setContentType("application/vnd.ms-excel");
//        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
//
//        ByteArrayOutputStream byteOut = generateByteArrayOutputStream();
//        InputStream input = new ByteArrayInputStream(byteOut.toByteArray());
//        byte[] buffer = new byte[1024];
//        try {
//            OutputStream outputStream = response.getOutputStream();
//            int len = 0;
//            while ((len = input.read(buffer)) != -1) {
//                outputStream.write(buffer, 0, len);
//            }
//            outputStream.flush();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
    
    @SuppressWarnings("resource")
    public void exportAllGlass(String name) {
//        RawPackageTxt rawPackageTxt = rawPackageTxtDao.findCutFinishByGroup("1");
//        String s="0000";
//        if (rawPackageTxt !=null) {
//            s=rawPackageTxt.getTxt_name();
//        }
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
//        String fileName = "report_" + format.format(new Date()) + ".xls";
        String fileName = "report_" + name + ".xls";
//        String path = "C:\\Users\\northglass\\Desktop\\完工报告";
        String path1 = "\\\\192.168.0.200\\完成计划";
        File file = new File(path1);
        if (file.exists()) {
            file.deleteOnExit();
            file = new File(path1);
        }
        ByteArrayOutputStream byteOut = generateByteArrayOutputStream(name);
        InputStream input = new ByteArrayInputStream(byteOut.toByteArray());
        byte[] buffer = new byte[1024];
        
        try {
            OutputStream outputStream = null;
            outputStream = new FileOutputStream(file.toString() + "\\"+ fileName);
            int len = 0;
            while ((len = input.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    }
    
    public ByteArrayOutputStream generateByteArrayOutputStream(String name) {
        // 创建Excel文件的sheet
        HSSFWorkbook workBook = new HSSFWorkbook();
        HSSFSheet sheet = workBook.createSheet("完工信息");
        HSSFRow row = sheet.createRow(0);
        // 设置表头
        row.createCell(0).setCellValue("ID");
        row.createCell(1).setCellValue("任务号");
        row.createCell(2).setCellValue("流程卡号");
        row.createCell(3).setCellValue("条码号");
//        row.createCell(4).setCellValue("架号");
//        row.createCell(5).setCellValue("客户简称");
        row.createCell(4).setCellValue("长度");
        row.createCell(5).setCellValue("宽度");
        row.createCell(6).setCellValue("厚度");
        row.createCell(7).setCellValue("颜色");
        row.createCell(8).setCellValue("数量");
        row.createCell(9).setCellValue("磨边数量");
        row.createCell(10).setCellValue("未磨边数量");
        row.createCell(11).setCellValue("破损数量");
        
        // 获取仓库中所有使用中的料架
        RawPackageTxt rawPackageTxt = rawPackageTxtDao.findByTxtName(name);
        if(rawPackageTxt != null){
            List<Glass> allGlasses=glassDao.findByBatch(rawPackageTxt.getTxt_name());
            if (allGlasses.size() != 0) {
                for (Glass glass : allGlasses) {
                    HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
                    dataRow.createCell(0).setCellValue(glass.getId());
                    dataRow.createCell(1).setCellValue(glass.getManufacture_batch());
                    dataRow.createCell(2).setCellValue(glass.getApart_id());
                    dataRow.createCell(3).setCellValue(glass.getApplication());
//                    if (!glass.getArrangeStatu().equals("0")) {
//                        dataRow.createCell(4).setCellValue(glass.getArrangeStatu());
//                    }
//                    dataRow.createCell(5).setCellValue(glass.getCustomer());
                    dataRow.createCell(4).setCellValue(glass.getLength());
                    dataRow.createCell(5).setCellValue(glass.getWidth());
                    dataRow.createCell(6).setCellValue(glass.getThickness());
                    dataRow.createCell(7).setCellValue(glass.getColor());
                    dataRow.createCell(8).setCellValue(glass.getPieces());
                    dataRow.createCell(9).setCellValue(glass.getPieces());
                    dataRow.createCell(10).setCellValue(0);
                    dataRow.createCell(11).setCellValue(glass.getDamagePieces());
                }
            }
        }
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        try {
            workBook.write(byteOut);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteOut;
 
    }
 
 
    public String completetask() {
        //打印报表
        //\\192.168.0.200\\完成计划\\完成计划 (192.168.0.200)
        //磨边机结束任务
        GaoliweiController.setButton("1"); 
        GaoliweiController.setButton1("1");
         RawPackageTxt txt = rawPackageTxtDao.findCutFinishByGroup("1");
         countMachineTaskDao.deleteAll();
//         if (txt==null) {
//             txt = rawPackageTxtDao.findAcceptedByGroup("1");
//        }
         if (txt!=null) {
            txt.setStatus(RawPackageTxtState.COMPLETED);
            //exportAllGlass(txt.getTxt_name());
            return "任务"+txt.getTxt_name()+"完成";
        }
         RawPackageTxt txts = rawPackageTxtDao.findCutFinishByGroup("1");
         if (txts !=null) {
             return "任务"+txts.getTxt_name()+"切割任务还没有完成,不能完成下片任务";
        }
         return "抱歉,没有可以完成的任务";
    }
 
 
    @SuppressWarnings("resource")
    public void exportUseGlass(String optname) {
        String fileName = "使用原片数量_" + optname + ".xls";
//        String path = "C:\\Users\\northglass\\Desktop\\完工报告";
        String path1 = "\\\\192.168.0.200\\原片使用量";
        File file = new File(path1);
        if (file.exists()) {
            file.deleteOnExit();
            file = new File(path1);
        }
        ByteArrayOutputStream byteOut = getUseStream(optname);
        InputStream input = new ByteArrayInputStream(byteOut.toByteArray());
        byte[] buffer = new byte[1024];
        
        try {
            OutputStream outputStream = null;
            outputStream = new FileOutputStream(file.toString() + "\\"+ fileName);
            int len = 0;
            while ((len = input.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        
    }
    
    public ByteArrayOutputStream getUseStream(String optname) {
        // 创建Excel文件的sheet
        HSSFWorkbook workBook = new HSSFWorkbook();
        HSSFSheet sheet = workBook.createSheet("使用原片信息");
        HSSFRow row = sheet.createRow(0);
        // 设置表头
        row.createCell(0).setCellValue("ID");
        row.createCell(1).setCellValue("任务号");
        row.createCell(2).setCellValue("厚度");
        row.createCell(3).setCellValue("颜色膜系");
        row.createCell(4).setCellValue("宽度");
        row.createCell(5).setCellValue("高度");
        row.createCell(6).setCellValue("数量");
        
        List<OptPattern> optPatterns = new ArrayList<OptPattern>();
        List<OptPattern> optPatternes = optPatternDao.findOptPatternByBatchNumber(optname);
        if (optPatternes.size()>0) {
            for (OptPattern optPattern:optPatternes) {
                if (optPatterns.size()>0) {
                    for (int i=0;i<optPatterns.size();i++) {
                        OptPattern opt = optPatterns.get(i);
                        if (opt.getWidth()==optPattern.getWidth() && opt.getHeight() == optPattern.getHeight()) {
                            opt.setCompletedPieces(opt.getCompletedPieces()+optPattern.getPieces());
                            break;
                        }
                        if (i == optPatterns.size()-1) {
                            optPattern.setCompletedPieces(optPattern.getPieces());
                            optPatternDao.save(optPattern);
                            optPatterns.add(optPattern);
                            break;
                        }
                    }
                    
                }else {
                    optPattern.setCompletedPieces(optPattern.getPieces());
                    optPatternDao.save(optPattern);
                    optPatterns.add(optPattern);
                }
            }
        }
        int s=1;
        for (OptPattern ooPattern :optPatterns) {
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
            dataRow.createCell(0).setCellValue(s++);
            dataRow.createCell(1).setCellValue(optname);
            dataRow.createCell(2).setCellValue(ooPattern.getGlassThickness());
            dataRow.createCell(3).setCellValue(ooPattern.getColor());
            dataRow.createCell(4).setCellValue(ooPattern.getWidth());
            dataRow.createCell(5).setCellValue(ooPattern.getHeight());
            dataRow.createCell(6).setCellValue(ooPattern.getCompletedPieces());
            ooPattern.setCompletedPieces(ooPattern.getPieces());
            optPatternDao.save(ooPattern);
        }
//        RawPackageTxt rawPackageTxt = rawPackageTxtDao.findByTxtName(optname);
//        
//        List<RawPackage> rawPackages = rawPackageTxt.getRawPackagees();
//        List<RawPackage> rawPackagees = new ArrayList<RawPackage>();// 将新建对象放入,防止数据改变后同步到数据库
//
//        for (int i = 0; i < rawPackages.size(); i++) {
//            RawPackage rawPackage = rawPackages.get(i);
//            RawPackage raw = new RawPackage(rawPackage.getGlassId(), rawPackage.getPieces(),
//                    rawPackage.getState(), rawPackage.getWidth(), rawPackage.getHeight(),
//                    rawPackage.getThickness(), rawPackage.getColor(), rawPackage.getLeftPieces(),
//                    rawPackage.getManufacturer(), rawPackage.getComment(), rawPackage.getCreateTime());
//            rawPackagees.add(i, raw);
//        }
        
//        for (RawPackage rawPackage : rawPackagees) {
//            // 初始化当前规格原片需要切割的片数
//            int pieces = 0;
//            // 拿到当前需要领取的opt下所有的pattern
//            List<OptPattern> patterns = optPatternDao.findById(rawPackageTxt.getId());
//            // 找到当前需要的原片规格相同的pattern,剩余多少片没切
//            if (patterns.size() != 0) {
//                for (OptPattern pa : patterns) {
//                    if (rawPackage.getWidth() == pa.getWidth() && rawPackage.getHeight() == pa.getHeight()
//                            && rawPackage.getThickness() == pa.getGlassThickness()
//                            && rawPackage.getColor().equals(pa.getColor())
//                            ) {
//                        // 规格相同且没完成
//                        // 计算当前pattern剩余多少片没切
//                        int needPiece = pa.getPieces();
//                        pieces += needPiece;
//                    }
//                }
//            }
//            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
//            dataRow.createCell(0).setCellValue(s++);
//            dataRow.createCell(1).setCellValue(optname);
//            dataRow.createCell(2).setCellValue(rawPackage.getThickness());
//            dataRow.createCell(3).setCellValue(rawPackage.getColor());
//            dataRow.createCell(4).setCellValue(rawPackage.getWidth());
//            dataRow.createCell(5).setCellValue(rawPackage.getHeight());
//            dataRow.createCell(6).setCellValue(pieces);
//            
//        }
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        try {
            workBook.write(byteOut);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteOut;
    }
 
 
    public String getmessage(CountMachine machineClient) {
        List<CountMachineTask> tasks = this.findTask(machineClient);
        LOGGER.debug("daxiao:"+tasks.size());
        if (tasks.size()>0) {
            CountMachineTask task = tasks.get(0);
            //machineService.saveCountMachineTask(task);
            task.setState("已完成");
            saveCountMachineTask(task);
            LOGGER.debug("daxiao1");
            return task.getGlass().tojsonString() ;
        }else {
            return "0000";
        }
    }
 
 
    public void addTask() {
         CountMachineTask task = new CountMachineTask(1688,
                    1200,
                    "5",
                    glassDao.findOne(5L),
                    countMachineDao.findOne(1L), 
                    rawPackageTxtDao.findOne(69L),
                    ShelfTaskState.WAITING, new Date());
            task.setRank("2");
            countMachineTaskDao.save(task);
    }
 
 
    public List<CountMachineTask> getByWaiting(Long countMachineId){
          return countMachineTaskDao.findWaitingTasksByCountMachine(countMachineId);
      }
}