huang
2025-06-12 e206ea8f7dbb655c0d8868996dae8ff1ff5ed11a
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
package com.mes.md.service.impl;
 
import cn.smallbun.screw.core.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.mes.md.entity.KBBTJPDrawingBP;
import com.mes.md.entity.KBBTProgramsOperationLogBP;
import com.mes.md.entity.TaskingLog;
import com.mes.md.mapper.KBBTJPDrawingBPMapper;
import com.mes.md.mapper.KBBTProgramsOperationLogBPMapper;
import com.mes.md.mapper.TaskingLogMapper;
import com.mes.md.service.TaskingLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wu
 * @since 2024-08-28
 */
@Slf4j
@Service
public class TaskingLogServiceImpl extends MPJBaseServiceImpl<TaskingLogMapper, TaskingLog> implements TaskingLogService {
 
    @Autowired
    KBBTProgramsOperationLogBPMapper kBBTProgramsOperationLogBPMapper;
    @Autowired
    KBBTJPDrawingBPMapper kBBTJPDrawingBPMapper;
 
    @Override
    public List<Map> selectMechanicalReport(int dayCount, Date startDate, Date endDate, String taskType, String operationRecord, String lineType) {
        try {
            // 构建查询条件
            QueryWrapper<TaskingLog> taskingWrapper = new QueryWrapper<>();
 
            // 添加完工状态过滤
            taskingWrapper.eq("work_state", "完工");
 
            // 时间范围处理
            if (startDate != null && endDate != null) {
                taskingWrapper.ge("operation_record_time", startDate)
                        .le("operation_record_time", endDate);
            } else if (dayCount > 0) {
                // 如果没有时间范围,使用默认的dayCount
                Calendar cal = Calendar.getInstance();
                cal.setTime(new Date());
                cal.set(Calendar.HOUR_OF_DAY, 0);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
                cal.set(Calendar.MILLISECOND, 0);
                cal.add(Calendar.DATE, 1 - dayCount);
                Date defaultStartDate = cal.getTime();
                Date defaultEndDate = new Date();
                
                taskingWrapper.ge("operation_record_time", defaultStartDate)
                        .le("operation_record_time", defaultEndDate);
            }
 
            // 添加可选条件
            if (taskType != null && !taskType.isEmpty()) {
                taskingWrapper.eq("task_type", taskType);
            }
            if (operationRecord != null && !operationRecord.isEmpty()) {
                taskingWrapper.like("operation_record", operationRecord);
            }
            if (lineType != null && !lineType.isEmpty()) {
                taskingWrapper.apply("operation_record REGEXP '.*[^0-9]" + lineType + "$'");
            }
            
            // 按时间排序(降序)
            //taskingWrapper.orderByDesc("operation_record_time");
            //(升序)
            taskingWrapper.orderByAsc("operation_record_time");
            // 先按sortOrder排序,再按时间排序
            //taskingWrapper.orderByAsc("sort_order", "operation_record_time");
            
            // 执行查询
            List<Map<String, Object>> taskingList = baseMapper.selectMaps(taskingWrapper);
 
            // 直接返回查询结果
            return new ArrayList<>(taskingList);
        } catch (Exception e) {
            log.error("查询异常", e);
            throw e;
        }
    }
 
    public List<TaskingLog> findTaskingLog(){
        return new ArrayList<TaskingLog>();
    }
 
    /**
     * 查询 dayCount 天  完工数量-分线路
     */
    @Override
    public List<Map> selectTaskingLog(int dayCount) {
        Calendar cal = Calendar.getInstance();
        //设置当前时间
        cal.setTime(new Date());
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.DATE, 1-dayCount);
        Date startDate = cal.getTime();
 
        QueryWrapper<KBBTJPDrawingBP> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("CAST(PlanDate AS DATE) AS CreateDate,isNull(sum(task_quantity),0) as task_quantity_sum")
                .gt("PlanDate",startDate).groupBy("CAST(PlanDate AS DATE)")
                .orderByAsc("CAST(PlanDate AS DATE)");
        List<Map> list=kBBTJPDrawingBPMapper.selectMaps((QueryWrapper)queryWrapper);
 
