Crunchy
2024-05-13 35da9191297752452f7ab60ff9bc3eed515dfeec
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
package com.yuanchu.mom.service.impl;
 
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.mom.dto.PerformanceShiftAddDto;
import com.yuanchu.mom.dto.PerformanceShiftMapDto;
import com.yuanchu.mom.mapper.PerformanceShiftMapper;
import com.yuanchu.mom.pojo.Enums;
import com.yuanchu.mom.pojo.PerformanceShift;
import com.yuanchu.mom.service.EnumService;
import com.yuanchu.mom.service.PerformanceShiftService;
import com.yuanchu.mom.utils.JackSonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
 
/**
 * <p>
 * 绩效管理-班次 服务实现类
 * </p>
 *
 * @author 江苏鵷雏网络科技有限公司
 * @since 2024-05-08 09:12:04
 */
@Service
public class PerformanceShiftServiceImpl extends ServiceImpl<PerformanceShiftMapper, PerformanceShift> implements PerformanceShiftService {
 
    @Autowired
    private EnumService enumService;
 
    public List<PerformanceShift> list = new ArrayList<>();
 
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void performanceShiftAdd(PerformanceShiftAddDto performanceShiftAddDto) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDateTime = performanceShiftAddDto.getStartWeek().format(formatter);
        String[] splitUserId = performanceShiftAddDto.getUserId().split(",");
        for (String userId : splitUserId) {
            boolean exists = baseMapper.exists(Wrappers.<PerformanceShift>lambdaQuery()
                    .eq(PerformanceShift::getWorkTime, formattedDateTime)
                    .eq(PerformanceShift::getUserId, userId));
            // 如果不存在添加数据
            if (!exists) {
                LocalDate firstDayOfMonth = performanceShiftAddDto.getEndWeek().toLocalDate().withDayOfMonth(1);
                LocalDate lastDayOfMonth = performanceShiftAddDto.getEndWeek().toLocalDate().with(TemporalAdjusters.lastDayOfMonth());
                List<LocalDateTime> localDateTimesBetween = getLocalDateTimesBetween(firstDayOfMonth.atStartOfDay(), lastDayOfMonth.atStartOfDay());
                localDateTimesBetween.forEach(i -> {
                    for (String s : splitUserId) {
                        PerformanceShift performanceShift = new PerformanceShift();
                        performanceShift.setUserId(Integer.valueOf(s));
                        performanceShift.setWorkTime(i);
                        performanceShift.setShift("");
                        list.add(performanceShift);
                    }
                    if (list.size() >= 1000) {
                        baseMapper.insertBatchSomeColumn(list);
                        list.clear();
                    }
                });
                if (!list.isEmpty()) {
                    baseMapper.insertBatchSomeColumn(list);
                }
            }
        }
        // 再次更新
        List<LocalDateTime> datesBetween = getLocalDateTimesBetween(performanceShiftAddDto.getStartWeek(), performanceShiftAddDto.getEndWeek());
        for (LocalDateTime date : datesBetween) {
            for (String s : splitUserId) {
                PerformanceShift performanceShift = new PerformanceShift();
                performanceShift.setShift(performanceShiftAddDto.getShift());
                performanceShift.setUserId(Integer.valueOf(s));
                performanceShift.setWorkTime(date);
                String formatterDateTime = date.format(formatter);
                baseMapper.update(new PerformanceShift(), Wrappers.<PerformanceShift>lambdaUpdate()
                        .set(PerformanceShift::getShift, performanceShiftAddDto.getShift())
                        .eq(PerformanceShift::getUserId, s)
                        .eq(PerformanceShift::getWorkTime, formatterDateTime));
            }
        }
    }
 
    @Override
    public Map<String, Object> performanceShiftPage(Page<Object> page, String time, String userName, String laboratory) {
        IPage<PerformanceShiftMapDto> mapIPage = baseMapper.performanceShiftPage(page, time, userName, laboratory);
        List<Enums> shiftType = enumService.selectEnumByCategory("班次类型");
        List<Map<String, Object>> mapYearIPage = baseMapper.performanceShiftYearPage(time, userName, laboratory);
        mapIPage.getRecords().forEach(i -> {
            String[] shiftTimes = i.getShiftTime().split(";");
            int totalAttendance = 0;
            List<Map<String, Object>> map = new ArrayList<>();
            // 分割日期
            for (String shiftTime : shiftTimes) {
                Map<String, Object> hashMap = new HashMap<>();
                String[] shiftTimeAndShift = shiftTime.split(":");
                for (Enums enums : shiftType) {
                    if (!i.getMonthlyAttendance().containsKey(enums.getLabel())) {
                        i.getMonthlyAttendance().put(enums.getLabel(), 0);
                    }
                    if (enums.getValue().equals(shiftTimeAndShift[1])) {
                        Integer num = (Integer) i.getMonthlyAttendance().get(enums.getLabel());
                        i.getMonthlyAttendance().put(enums.getLabel(), num += 1);
                    }
                }
                if (shiftTimeAndShift[1].equals("1") || shiftTimeAndShift[1].equals("2") || shiftTimeAndShift[1].equals("0")) {
                    i.getMonthlyAttendance().put("totalAttendance", totalAttendance += 1);
                }
                hashMap.put("id", shiftTimeAndShift[2]);
                hashMap.put("shift", shiftTimeAndShift[1]);
                hashMap.put("time", shiftTimeAndShift[0]);
                map.add(hashMap);
            }
            int totalYearAttendance = 0;
            Map<String, Object> hashMap = new HashMap<>();
            for (Map<String, Object> record : mapYearIPage) {
                if (record.get("user_id").toString().equals(i.getUserId())) {
                    for (Enums enums : shiftType) {
                        if (!hashMap.containsKey(enums.getLabel())) {
                            hashMap.put(enums.getLabel(), 0);
                        }
                        if (enums.getValue().equals(record.get("shift"))) {
                            Integer num = (Integer) hashMap.get(enums.getLabel());
                            hashMap.put(enums.getLabel(), num += 1);
                        }
                    }
                    if (record.get("shift").equals("1") || record.get("shift").equals("2") || record.get("shift").equals("0")) {
                        hashMap.put("totalAttendance", totalYearAttendance += 1);
                    }
                }
            }
            i.setSidebarAnnualAttendance(hashMap);
            i.setList(map);
            i.setShiftTime(null);
        });
        // 获取header时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 将字符串时间转换为 LocalDateTime 类型时间
        LocalDateTime localDateTime = LocalDateTime.parse(time, formatters);
        LocalDate firstDayOfMonth = localDateTime.toLocalDate().withDayOfMonth(1);
        LocalDate lastDayOfMonth = localDateTime.toLocalDate().with(TemporalAdjusters.lastDayOfMonth());
        List<LocalDateTime> localDateTimesBetween = getLocalDateTimesBetween(firstDayOfMonth.atStartOfDay(), lastDayOfMonth.atStartOfDay());
        List<Object> list1 = new ArrayList<>();
        for (LocalDateTime dateTime : localDateTimesBetween) {
            Map<Object, Object> hashMap = new HashMap<>();
            DateTime parse = DateUtil.parse(dateTime.format(formatter));
            hashMap.put("weekly", DateUtil.weekOfYear(DateUtil.offsetDay(parse, 1)));
            hashMap.put("headerTime", getWeek(dateTime.format(formatters)));
            list1.add(hashMap);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("page", mapIPage);
        resultMap.put("headerList", list1);
        return resultMap;
    }
 
    @Override
    public void performanceShiftUpdate(PerformanceShift performanceShift) {
        baseMapper.update(new PerformanceShift(), Wrappers.<PerformanceShift>lambdaUpdate()
                .eq(PerformanceShift::getId, performanceShift.getId())
                .set(PerformanceShift::getShift, performanceShift.getShift()));
    }
 
    @Override
    public IPage<Map<String, Object>> performanceShiftPageYear(Page<Object> page, String time, String userName, String laboratory) {
        IPage<Map<String, Object>> mapYearIPage = baseMapper.performanceShiftYear(page, time, userName, laboratory);
        List<Enums> shiftType = enumService.selectEnumByCategory("班次类型");
        mapYearIPage.setRecords(annualAttendanceProcessing(mapYearIPage.getRecords(), shiftType));
        return mapYearIPage;
    }
 
    // 年分页与导出共同使用
    public List<Map<String, Object>> annualAttendanceProcessing(List<Map<String, Object>> mapYearList, List<Enums> shiftType){
        for (Map<String, Object> map : mapYearList) {
            Map<String, Object> resultMap = new LinkedHashMap<>();
            Map<String, Object> hashMapYear = new LinkedHashMap<>();
            int totalYearAttendance = 0;
            // 一年12个月
            for (int i = 1; i < 13; i++) {
                Map<String, Object> hashMapMonth = new LinkedHashMap<>();
                int totalMonthAttendance = 0;
                for (Enums enums : shiftType) {
                    if (!hashMapYear.containsKey(enums.getLabel())) {
                        hashMapYear.put(enums.getLabel(), 0);
                    }
                    // 月
                    if (ObjectUtils.isNotEmpty(map.get("month_str")) && map.get("work_time").equals(i)) {
                        String charArray = map.get("month_str").toString();
                        int count = countOccurrences(charArray, i + ":" + enums.getValue());
                        hashMapMonth.put(enums.getLabel(), count);
                        hashMapYear.put(enums.getLabel(), Integer.parseInt(hashMapYear.get(enums.getLabel()).toString()) + count );
                        if (enums.getValue().equals("0") || enums.getValue().equals("1") || enums.getValue().equals("2")) {
                            totalMonthAttendance += count;
                            totalYearAttendance += count;
                        }
                    }
                    // 空数据
                    else {
                        map.put("work_time", i);
                        hashMapMonth.put(enums.getLabel(), 0);
                    }
                }
                hashMapMonth.put("totalMonthAttendance", totalMonthAttendance);
                hashMapYear.put("totalYearAttendance", totalYearAttendance);
                resultMap.put(i + "", hashMapMonth);
            }
            map.remove("month_str");
            map.remove("year_str");
            map.put("year", hashMapYear);
            map.put("month", resultMap);
        }
        return mapYearList;
    }
 
    public static int countOccurrences(String str, String target) {
        int count = 0;
        int index = 0;
        while ((index = str.indexOf(target, index))!= -1) {
            count++;
            index += target.length();
        }
        return count;
    }
 
    public List<List<Object>> dataRequiredForProcessingIntoExcel(List<Map<String, Object>> list, List<Enums> enums) throws Exception {
        List<List<Object>> data = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            List<Object> excelRowList = new ArrayList<>();
            excelRowList.add(i + 1);
            excelRowList.add(list.get(i).get("account"));
            excelRowList.add(list.get(i).get("name"));
            Map<String, Object> year = JackSonUtil.unmarshal(JackSonUtil.marshal(list.get(i).get("year")), Map.class);
            excelRowList.add(year.get("totalYearAttendance"));
            enums.forEach(j -> {
                excelRowList.add(year.get(j.getLabel()));
            });
            Map<String, Map<String, Object>> month = JackSonUtil.unmarshal(JackSonUtil.marshal(list.get(i).get("month")), Map.class);
            for (int j = 1; j < 13; j++) {
                Object totalMonthAttendance = month.get(j + "").get("totalMonthAttendance");
                excelRowList.add(totalMonthAttendance);
                for (Enums anEnum : enums) {
                    excelRowList.add(month.get(j + "").get(anEnum.getLabel()));
                }
            }
            data.add(excelRowList);
        }
        return data;
    }
 
    @Override
    public Map<Object, Object> exportToYearExcel(String time, String userName, String laboratory) throws Exception {
        Map<Object, Object> map = new HashMap<>();
        List<Enums> shiftType = enumService.selectEnumByCategory("班次类型");
        DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 将字符串时间转换为 LocalDateTime 类型时间
        LocalDateTime localDateTime = LocalDateTime.parse(time, formatters);
        map.put("header", getYearHeader(localDateTime.getYear() + " 年", shiftType));
        List<Map<String, Object>> mapYearList = baseMapper.performanceShiftYearList(time, userName, laboratory);
        annualAttendanceProcessing(mapYearList, shiftType);
        List<List<Object>> lists = dataRequiredForProcessingIntoExcel(mapYearList, shiftType);
        map.put("data", lists);
        return map;
    }
 
    @Override
    public Map<Object, Object> exportToMonthExcel(String time, String userName, String laboratory) {
        List<Enums> shiftType = enumService.selectEnumByCategory("班次类型");
        List<PerformanceShiftMapDto> mapIPage = baseMapper.performanceShiftList(time, userName, laboratory);
        mapIPage.forEach(i -> {
            String[] shiftTimes = i.getShiftTime().split(";");
            int totalAttendance = 0;
            List<Map<String, Object>> map = new ArrayList<>();
            // 分割日期
            for (String shiftTime : shiftTimes) {
                Map<String, Object> hashMap = new HashMap<>();
                String[] shiftTimeAndShift = shiftTime.split(":");
                for (Enums enums : shiftType) {
                    if (!i.getMonthlyAttendance().containsKey(enums.getLabel())) {
                        i.getMonthlyAttendance().put(enums.getLabel(), 0);
                    }
                    if (enums.getValue().equals(shiftTimeAndShift[1])) {
                        Integer num = (Integer) i.getMonthlyAttendance().get(enums.getLabel());
                        i.getMonthlyAttendance().put(enums.getLabel(), num += 1);
                    }
                }
                if (shiftTimeAndShift[1].equals("1") || shiftTimeAndShift[1].equals("2") || shiftTimeAndShift[1].equals("0")) {
                    i.getMonthlyAttendance().put("totalAttendance", totalAttendance += 1);
                }
                hashMap.put("id", shiftTimeAndShift[2]);
                hashMap.put("shift", shiftTimeAndShift[1]);
                hashMap.put("time", shiftTimeAndShift[0]);
                map.add(hashMap);
            }
            i.setList(map);
            i.setShiftTime(null);
        });
        Map<Object, Object> map = new HashMap<>();
        DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 将字符串时间转换为 LocalDateTime 类型时间
        LocalDateTime localDateTime = LocalDateTime.parse(time, formatters);
        map.put("header", getMonthHeader(localDateTime, shiftType));
        List<List<Object>> lists = dataRequiredForProcessingIntoExcelMonth(mapIPage, shiftType);
        map.put("data", lists);
        return map;
    }
 
    // 获取两个localDateTime的每一天
    public static List<LocalDateTime> getLocalDateTimesBetween(LocalDateTime start, LocalDateTime end) {
        List<LocalDateTime> localDateTimes = new ArrayList<>();
        LocalDate currentDate = start.toLocalDate();
        LocalDateTime currentLocalDateTime = start;
        while (!currentDate.isAfter(end.toLocalDate())) {
            localDateTimes.add(currentLocalDateTime);
            currentLocalDateTime = currentLocalDateTime.plusDays(1);
            currentDate = currentDate.plusDays(1);
        }
        return localDateTimes;
    }
 
    public static String getWeek(String dayStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(dayStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            return day + " " + getWeekDay(dayOfWeek);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    public static String getWeekDay(int dayOfWeek) {
        switch (dayOfWeek) {
            case Calendar.MONDAY:
                return "周一";
            case Calendar.TUESDAY:
                return "周二";
            case Calendar.WEDNESDAY:
                return "周三";
            case Calendar.THURSDAY:
                return "周四";
            case Calendar.FRIDAY:
                return "周五";
            case Calendar.SATURDAY:
                return "周六";
            case Calendar.SUNDAY:
                return "周日";
            default:
                return "未知";
        }
    }
 
    /**
     * 返回表头
     *
     * 外层List代表行内层 List代表列  相同的列数据会被主动合并
     * 构造双列表头
     * @return List<List<String>>
     */
    private static List<List<String>> getYearHeader(String year, List<Enums> enums){
        List<List<String>> line = new ArrayList<>();
        line.add(Arrays.asList("考勤汇总", "序号", "序号"));
        line.add(Arrays.asList("考勤汇总", "工号", "工号"));
        line.add(Arrays.asList("考勤汇总", "姓名", "姓名"));
        line.add(Arrays.asList("出勤详情", year, "出勤"));
        // 年 header
        for (Enums anEnum : enums) {
            line.add(Arrays.asList("考勤汇总", year, anEnum.getLabel()));
        }
        // 月header
        for (int i = 1; i < 13; i++) {
            line.add(Arrays.asList("出勤详情", i + " 月", "出勤"));
            for (Enums anEnum : enums) {
                line.add(Arrays.asList("出勤详情", i + " 月", anEnum.getLabel()));
            }
        }
        return line;
    }
 
    private static List<List<String>> getMonthHeader(LocalDateTime localDateTimeYear, List<Enums> enums){
        String year = localDateTimeYear.getYear() + " 年人员班次";
        List<List<String>> line = new ArrayList<>();
        line.add(Arrays.asList(year, "序号", "序号", "序号"));
        line.add(Arrays.asList(year, "姓名", "姓名", "姓名"));
        line.add(Arrays.asList(year, "实验室", "实验室", "实验室"));
        line.add(Arrays.asList(year, localDateTimeYear.getYear() + "", localDateTimeYear.getYear() + "", "出勤"));
        line.add(Arrays.asList(year, localDateTimeYear.getYear() + "", localDateTimeYear.getYear() + "", enums.get(3).getLabel()));
        line.add(Arrays.asList(year, "年", "年", enums.get(4).getLabel()));
        line.add(Arrays.asList(year, localDateTimeYear.getMonthValue() + "", localDateTimeYear.getMonthValue() + "", enums.get(0).getLabel()));
        line.add(Arrays.asList(year, "月", "月", enums.get(1).getLabel()));
        line.add(Arrays.asList(year, "", "", enums.get(2).getLabel()));
        line.add(Arrays.asList(year, "周次", "星期", "出差"));
        LocalDate firstDayOfMonth = localDateTimeYear.toLocalDate().withDayOfMonth(1);
        LocalDate lastDayOfMonth = localDateTimeYear.toLocalDate().with(TemporalAdjusters.lastDayOfMonth());
        List<LocalDateTime> timeList = getLocalDateTimesBetween(firstDayOfMonth.atStartOfDay(), lastDayOfMonth.atStartOfDay());
        timeList.forEach(i -> {
            int dayOfYear = i.getDayOfMonth();
            Date from = Date.from(i.atZone(ZoneId.systemDefault()).toInstant());
            String weekDay = getWeekDay(i.getDayOfWeek().getValue());
            line.add(Arrays.asList(year, DateUtil.weekOfYear(DateUtil.offsetDay(from, 1)) + "", weekDay, dayOfYear + ""));
        });
        return line;
    }
 
    public List<List<Object>> dataRequiredForProcessingIntoExcelMonth(List<PerformanceShiftMapDto> list, List<Enums> enums) {
        List<List<Object>> data = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            List<Object> excelRowList = new ArrayList<>();
            excelRowList.add(i + 1);
            excelRowList.add(list.get(i).getName());
            excelRowList.add(list.get(i).getDepartment());
            excelRowList.add(list.get(i).getMonthlyAttendance().get("totalAttendance"));
            excelRowList.add(list.get(i).getMonthlyAttendance().get(enums.get(3).getLabel()));
            excelRowList.add(list.get(i).getMonthlyAttendance().get(enums.get(4).getLabel()));
            excelRowList.add(list.get(i).getMonthlyAttendance().get(enums.get(0).getLabel()));
            excelRowList.add(list.get(i).getMonthlyAttendance().get(enums.get(1).getLabel()));
            excelRowList.add(list.get(i).getMonthlyAttendance().get(enums.get(2).getLabel()));
            excelRowList.add(0); // 出差
            for (Map<String, Object> o : list.get(i).getList()) {
                String enumLabel = "";
                for (Enums anEnum : enums) {
                    if (anEnum.getValue().equals(o.get("shift"))) {
                        enumLabel = anEnum.getLabel();
                    }
                }
                excelRowList.add(ObjectUtils.isEmpty(enumLabel) ? "无" : enumLabel);
            }
            data.add(excelRowList);
        }
        return data;
    }
}