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
package com.qianwen.smartman.modules.mdc.service.impl;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
 
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qianwen.core.tool.utils.DateTimeUtil;
import com.qianwen.core.tool.utils.DateUtil;
import com.qianwen.core.tool.utils.Func;
import com.qianwen.smartman.common.constant.CommonConstant;
import com.qianwen.smartman.common.constant.DateConstant;
import com.qianwen.smartman.common.utils.LocalDateTimeUtils;
import com.qianwen.smartman.modules.smis.entity.Workstation;
import com.qianwen.smartman.modules.smis.service.IWorkstationService;
import com.qianwen.smartman.modules.mdc.entity.SuperAggregate;
import com.qianwen.smartman.modules.mdc.entity.SuperAggregateState;
import com.qianwen.smartman.modules.mdc.enums.OpenTypeEnums;
import com.qianwen.smartman.modules.mdc.enums.StatisticalMethodEnum;
import com.qianwen.smartman.modules.mdc.mapper.SuperAggregateStateFeedbackMapper;
import com.qianwen.smartman.modules.mdc.mapper.SuperAggregateStateMapper;
import com.qianwen.smartman.modules.mdc.service.ISuperAggregateStateService;
import com.qianwen.smartman.modules.mdc.utils.FilterOffUtils;
import com.qianwen.smartman.modules.mdc.vo.StatusTimeTopVO;
 
import cn.hutool.core.date.LocalDateTimeUtil;
 
@Service
public class SuperAggregateStateServiceImpl implements ISuperAggregateStateService {
    private static final Logger log = LoggerFactory.getLogger(SuperAggregateStateServiceImpl.class);
    private final SuperAggregateStateMapper baseMapper;
    private final SuperAggregateStateFeedbackMapper aggregateStateFeedbackMapper;
    private final IWorkstationService workstationService;
 
    public SuperAggregateStateServiceImpl(final SuperAggregateStateMapper baseMapper, final SuperAggregateStateFeedbackMapper aggregateStateFeedbackMapper, final IWorkstationService workstationService) {
        this.baseMapper = baseMapper;
        this.aggregateStateFeedbackMapper = aggregateStateFeedbackMapper;
        this.workstationService = workstationService;
    }
 