        List<Map<String, Object>> listTasking1 = baseMapper.selectMaps(new QueryWrapper<TaskingLog>()
                .select("task_type, operation_record, operation_mode, DATE_FORMAT(operation_record_time, '%Y-%m-%d') as operation_record_time, count(*) as count")
                .eq("operation_record", "旋转1")
                .eq("operation_mode", "结束")
                .gt("operation_record_time", startDate)
                .groupBy("task_type", "operation_record", "operation_mode", "DATE_FORMAT(operation_record_time, '%Y-%m-%d')")
                .orderByAsc("DATE_FORMAT(operation_record_time, '%Y-%m-%d')"));
        List<Map<String, Object>> listTasking2 = baseMapper.selectMaps(new QueryWrapper<TaskingLog>()
                .select("task_type,operation_record,operation_mode,DATE_FORMAT(operation_record_time, '%Y-%m-%d') as operation_record_time,count(1) as count")
                .eq("operation_record", "旋转2")
                .eq("operation_mode", "结束")
                .gt("operation_record_time", startDate)
                .groupBy("task_type", "operation_record", "operation_mode", "DATE_FORMAT(operation_record_time, '%Y-%m-%d')")
                .orderByAsc("DATE_FORMAT(operation_record_time, '%Y-%m-%d')"));
 
        //标准上片记录
        List<Map<String, Object>> loadTaskingList1 = baseMapper.selectMaps(new QueryWrapper<TaskingLog>()
                .select("task_type, operation_record, operation_mode, DATE_FORMAT(operation_record_time, '%Y-%m-%d') as operation_record_time, count(*) as count")
                .eq("task_type", "标准")
                .eq("operation_record", "上片1")
                .eq("operation_mode", "结束")
                .gt("operation_record_time", startDate)
                .groupBy("task_type", "operation_record", "operation_mode", "DATE_FORMAT(operation_record_time, '%Y-%m-%d')")
                .orderByAsc("DATE_FORMAT(operation_record_time, '%Y-%m-%d')"));
        List<Map<String, Object>> loadTaskingList2 = baseMapper.selectMaps(new QueryWrapper<TaskingLog>()
                .select("task_type, operation_record, operation_mode, DATE_FORMAT(operation_record_time, '%Y-%m-%d') as operation_record_time, count(*) as count")
                .eq("task_type", "标准")
                .eq("operation_record", "上片2")
                .eq("operation_mode", "结束")
                .gt("operation_record_time", startDate)
                .groupBy("task_type", "operation_record", "operation_mode", "DATE_FORMAT(operation_record_time, '%Y-%m-%d')")
                .orderByAsc("DATE_FORMAT(operation_record_time, '%Y-%m-%d')"));
 
        // 存储每条线路的数据
        Map<String, Map<String, Integer>> lineDataMap = new HashMap<>();
        lineDataMap.put("line1", new HashMap<>());
        lineDataMap.put("line2", new HashMap<>());
 
        // 处理第一条线路数据
        // 处理旋转1结束记录
        for (Map<String, Object> map : listTasking1) {
            String date = map.get("operation_record_time").toString();
            int count = Integer.parseInt(map.get("count").toString());
            Map<String, Integer> line1Map = lineDataMap.get("line1");
            line1Map.put(date, line1Map.getOrDefault(date, 0) + count);
        }
        // 处理线路1上片记录
        for (Map<String, Object> map : loadTaskingList1) {
            String date = map.get("operation_record_time").toString();
            int count = Integer.parseInt(map.get("count").toString());
            Map<String, Integer> line1Map = lineDataMap.get("line1");
            line1Map.put(date, line1Map.getOrDefault(date, 0) + count);
        }
 
        // 处理第二条线路数据
        // 处理旋转2结束记录
        for (Map<String, Object> map : listTasking2) {
            String date = map.get("operation_record_time").toString();
            int count = Integer.parseInt(map.get("count").toString());
            Map<String, Integer> line2Map = lineDataMap.get("line2");
            line2Map.put(date, line2Map.getOrDefault(date, 0) + count);
        }
        // 处理线路2上片记录
        for (Map<String, Object> map : loadTaskingList2) {
            String date = map.get("operation_record_time").toString();
            int count = Integer.parseInt(map.get("count").toString());
            Map<String, Integer> line2Map = lineDataMap.get("line2");
            line2Map.put(date, line2Map.getOrDefault(date, 0) + count);
        }
 
 
        //log.info("客户表计划量:{},{},{}",list,listTasking1,listTasking2);
        List<Map> Result=new ArrayList<>();
        for (int i=0;i<dayCount;i++){
            Date thisdate=cal.getTime();
            cal.add(Calendar.DATE, 1);
            Map thisMap=new HashMap<>();
 
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = sdf.format(thisdate);
            thisMap.put("date",dateString);
            
            // 获取一线数据
            thisMap.put("line1", lineDataMap.get("line1").getOrDefault(dateString, 0));
            
            // 获取二线数据
            thisMap.put("line2", lineDataMap.get("line2").getOrDefault(dateString, 0));
 
            if (list.size()>0 && list.get(0).get("CreateDate").toString().equals(dateString)){
                thisMap.put("plan",list.get(0).get("task_quantity_sum"));
                list.remove(0);
            }else{
                thisMap.put("plan",0);
            }
            Result.add(thisMap);
        }
 
