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 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.format.DateTimeFormatter; import java.time.temporal.TemporalAdjusters; import java.util.*; import java.util.stream.Collectors; /** *

* 绩效管理-班次 服务实现类 *

* * @author 江苏鵷雏网络科技有限公司 * @since 2024-05-08 09:12:04 */ @Service public class PerformanceShiftServiceImpl extends ServiceImpl implements PerformanceShiftService { @Autowired private EnumService enumService; public List 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.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 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 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.lambdaUpdate() .set(PerformanceShift::getShift, performanceShiftAddDto.getShift()) .eq(PerformanceShift::getUserId, s) .eq(PerformanceShift::getWorkTime, formatterDateTime)); } } } @Override public Map performanceShiftPage(Page page, String time, String userName, String laboratory) { IPage mapIPage = baseMapper.performanceShiftPage(page, time, userName, laboratory); List shiftType = enumService.selectEnumByCategory("班次类型"); List> mapYearIPage = baseMapper.performanceShiftYearPage(time, userName, laboratory); mapIPage.getRecords().forEach(i -> { String[] shiftTimes = i.getShiftTime().split(";"); int totalAttendance = 0; List map = new ArrayList<>(); // 分割日期 for (String shiftTime : shiftTimes) { Map 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 hashMap = new HashMap<>(); for (Map 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 localDateTimesBetween = getLocalDateTimesBetween(firstDayOfMonth.atStartOfDay(), lastDayOfMonth.atStartOfDay()); List list1 = new ArrayList<>(); for (LocalDateTime dateTime : localDateTimesBetween) { Map 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 resultMap = new HashMap<>(); resultMap.put("page", mapIPage); resultMap.put("headerList", list1); return resultMap; } @Override public void performanceShiftUpdate(PerformanceShift performanceShift) { baseMapper.update(new PerformanceShift(), Wrappers.lambdaUpdate() .eq(PerformanceShift::getId, performanceShift.getId()) .set(PerformanceShift::getShift, performanceShift.getShift())); } @Override public IPage> performanceShiftPageYear(Page page, String time, String userName, String laboratory) { IPage> mapYearIPage = baseMapper.performanceShiftYear(page, time, userName, laboratory); List shiftType = enumService.selectEnumByCategory("班次类型"); mapYearIPage.setRecords(annualAttendanceProcessing(mapYearIPage.getRecords(), shiftType)); return mapYearIPage; } // 年分页与导出共同使用 public List> annualAttendanceProcessing(List> mapYearList, List shiftType){ for (Map map : mapYearList) { Map resultMap = new HashMap<>(); Map hashMapYear = new LinkedHashMap<>(); int totalYearAttendance = 0; // 一年12个月 for (int i = 1; i < 13; i++) { Map 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 void dataRequiredForProcessingIntoExcel(List> list){ Map>> userId = list.stream().collect(Collectors.groupingBy(i -> i.get("user_id"))); userId.forEach((k, v) -> { System.out.println(k); System.out.println("============="); System.out.println(v); }); } @Override public Map exportToExcel(String time, String userName, String laboratory) { Map map = new HashMap<>(); List shiftType = enumService.selectEnumByCategory("班次类型"); DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 将字符串时间转换为 LocalDateTime 类型时间 LocalDateTime localDateTime = LocalDateTime.parse(time, formatters); map.put("header", getHeader(localDateTime.getYear() + " 年", shiftType)); List> mapYearList = baseMapper.performanceShiftYearList(time, userName, laboratory); annualAttendanceProcessing(mapYearList, shiftType); dataRequiredForProcessingIntoExcel(mapYearList); map.put("data", mapYearList); return map; } // 获取两个localDateTime的每一天 public static List getLocalDateTimesBetween(LocalDateTime start, LocalDateTime end) { List 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> */ private static List> getHeader(String month, List enums){ List> line = new ArrayList<>(); line.add(Arrays.asList("考勤汇总", "序号", "序号")); line.add(Arrays.asList("考勤汇总", "工号", "工号")); line.add(Arrays.asList("考勤汇总", "姓名", "姓名")); // 年 header for (Enums anEnum : enums) { line.add(Arrays.asList("考勤汇总", month, anEnum.getLabel())); } // 月header for (int i = 1; i < 13; i++) { for (Enums anEnum : enums) { line.add(Arrays.asList("出勤详情", i + " 月", anEnum.getLabel())); } } return line; } }