    @Override
    public List<SuperAggregateState> getStatusData(List<Long> workstationIds, StatisticalMethodEnum statisticalMethod, LocalDate startDate, LocalDate endDate) {
        List<SuperAggregateState> statusDataList;
        if (StatisticalMethodEnum.SHIFT.equals(statisticalMethod) || StatisticalMethodEnum.DAY.equals(statisticalMethod) || StatisticalMethodEnum.WEEK.equals(statisticalMethod) || StatisticalMethodEnum.MONTH.equals(statisticalMethod)) {
            statusDataList = this.baseMapper.getStatusDataByFactoryDate(workstationIds, Integer.parseInt(LocalDateTimeUtil.format(startDate, "yyyyMMdd")), Integer.parseInt(LocalDateTimeUtil.format(endDate, "yyyyMMdd")));
        } else {
            //statusDataList = this.baseMapper.getStatusData(workstationIds, LocalDateTimeUtil.format(startDate, DateConstant.PATTERN_DATE_TIME), LocalDateTimeUtil.format(endDate.plusDays(1L), DateConstant.PATTERN_DATE_TIME));
            LocalDateTime startTime = LocalDateTime.of(startDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(endDate.plusDays(1L), LocalTime.MIN);
            //statusDataList = this.baseMapper.getStatusData(workstationIds, startDate,endDate.plusDays(1L));
            statusDataList = this.baseMapper.getStatusData(workstationIds, DateTimeUtil.toDate(startTime),DateTimeUtil.toDate(endTime));
        }
        return buildDuration(statusDataList);
    }
 
    @Override
    public List<SuperAggregateState> getStatusDataWithFeedback(List<Long> workstationIds, StatisticalMethodEnum statisticalMethod, LocalDate startDate, LocalDate endDate) {
        //稼动率查询
        List<SuperAggregateState> statusDataList;
        if (StatisticalMethodEnum.SHIFT.equals(statisticalMethod) || StatisticalMethodEnum.DAY.equals(statisticalMethod) || StatisticalMethodEnum.WEEK.equals(statisticalMethod) || StatisticalMethodEnum.MONTH.equals(statisticalMethod)) {
            //statusDataList = this.aggregateStateFeedbackMapper.getStatusDataByFactoryDate(workstationIds, LocalDateTimeUtil.format(startDate, "yyyyMMdd"), LocalDateTimeUtil.format(endDate, "yyyyMMdd"));
            int startFactoryDate = Integer.parseInt(LocalDateTimeUtil.format(startDate, "yyyyMMdd"));
            int endFactoryDate = Integer.parseInt(LocalDateTimeUtil.format(endDate, "yyyyMMdd"));
            statusDataList = this.aggregateStateFeedbackMapper.getStatusDataByFactoryDate(workstationIds, startFactoryDate, endFactoryDate);
        } else {
            //statusDataList = this.aggregateStateFeedbackMapper.getStatusData(workstationIds, LocalDateTimeUtil.format(startDate, DateConstant.PATTERN_DATE_TIME), LocalDateTimeUtil.format(endDate.plusDays(1L), DateConstant.PATTERN_DATE_TIME));
            LocalDateTime startTime = LocalDateTime.of(startDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(endDate.plusDays(1L), LocalTime.MIN);
            statusDataList = this.aggregateStateFeedbackMapper.getStatusData(workstationIds, DateTimeUtil.toDate(startTime),DateTimeUtil.toDate(endTime));
        }
        return buildDuration(statusDataList);
    }
 
    @Override
    public List<SuperAggregateState> getStatusByCondition(List<Long> workstationIds, LocalDateTime startTime, LocalDateTime endTime) {
        //List<SuperAggregateState> statusDataList = this.baseMapper.getStatusData(workstationIds, LocalDateTimeUtil.format(startTime, DateConstant.PATTERN_DATE_TIME), LocalDateTimeUtil.format(endTime, DateConstant.PATTERN_DATE_TIME));
        List<SuperAggregateState> statusDataList = this.baseMapper.getStatusData(workstationIds,  DateTimeUtil.toDate(startTime), DateTimeUtil.toDate(endTime));
        return buildDuration(statusDataList);
    }
 
    @Override
    public List<SuperAggregateState> getStatusByTimeSection(List<Long> workstationIds, LocalDateTime startTime, LocalDateTime endTime) {
        //List<SuperAggregateState> statusDataList = this.baseMapper.getStatusDataByTimeSection(workstationIds, LocalDateTimeUtil.format(startTime, DateConstant.PATTERN_DATE_TIME), LocalDateTimeUtil.format(endTime, DateConstant.PATTERN_DATE_TIME));
        
        List<SuperAggregateState> statusDataList = this.baseMapper.getStatusDataByTimeSection(workstationIds, DateTimeUtil.toDate(startTime), DateTimeUtil.toDate(endTime));
        return buildDuration(startTime, statusDataList);
    }
 
    @Override
    public List<StatusTimeTopVO> getStatusTimeByWcs(List<Long> workstationIds, LocalDateTime startTime, LocalDateTime endTime, Integer status, Integer top) {
        List<StatusTimeTopVO> voList = new ArrayList<>();
        //查询除所有状态时可用的工位,转换位 工位id -> 工位 的map
        Map<Long, Workstation> workstationMap = this.workstationService.list(Wrappers.<Workstation>lambdaQuery()
                .eq(Workstation::getStatus, CommonConstant.ENABLE)).stream().collect(Collectors.toMap(Workstation::getId, Function.identity()));
           
       // Date startTimeD = LocalDateUtil.localDateTimeToDate(startTime);
        //startTimeD = new Date(124,8,2);
        //Date endTimeD = LocalDateUtil.localDateTimeToDate(endTime);
        //endTimeD = new Date(124,8,3);
        
        //查询出时间段内wcs=status的所有数据
        List<SuperAggregateState> equipmentStatusDuration = this.baseMapper.getEquipmentStatusDuration(workstationIds, DateTimeUtil.toDate(startTime), DateTimeUtil.toDate(endTime), status);
        
        List<SuperAggregateState> equipmentStatusDuration2 = FilterOffUtils.filterOffDay(equipmentStatusDuration, OpenTypeEnums.TIME_USED_ANALYSIS);//过滤数据,TIME_USED_ANALYSIS open =1则过滤
        Map<Long, Long> timeMap = buildDuration(startTime, equipmentStatusDuration2).stream().collect(Collectors.groupingBy(SuperAggregate::getWorkstationId, Collectors.summingLong(SuperAggregateState::getDurationCollect))).entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).limit(top.intValue()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, java.util.LinkedHashMap::new));
        //yangys改了buildDuration,去掉了startTime参数
        //Map<Long, Long> timeMap = buildDuration(equipmentStatusDuration2,ChronoUnit.SECONDS).stream().collect(Collectors.groupingBy(SuperAggregate::getWorkstationId, Collectors.summingLong(SuperAggregateState::getDurationCollect))).entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).limit(top.intValue()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, java.util.LinkedHashMap::new));
        /*
        Map<Long, Long> timeMap = (buildDuration(startTime, FilterOffUtils.filterOffDay(equipmentStatusDuration, OpenTypeEnums.TIME_USED_ANALYSIS)).stream().collect(Collectors.groupingBy((v0) -> {
            return v0.getWorkstationId();
        }, Collectors.summingLong((v0) -> {
            return v0.getDurationCollect();
        })))).entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).limit(top.intValue()).collect(Collectors.toMap((v0) -> {
            return v0.getKey();
        }, (v0) -> {
            return v0.getValue();
        }, (oldValue, newValue) -> {
            return oldValue;
        }, LinkedHashMap::new));*/
        timeMap.forEach((k, v) -> {
            StatusTimeTopVO statusTimeTopVO = new StatusTimeTopVO();
            statusTimeTopVO.setValue(secondToHour(v));//
            statusTimeTopVO.setWorkstation(workstationMap.get(k));
            voList.add(statusTimeTopVO);
        });
        return voList;
    }
 