        return Result;
    }
    /**
     * 回传报工数据+ 设备玻璃过片记录给 九牧
     */
    @Override
    public Integer reportTaskingLog() {
        TaskingLog updateTaskingLog = new TaskingLog();
        updateTaskingLog.setIsSend(1);
        baseMapper.update(updateTaskingLog, new QueryWrapper<TaskingLog>().lambda().
                eq(TaskingLog::getIsSend, 0));
        List<TaskingLog> listTasking = baseMapper.selectList(new QueryWrapper<TaskingLog>().lambda()
                .eq(TaskingLog::getIsSend, 1));
        // 判端是否为空
        if (CollectionUtils.isNotEmpty(listTasking)) {
            // 进行拆解封装
            List<KBBTProgramsOperationLogBP> report = listTasking.stream().map(item -> {
                KBBTProgramsOperationLogBP newData = new KBBTProgramsOperationLogBP();
                newData.setGlassId(item.getGlassId());
                newData.setState(item.getState());
                newData.setWorkState(item.getWorkState());
                newData.setGlassState(item.getGlassState());
                newData.setState(item.getState());
                newData.setScanId(item.getScanId());
                newData.setProgramId(item.getProgramId());
                newData.setBatchNumber(item.getBatchNumber() == null ? "" : item.getBatchNumber());
                newData.setLineConfigurationId(item.getLineConfigurationId());
                newData.setTaskType(item.getTaskType());
                newData.setLength(item.getLength());
                newData.setWidth(item.getWidth());
                newData.setThickness(item.getThickness());
                newData.setDrawingMarking(item.getDrawingMarking());
                newData.setIsSilkScreen(item.getIsSilkScreen());
                newData.setIsWorking(1);
                newData.setSilkScreenX(item.getSilkScreenX());
                newData.setSilkScreenY(item.getSilkScreenY());
                newData.setR_1_1(item.getR_1_1());
                newData.setR_1_2(item.getR_1_2());
                newData.setR_2_1(item.getR_2_1());
                newData.setR_2_2(item.getR_2_2());
                newData.setR_3_1(item.getR_3_1());
                newData.setR_3_2(item.getR_3_2());
                newData.setR_4_1(item.getR_4_1());
                newData.setR_4_2(item.getR_4_2());
                newData.setSilkScreenY(item.getSilkScreenY());
                newData.setOperationRecord(item.getOperationRecord());
                newData.setOperationMode(item.getOperationMode());
                newData.setOperationRecordTime(item.getOperationRecordTime());
                newData.setCreateDate(new Date());
                kBBTProgramsOperationLogBPMapper.insert(newData);
                return newData;
            }).collect(Collectors.toList());
            updateTaskingLog.setIsSend(2);
 
            int successfulCount = baseMapper.update(updateTaskingLog, new QueryWrapper<TaskingLog>().lambda().
                    eq(TaskingLog::getIsSend, 1));
            log.info("未提交的数量:{}   提交数量: {}   成功数量:{}", listTasking.size(), report.size(), successfulCount);
            return successfulCount;
        }
        return 0;
    }
 
 
    /**
     * 查询单小时产量
     * @param dayCount 查询天数
     * @return Map 包含每天两条线的平均小时产量
     */
    @Override
    public Map<String, Object> findHourlyOutput(int dayCount) {
        try {
            // 计算开始时间
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            cal.add(Calendar.DATE, -dayCount + 1);
            Date startDate = cal.getTime();
 
            // 查询一线数据,按天分组统计总产量和工作小时数
            QueryWrapper<TaskingLog> line1Query = new QueryWrapper<>();
            line1Query.select(
                    "DATE_FORMAT(operation_record_time, '%Y-%m-%d') as date",
                    "COUNT(*) as total_count",
                    "COUNT(DISTINCT DATE_FORMAT(operation_record_time, '%H')) as working_hours"
                )
                .eq("operation_record", "旋转1")
                .eq("operation_mode", "结束")
                .ge("operation_record_time", startDate)
                .groupBy("DATE_FORMAT(operation_record_time, '%Y-%m-%d')")
                .orderByAsc("date");
            List<Map<String, Object>> line1Results = baseMapper.selectMaps(line1Query);
 
            // 查询二线数据,按天分组统计总产量和工作小时数
            QueryWrapper<TaskingLog> line2Query = new QueryWrapper<>();
            line2Query.select(
                    "DATE_FORMAT(operation_record_time, '%Y-%m-%d') as date",
                    "COUNT(*) as total_count",
                    "COUNT(DISTINCT DATE_FORMAT(operation_record_time, '%H')) as working_hours"
                )
                .eq("operation_record", "旋转2")
                .eq("operation_mode", "结束")
                .ge("operation_record_time", startDate)
                .groupBy("DATE_FORMAT(operation_record_time, '%Y-%m-%d')")
                .orderByAsc("date");
            List<Map<String, Object>> line2Results = baseMapper.selectMaps(line2Query);
 
            // 合并结果
            Map<String, Object> result = new HashMap<>();
            Map<String, Map<String, Object>> dailyStats = new HashMap<>();
 
            // 处理一线数据
            for (Map<String, Object> line1Data : line1Results) {
                String date = (String) line1Data.get("date");
                int totalCount = ((Number) line1Data.get("total_count")).intValue();
                int workingHours = ((Number) line1Data.get("working_hours")).intValue();
                
                Map<String, Object> dailyData = new HashMap<>();
                dailyData.put("date", date);
                dailyData.put("line1Count", totalCount);
                dailyData.put("line1Hours", workingHours);
                dailyData.put("line1HourlyAvg", workingHours > 0 ? totalCount / workingHours : 0);
                
                dailyStats.put(date, dailyData);
            }
 
            // 处理二线数据
            for (Map<String, Object> line2Data : line2Results) {
                String date = (String) line2Data.get("date");
                int totalCount = ((Number) line2Data.get("total_count")).intValue();
                int workingHours = ((Number) line2Data.get("working_hours")).intValue();
                
                Map<String, Object> dailyData = dailyStats.computeIfAbsent(date, k -> {
                    Map<String, Object> newData = new HashMap<>();
                    newData.put("date", date);
                    return newData;
                });
                
                dailyData.put("line2Count", totalCount);
                dailyData.put("line2Hours", workingHours);
                dailyData.put("line2HourlyAvg", workingHours > 0 ? totalCount / workingHours : 0);
            }
 
            // 转换为最终的返回格式
            List<Map<String, Object>> finalStats = new ArrayList<>(dailyStats.values());
 
            // 按日期排序
            finalStats.sort((a, b) -> ((String)a.get("date")).compareTo((String)b.get("date")));
 
            result.put("dailyStats", finalStats);
            return result;
        } catch (Exception e) {
            log.error("计算单小时产量失败", e);
            throw new RuntimeException("计算单小时产量失败: " + e.getMessage());
        }
    }
 
    /**
     * 查询库位数据
     * 按库位统计:
     * - 标准工艺:统计上片1和上片2的记录
     * - 定制工艺:统计旋转1和旋转2的记录
     */
    @Override
    public List<Map<String, Object>> selectWareHouse(int dayCount) {
        try {
            // 计算开始时间
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            cal.add(Calendar.DATE, -dayCount + 1);  
            Date startDate = cal.getTime();
            
            // 使用QueryWrapper构建查询
            QueryWrapper<TaskingLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.select(
                    "DATE_FORMAT(operation_record_time, '%Y-%m-%d') as date",
                    "warehouse",
                    "COUNT(*) as count"
                )
                .and(wrapper -> wrapper
                    .and(w -> w
                        .eq("task_type", "标准")
                        .in("operation_record", "上片1", "上片2")
                    )
                    .or(w -> w
                        .eq("task_type", "定制")
                        .in("operation_record", "旋转1", "旋转2")
                    )
                )
                .eq("operation_mode", "结束")
                .ge("operation_record_time", startDate)
                .groupBy("DATE_FORMAT(operation_record_time, '%Y-%m-%d')", "warehouse")
                .orderByAsc("date", "warehouse");
 
            return baseMapper.selectMaps(queryWrapper);
 
        } catch (Exception e) {
            log.error("查询库位数据失败", e);
            throw new RuntimeException("查询库位数据失败: " + e.getMessage());
        }
    }
}