    @Override
    public List<SuperAggregateState> getOeeAnalysis(List<Long> workStationIdList, LocalDateTime startTime, LocalDateTime endTime) {
        //Date startTimeD = LocalDateUtil.localDateTimeToDate(startTime);
        //Date endTimeD = LocalDateUtil.localDateTimeToDate(endTime);
        //List<SuperAggregateState> statusDataList = this.baseMapper.getEquipmentStatusDuration(workStationIdList, LocalDateTimeUtil.format(startTime, DateConstant.PATTERN_DATE_TIME), LocalDateTimeUtil.format(endTime, DateConstant.PATTERN_DATE_TIME), null);
        List<SuperAggregateState> statusDataList = this.baseMapper.getEquipmentStatusDuration(workStationIdList, DateTimeUtil.toDate(startTime), DateTimeUtil.toDate(endTime), null);
        return buildDuration(startTime, FilterOffUtils.filterOffDay(statusDataList, OpenTypeEnums.OEE));
    }
 
    @Override
    public List<SuperAggregateState> getShiftStatusData(List<Long> workstationIdList, String factoryDate, Integer shiftIndex) {
        List<SuperAggregateState> statusDataShift = this.baseMapper.getStatusDataShift(Integer.valueOf(factoryDate.replace("-", "")), shiftIndex, workstationIdList);
        return buildDuration(statusDataShift);
    }
 
    @Override
    public List<SuperAggregateState> getStatusByFactory(List<Long> workstationIdList, String factoryDate, Integer shiftIndex) {
        List<SuperAggregateState> statusDataShift = this.baseMapper.getStatusByFactory(Integer.valueOf(Func.toInt(factoryDate.replace("-", ""))), shiftIndex, workstationIdList);
        return buildDuration(statusDataShift);
    }
 
    @Override
    public List<SuperAggregateState> listsState(List<Long> ids, LocalDate queryTime, List<Integer> shiftIndex) {
        String factoryDate = DateUtil.format(queryTime, DateConstant.PATTERN_DATE);
        List<SuperAggregateState> statusDataShift = this.baseMapper.listsState(Integer.valueOf(Func.toInt(factoryDate.replace("-", ""))), ids, shiftIndex);
        return buildDuration(statusDataShift);
    }
 
    @Override
    public List<SuperAggregateState> getDataByWeek(List<Long> ids, Integer year, List<Integer> weekList) {
        List<SuperAggregateState> data = this.baseMapper.getDataByWeek(ids, year, weekList);
        return buildDuration(data);
    }
 
    @Override
    public List<SuperAggregateState> getDataByMonth(List<Long> ids, Integer year, List<Integer> monthList) {
        List<SuperAggregateState> data = this.baseMapper.getDataByMonth(ids, year, monthList);
        
        return buildDuration(data);
    }
 
    @Override
    public List<SuperAggregateState> crossDay(LocalDateTime start, LocalDateTime end) {
        String startTime = DateUtil.formatDateTime(start);
        String endTime = DateUtil.formatDateTime(end);
        List<SuperAggregateState> res = this.baseMapper.listCrossDay(startTime, endTime);
        return buildDuration(res);
    }
    /*
    @Override
    public void saveState(List<SuperAggregateState> collect) {
        Map<Long, List<SuperAggregateState>> map = collect.stream().collect(Collectors.groupingBy(SuperAggregate::getWorkstationId));
        map.forEach(this.baseMapper::saveState);
        
    }
*/
    @Override
    public List<SuperAggregateState> getStatusDataByTime(List<Long> workstationIdList, LocalDateTime start, LocalDateTime end) {
        List<SuperAggregateState> superAggregateStateList = new ArrayList<>();
        String startTime = LocalDateTimeUtil.format(start, "yyyy-MM-dd HH:mm:ss.SSS");
        String endTime = LocalDateTimeUtil.format(end, "yyyy-MM-dd HH:mm:ss.SSS");
        List<SuperAggregateState> inTime = this.baseMapper.listInTime(workstationIdList, startTime, endTime);
        if (Func.isNotEmpty(inTime)) {
            superAggregateStateList.addAll(inTime);
        }
        List<SuperAggregateState> tsInTime = this.baseMapper.listTsInTime(workstationIdList, startTime, endTime);
        if (Func.isNotEmpty(tsInTime)) {
            superAggregateStateList.addAll(tsInTime);
        }
        List<SuperAggregateState> endTimeInTime = this.baseMapper.listEndTimeInTime(workstationIdList, startTime, endTime);
        if (Func.isNotEmpty(endTimeInTime)) {
            superAggregateStateList.addAll(inTime);
        }
        List<SuperAggregateState> outTime = this.baseMapper.listOutTime(workstationIdList, startTime, endTime);
        if (Func.isNotEmpty(outTime)) {
            superAggregateStateList.addAll(outTime);
        }
        superAggregateStateList.stream().forEach(superAggregateState -> {
            if (Func.isEmpty(endTime)) {
                superAggregateState.setEndTime(Timestamp.valueOf(LocalDateTime.now()));
            }
            if (superAggregateState.getStartTime().before(Timestamp.valueOf(start))) {
                superAggregateState.setStartTime(Timestamp.valueOf(start));
            }
            if (superAggregateState.getEndTime().after(Timestamp.valueOf(end))) {
                superAggregateState.setEndTime(Timestamp.valueOf(end));
            }
        });
        return superAggregateStateList;
    }
 
    @Override
    public List<SuperAggregateState> queryPerfByDay(Long workstationId, String startTime, String endTime, Long employeeId) {
        List<SuperAggregateState> states = this.baseMapper.queryPerfByDay(workstationId, startTime, endTime, employeeId);
        return buildDuration(states);
    }
 
    @Override
    public List<SuperAggregateState> queryPerfByWeek(Long workstationId, List<Integer> weeks, Long employeeId) {
        List<SuperAggregateState> states = this.baseMapper.queryPerfByWeek(workstationId, weeks, employeeId);
        return buildDuration(states);
    }
 
    @Override
    public List<SuperAggregateState> queryPerfByMonth(Long workstationId, List<Integer> months, Long employeeId) {
        List<SuperAggregateState> states = this.baseMapper.queryPerfByMonth(workstationId, months, employeeId);
        return buildDuration(states);
    }
 
    @Override
    public List<SuperAggregateState> queryPerfByEtDay(Long employeeId, String queryTime) {
        List<SuperAggregateState> states = this.baseMapper.queryPerfByEtDay(employeeId, queryTime);
        return buildDuration(states);
    }
 
    @Override
    public List<SuperAggregateState> queryPerfByEtWeek(Long employeeId, Integer week) {
        List<SuperAggregateState> states = this.baseMapper.queryPerfByEtWeek(employeeId, week);
        return buildDuration(states);
    }
 
    @Override
    public List<SuperAggregateState> queryPerfByEtMonth(Long employeeId, Integer month) {
        List<SuperAggregateState> states = this.baseMapper.queryPerfByEtMonth(employeeId, month);
        return buildDuration(states);
    }
 
    @Override
    public List<SuperAggregateState> queryPerfByWtDay(Long workstationId, String time) {
        List<SuperAggregateState> states = this.baseMapper.queryPerfByWtDay(workstationId, time);
        return buildDuration(states);
    }
 
    @Override
    public List<SuperAggregateState> queryPerfByWtWeek(Long workstationId, Integer week) {
        List<SuperAggregateState> states = this.baseMapper.queryPerfByWtWeek(workstationId, week);
        return buildDuration(states);
    }
 
    @Override
    public List<SuperAggregateState> queryPerfByWtMonth(Long workstationId, Integer month) {
        List<SuperAggregateState> states = this.baseMapper.queryPerfByWtMonth(workstationId, month);
        return buildDuration(states);
    }
 
    @Override
    public List<SuperAggregateState> getCurrMonthState(List<Long> ids, Integer month) {
        List<SuperAggregateState> states = this.baseMapper.getCurrMonthState(ids, month);
        return buildDuration(states);
    }
 
    @Override
    public List<SuperAggregateState> getCurrMonthAlarmState(List<Long> workIds, Integer month, Integer code) {
        List<SuperAggregateState> states = this.baseMapper.getCurrMonthAlarmState(workIds, month, code);
        return buildDuration(states);
    }
 
    @Override
    public List<SuperAggregateState> getCurrWeekAlarmState(List<Long> workIds, Integer week, Integer code) {
        List<SuperAggregateState> states = this.baseMapper.getCurrWeekAlarmState(workIds, week, code);
        return buildDuration(states);
    }
 
    private List<SuperAggregateState> buildDuration(List<SuperAggregateState> statusDataShift) {
        Date now = DateUtil.now();
        statusDataShift.forEach(x -> {
            if (Func.isEmpty(x.getEndTime()) ) {//|| x.getEndTime().toLocalDateTime().getYear()==1970
                x.setEndTime(new Timestamp(now.getTime()));
            }
            x.setDurationCollect(LocalDateTimeUtils.betweenTwoTime(x.getStartTime().toLocalDateTime(), x.getEndTime().toLocalDateTime(), ChronoUnit.MILLIS));
            //System.out.println(x);
        });
        return statusDataShift;
    }
 
    
    
    private List<SuperAggregateState> buildDuration(LocalDateTime startTime, List<SuperAggregateState> statusDataShift) {
        Date now = DateUtil.now();
        statusDataShift.forEach(x -> {
            if (Func.isEmpty(x.getEndTime()) || x.getEndTime().toLocalDateTime().getYear()==1970) {
                x.setEndTime(new Timestamp(now.getTime()));
            }
            if (x.getStartTime().toLocalDateTime().isBefore(startTime)) {
                x.setStartTime(Timestamp.valueOf(startTime));
                x.setTime(Timestamp.valueOf(startTime));//这个才起作用,getStartTime获取的是time
            }
            x.setDurationCollect(LocalDateTimeUtils.betweenTwoTime(x.getStartTime().toLocalDateTime(), x.getEndTime().toLocalDateTime(), ChronoUnit.MILLIS));
            //System.out.println(x);
        });
        return statusDataShift;
    }
 
    private double secondToHour(Long second) {
        BigDecimal bg = new BigDecimal(second.longValue());
        BigDecimal bg2 = new BigDecimal("3600000");
        return bg.divide(bg2, 2, RoundingMode.HALF_UP).doubleValue();
    }
}