使用map或者List<Tuple>组装数据

本文介绍了如何使用Java中的Map和List<Tuple>来组装数据。对于Map,重点在于key的唯一性,通过遍历List<MergeRow>,根据特定字段waybill_no创建或更新Map中的条目。而对于List<Tuple<String, List<Map<String, Object>>>>,适用于key不唯一的情况,需要比较相邻元素并整合相同key的数据。文章提供了详细的组装思路和示例代码。" 84898030,8239705,C语言动态数组的sizeof操作,"['C语言', '内存管理', '数组']

组装数据

1、使用Map组装 特点key唯一

将一个LIst<MergeRow>组装成以下格式:

Map<String, List<MergeRow>> result = Maps.newLinkedHashMap();

说明:MergeRow是一个对象 根据其中的某一个字段进行组装 例如:网点waybill_no

思路:


1、首先设计组装成的形式:
Map<String, List<MergeRow>> result = Maps.newLinkedHashMap();
2、代码思路:循环List<MergeRow>
判断result中是否含有waybill_no这个key 第一次肯定是不含有
那么创建一个mergeRows = Lists.newArrayList();并且put到result中result.put(waybillNo, mergeRows); 
后面的MergeRow对象的waybill_no如果和 result的key一致  那么add进去

Map<String, List<MergeRow>> result = Maps.newLinkedHashMap();
for (MergeRow mergeRow : rows) {
    String waybillNo = (String) mergeRow.toRow().get("waybill_no");
    if (StringUtils.isBlank(waybillNo)) {
        continue;
    }
    //判断是否存在
    List<MergeRow> mergeRows = result.get(waybillNo);
    if (mergeRows == null) {
        mergeRows = Lists.newArrayList();
        //不存在的话 存入一个空的
        result.put(waybillNo, mergeRows);
    }
    //waybillNo存在的话  会将waybillNo相同的都放在一起 
    mergeRows.add(mergeRow);
}

2、使用 List<Tuple<String, List<Map<String, Object>>>>组装 特点key不唯一

参考:https://blog.youkuaiyun.com/weixin_42201566/article/details/81428437

场景:将一个List<Map> 排序 如果相邻某个key(例如:org_code)相同的 map合成同一条记录   org_code 可能会间隔重复思路和map相似 不同的地方:

a、由于需要比较当前和上一条的org_code 所以需要一个全局变量tuple,

b、当前org_code和上一条org_code不一样时候也是 新建一个tuple

代码如下:

        List<Tuple<String, List<Map<String, Object>>>> result = Lists.newLinkedList();

        Tuple<String, List<Map<String, Object>>> tuple = null;
        for (Map map : list) {
            String orgCode = (String) map.get("org_code");
            if (tuple == null || !StringUtils.equals(orgCode, tuple.getOne())) {
                tuple = Tuple.of(orgCode, Lists.newArrayList(map));
                result.add(tuple);
            } else {
                tuple.getTwo().add(map);
            }
        }

 

package com.haosmart.dpr.mom.service.aps.impl; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.collection.ListUtil; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.google.common.collect.Lists; import com.haosmart.boot.mybatisplus.model.BaseModel; import com.haosmart.boot.mybatisplus.service.impl.HaoSmartBaseServiceImpl; import com.haosmart.boot.platform.dto.response.HaoSmartUserDTO; import com.haosmart.boot.platform.feign.IUserService; import com.haosmart.btp.mdm.enumcom.YesOrNoEnum; import com.haosmart.common.foundation.context.BaseContextHolder; import com.haosmart.common.foundation.exception.BusinessException; import com.haosmart.common.foundation.http.ErrorCode; import com.haosmart.common.foundation.http.ResponseResult; import com.haosmart.common.foundation.jwt.IJwtUser; import com.haosmart.dpr.mom.component.mybatis.helper.BatchRepositoryHelper; import com.haosmart.dpr.mom.component.mybatis.helper.BatchRepositoryHelperImpl; import com.haosmart.dpr.mom.config.StrategyDefinitionConfig; import com.haosmart.dpr.mom.constant.BusinessConstants; import com.haosmart.dpr.mom.dao.aps.ScheduleShiftCalendarDao; import com.haosmart.dpr.mom.dto.aps.*; import com.haosmart.dpr.mom.dto.bs.WorkcenterShiftCalendarDTO; import com.haosmart.dpr.mom.dto.inner.InnerWorkShiftModelScheduleDTO; import com.haosmart.dpr.mom.dto.mes.cs.OperationDTO; import com.haosmart.dpr.mom.dto.mes.cs.ProcessRouteDetailsDTO; import com.haosmart.dpr.mom.enumeration.ApsConfigurationEnum; import com.haosmart.dpr.mom.enumeration.MomModuleEnum; import com.haosmart.dpr.mom.enumeration.aps.ShiftModelTypeEnum; import com.haosmart.dpr.mom.ganttchart.scheduling.ScheduleGateway; import com.haosmart.dpr.mom.ganttchart.scheduling.context.SchedulingOrder; import com.haosmart.dpr.mom.infrastructure.mdm.dto.WorkCenterDTO; import com.haosmart.dpr.mom.infrastructure.mdm.service.WorkcenterQueryService; import com.haosmart.dpr.mom.model.aps.ScheduleShiftCalendar; import com.haosmart.dpr.mom.model.aps.ScheduleTask; import com.haosmart.dpr.mom.model.om.ProductionMonthPlan; import com.haosmart.dpr.mom.service.aps.ScheduleShiftCalendarService; import com.haosmart.dpr.mom.service.aps.ShiftModelService; import com.haosmart.dpr.mom.utils.MomDateUtil; import com.haosmart.dpr.mom.utils.WeiXinUtil; import com.haosmart.dpr.mom.utils.aps.TimeUtil; import com.haosmart.dpr.mom.vo.aps.*; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import javax.annotation.Resource; import java.time.LocalDate; import java.time.temporal.TemporalAdjusters; import java.util.*; import java.util.concurrent.*; import java.util.function.Function; import java.util.stream.Collectors; /** * <p> * 班次模型日程表 服务实现类 * </p> * * @author chixin * @since 2024-08-26 */ @Service public class ScheduleShiftCalendarServiceImpl extends HaoSmartBaseServiceImpl<ScheduleShiftCalendarDao, ScheduleShiftCalendar> implements ScheduleShiftCalendarService { @Resource private BatchRepositoryHelper<ScheduleShiftCalendar> batchRepositoryHelper; @Resource private WorkcenterQueryService workcenterQueryService; @Resource private ShiftModelService shiftModelService; @Resource private ScheduleGateway scheduleGateway; @Resource private ScheduleShiftCalendarDao scheduleShiftCalendarDao; @Autowired private IUserService iUserService; @Autowired private WeiXinUtil weiXinUtil; @Override @Transactional(rollbackFor = Exception.class) public void batchInsert(List<ScheduleShiftCalendar> entities) { if(CollectionUtils.isEmpty(entities)){ return; } batchRepositoryHelper.batchInsert(entities); } @Override @Transactional(rollbackFor = Exception.class) public void batchUpdate(List<ScheduleShiftCalendar> entities) { batchRepositoryHelper.batchUpdate(entities); } @Override @Transactional(rollbackFor = Exception.class) public void batchPhysicalDelete(List<ScheduleShiftCalendar> entities) { if(CollectionUtils.isEmpty(entities)){ return; } batchRepositoryHelper.batchRemove(entities); // //删除次数 // int deleteCount = entities.size()/1000; // for(int i = 0; i <= deleteCount; i++){ // List<ScheduleShiftCalendar> subList = entities.subList(i*1000,Math.min(entities.size(),(i+1)*1000)); // // } } @Override @Transactional(rollbackFor = Exception.class) public List<ScheduleShiftCalendar> create(ScheduleShiftCalendarCreateVO scheduleShiftCalendarCreateVO) { List<ScheduleShiftCalendar> resultList = new ArrayList<>(); do{ scheduleShiftCalendarCreateVO.setCalDate(scheduleShiftCalendarCreateVO.getStartCalDate()); resultList.addAll(updateById(BeanUtil.copyProperties(scheduleShiftCalendarCreateVO, ScheduleShiftCalendarUpdateVO.class))); scheduleShiftCalendarCreateVO.setStartCalDate(MomDateUtil.addOrSubtractsDate(scheduleShiftCalendarCreateVO.getStartCalDate(),1)); }while (scheduleShiftCalendarCreateVO.getStartCalDate().compareTo(scheduleShiftCalendarCreateVO.getEndCalDate())<=0); return resultList; } // @Override // public void batchCreate(ScheduleShiftCalendarCreateVO scheduleShiftCalendarCreateVO) { // List<Map<String, String>> workCenter = scheduleShiftCalendarCreateVO.getWorkCenter(); // Date startCalDate = scheduleShiftCalendarCreateVO.getStartCalDate(); // // for(Map<String, String> param : workCenter){ // scheduleShiftCalendarCreateVO.setWorkCenterCode(param.get("workCenterCode")); // scheduleShiftCalendarCreateVO.setWorkCenterName(param.get("workCenterName")); // scheduleShiftCalendarCreateVO.setStartCalDate(startCalDate); // create(scheduleShiftCalendarCreateVO); // } // } //start @Override @Transactional(rollbackFor = Exception.class) public void batchCreate(ScheduleShiftCalendarCreateVO scheduleShiftCalendarCreateVO) { List<Map<String, String>> workCenterList = scheduleShiftCalendarCreateVO.getWorkCenter(); Date startCalDate = scheduleShiftCalendarCreateVO.getStartCalDate(); Date endCalDate = scheduleShiftCalendarCreateVO.getEndCalDate(); // 收集所有日期和工作中心组合 List<Date> dates = getDateRange(startCalDate, endCalDate); List<Pair<String, String>> workCenterPairs = workCenterList.stream() .map(map -> Pair.of(map.get("workCenterCode"), map.get("workCenterName"))) .collect(Collectors.toList()); // 批量查询已有记录 ScheduleShiftCalendarQueryVO queryVO = new ScheduleShiftCalendarQueryVO(); queryVO.setStartCalDate(TimeUtil.convertedDate2LocalDateTime(startCalDate).toLocalDate()); queryVO.setEndCalDate(TimeUtil.convertedDate2LocalDateTime(endCalDate).toLocalDate()); queryVO.setWorkCenterCodeList(workCenterPairs.stream().map(Pair::getKey).collect(Collectors.toList())); queryVO.setTaskCode(BusinessConstants.DB_STR_DEFAULT); queryVO.setTaskVersion(BusinessConstants.DB_STR_DEFAULT); queryVO.setDefaultFlag(YesOrNoEnum.YES.getCode()); List<ScheduleShiftCalendarDTO> existingRecords = list(queryVO); // 按(日期, 工作中心)分组 Map<Pair<Date, String>, List<ScheduleShiftCalendarDTO>> groupByDateAndWorkCenter = existingRecords.stream() .collect(Collectors.groupingBy(dto -> Pair.of(dto.getCalDate(), dto.getWorkCenterCode()))); // 创建线程安全的集合 Queue<ScheduleShiftCalendar> toDelete = new ConcurrentLinkedQueue<>(); Queue<ScheduleShiftCalendar> toInsert = new ConcurrentLinkedQueue<>(); // 根据CPU核心数设置线程池大小(建议I/O密集型任务可设置2*核心数) int threadPoolSize = Math.min(8, Runtime.getRuntime().availableProcessors() * 2); ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize); // 使用CountDownLatch等待所有任务完成 CountDownLatch latch = new CountDownLatch(workCenterPairs.size()); workCenterPairs.forEach(workCenter -> executor.submit(() ->{ try{ String workCenterCode = workCenter.getKey(); String workCenterName = workCenter.getValue(); for (Date date : dates) { Pair<Date, String> key = Pair.of(date, workCenterCode); List<ScheduleShiftCalendarDTO> groupRecords = groupByDateAndWorkCenter.getOrDefault(key, Collections.emptyList()); // 提取不可修改的班次模型编码 List<String> cannotModifyShiftModelCodes = groupRecords.stream() .filter(dto -> !BusinessConstants.DB_STR_DEFAULT.equals(dto.getTaskVersion())) .map(ScheduleShiftCalendarDTO::getShiftModelCode) .distinct() .collect(Collectors.toList()); // 检查是否存在特殊班次模型 boolean hasSpecialShiftModel = groupRecords.stream() .anyMatch(dto -> ShiftModelTypeEnum.SPECIAL.getCode().equals(dto.getShiftModelType())); // 过滤可更新的班次模型 List<ShiftModelCreateVO> filteredShiftModels = scheduleShiftCalendarCreateVO.getShiftModelCreateVOList().stream() .filter(vo -> !cannotModifyShiftModelCodes.contains(vo.getShiftModelCode())) .collect(Collectors.toList()); // 如果存在特殊班次则只保留特殊班次 if (hasSpecialShiftModel) { filteredShiftModels = filteredShiftModels.stream() .filter(vo -> ShiftModelTypeEnum.SPECIAL.getCode().equals(vo.getShiftModelType())) .collect(Collectors.toList()); } // 生成新记录 if (!CollectionUtils.isEmpty(filteredShiftModels)) { ScheduleShiftCalendarCreateVO tempCreateVO = new ScheduleShiftCalendarCreateVO(); BeanUtil.copyProperties(scheduleShiftCalendarCreateVO, tempCreateVO); tempCreateVO.setWorkCenterCode(workCenterCode); tempCreateVO.setWorkCenterName(workCenterName); tempCreateVO.setStartCalDate(date); tempCreateVO.setEndCalDate(date); tempCreateVO.setShiftModelCreateVOList(filteredShiftModels); List<ScheduleShiftCalendar> newRecords = generateShiftCalendars(tempCreateVO, hasSpecialShiftModel); toInsert.addAll(newRecords); } // 标记可修改记录为待删除 List<ScheduleShiftCalendar> deletableRecords = groupRecords.stream() .filter(dto -> BusinessConstants.DB_STR_DEFAULT.equals(dto.getTaskVersion())) .map(dto -> BeanUtil.copyProperties(dto, ScheduleShiftCalendar.class)) .collect(Collectors.toList()); toDelete.addAll(deletableRecords); } } catch (Exception ex) { // 异常处理(可添加日志记录) throw new RuntimeException("日历新增失败", ex); } finally { latch.countDown(); // 任务完成计数 } })); try { // 等待所有任务完成(设置超时时间避免死锁) latch.await(30, TimeUnit.MINUTES); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException("任务执行超时", ex); } finally { executor.shutdown(); // 关闭线程池 } // 批量操作数据库 if(CollectionUtil.isNotEmpty(toDelete)){ List<ScheduleShiftCalendar> delTmpList = new ArrayList<>(toDelete); // 保存本次执行结果(保持原有分批保存逻辑) for(List<ScheduleShiftCalendar> tmpList : ListUtil.split(delTmpList, 2000)) { batchPhysicalDelete(tmpList); } } if(CollectionUtil.isNotEmpty(toInsert)){ List<ScheduleShiftCalendar> addTmpList = new ArrayList<>(toInsert); // 保存本次执行结果(保持原有分批保存逻辑) for(List<ScheduleShiftCalendar> tmpList : ListUtil.split(addTmpList, 2000)) { batchInsert(tmpList); } } // 获取当前登录人 ResponseResult<HaoSmartUserDTO> userInfo = iUserService.getUserInfo(); if (userInfo.getErrcode().equals(ErrorCode.OK)&&ObjectUtil.isNotEmpty(userInfo)&&ObjectUtil.isNotEmpty(userInfo.getData())) { String prongNo = userInfo.getData().getProngNo(); weiXinUtil.sendRouteMessage(prongNo,"您创建的日历已完成,请查看"); } } /** * 生成班次日历记录 */ private List<ScheduleShiftCalendar> generateShiftCalendars(ScheduleShiftCalendarCreateVO createVO, boolean addNormalModel) { List<ScheduleShiftCalendar> result = new ArrayList<>(); Date currentDate = createVO.getStartCalDate(); List<String> shiftModelCodes = createVO.getShiftModelCreateVOList().stream() .map(ShiftModelCreateVO::getShiftModelCode) .filter(Objects::nonNull) .distinct() .collect(Collectors.toList()); // 获取班次模型详情 List<ShiftModelDTO> shiftModels = shiftModelService.findByShiftModelCodeList(shiftModelCodes, null); if (addNormalModel) { shiftModels = shiftModels.stream() .filter(m -> ShiftModelTypeEnum.SPECIAL.getCode().equals(m.getShiftModelType())) .collect(Collectors.toList()); } // 构建班次映射 Map<String, Pair<String, String>> shiftMap = createVO.getShiftModelCreateVOList().stream() .flatMap(model -> model.getShiftVOList().stream() .flatMap(shiftVO -> shiftVO.getShiftCreateVOList().stream())) .collect(Collectors.toMap( ShiftCreateVO::getShiftCode, shift -> Pair.of(shift.getShiftCode(), shift.getShiftName()) )); // 生成日历记录 for (ShiftModelDTO model : shiftModels) { for (ShiftNameDTO shift : model.getShiftList()) { for (ShiftDTO shiftDetail : shift.getShiftDTOList()) { ScheduleShiftCalendar calendar = new ScheduleShiftCalendar(); calendar.setTaskCode(createVO.getTaskCode()); calendar.setTaskVersion(createVO.getTaskVersion()); calendar.setCalDate(currentDate); calendar.setWorkCenterCode(createVO.getWorkCenterCode()); calendar.setWorkCenterName(createVO.getWorkCenterName()); calendar.setShiftModelType(model.getShiftModelType()); calendar.setShiftModelCode(model.getShiftModelCode()); calendar.setShiftModelName(model.getShiftModelName()); calendar.setShiftCode(shiftDetail.getShiftCode()); calendar.setShiftName(shiftDetail.getShiftName()); // 处理跨天时间 String calDateStr = MomDateUtil.currentDateStr(currentDate, MomDateUtil.YYYYMMDD); String workStartTime = calDateStr+" "+MomDateUtil.currentDateStr(shiftDetail.getWorkStartTime(), MomDateUtil.HHMMSS); if(YesOrNoEnum.YES.getCode().equals(shiftDetail.getNextDay())){ // 如果跨天了 calDateStr = MomDateUtil.currentDateStr(MomDateUtil.addOrSubtractsDate(currentDate,1), MomDateUtil.YYYYMMDD); if(shiftDetail.getWorkStartTime().compareTo(shiftDetail.getWorkEndTime())<0){ workStartTime = calDateStr+" "+MomDateUtil.currentDateStr(shiftDetail.getWorkStartTime(), MomDateUtil.HHMMSS); } } String workEndTime = calDateStr+" "+MomDateUtil.currentDateStr(shiftDetail.getWorkEndTime(), MomDateUtil.HHMMSS); calendar.setWorkStartTime(MomDateUtil.covertToDate(workStartTime, MomDateUtil.YYYYMMDDHHMMSS)); calendar.setWorkEndTime(MomDateUtil.covertToDate(workEndTime, MomDateUtil.YYYYMMDDHHMMSS)); calendar.setTimeDuration(shiftDetail.getTimeDuration()); calendar.setDefaultFlag(StringUtils.defaultIfBlank(createVO.getDefaultFlag(), YesOrNoEnum.YES.getCode())); // 设置班组信息 Pair<String, String> teamInfo = shiftMap.get(shiftDetail.getShiftCode()); if (teamInfo != null) { calendar.setTeamCode(teamInfo.getKey()); calendar.setTeamName(teamInfo.getValue()); } result.add(calendar); } } } // 检查时间重叠 checkDateOverlapping(result); return result; } // 获取日期范围内的所有日期 public static List<Date> getDateRange(Date startDate, Date endDate) { List<Date> dates = new ArrayList<>(); Date current = startDate; while (!current.after(endDate)) { dates.add(current); current = MomDateUtil.addOrSubtractsDate(current, 1); } return dates; } //end @Transactional(rollbackFor = Exception.class) public List<ScheduleShiftCalendar> bind(ScheduleShiftCalendarCreateVO scheduleShiftCalendarCreateVO,boolean addNormalModel) { List<ScheduleShiftCalendar> scheduleShiftCalendarList = new ArrayList<>(); List<String> shiftModelCodeList = scheduleShiftCalendarCreateVO.getShiftModelCreateVOList() .stream() .map(ShiftModelCreateVO::getShiftModelCode) .filter(Objects::nonNull) .distinct().collect(Collectors.toList()); //group List<ShiftCreateVO> shiftCreateVOList = scheduleShiftCalendarCreateVO.getShiftModelCreateVOList() .stream() .flatMap(e-> e.getShiftVOList().stream().flatMap(f-> f.getShiftCreateVOList().stream())) .collect(Collectors.toList()); Map<String, Pair<String,String>> shiftMap = shiftCreateVOList.stream() .collect(Collectors.toMap(ShiftCreateVO::getShiftCode,item -> Pair.of(item.getShiftCode(),item.getShiftName()))); List<ShiftModelDTO> shiftModelList = shiftModelService.findByShiftModelCodeList(shiftModelCodeList,null); if(addNormalModel){ shiftModelList = shiftModelList.stream().filter(f-> ShiftModelTypeEnum.SPECIAL.getCode().equals(f.getShiftModelType())).collect(Collectors.toList()); } shiftModelList.forEach(e-> e.getShiftList().forEach(f-> f.getShiftDTOList().forEach(g->{ ScheduleShiftCalendar scheduleShiftCalendar = new ScheduleShiftCalendar(); scheduleShiftCalendar.setTaskCode(scheduleShiftCalendarCreateVO.getTaskCode()); scheduleShiftCalendar.setTaskVersion(scheduleShiftCalendarCreateVO.getTaskVersion()); scheduleShiftCalendar.setCalDate(scheduleShiftCalendarCreateVO.getCalDate()); scheduleShiftCalendar.setWorkCenterCode(scheduleShiftCalendarCreateVO.getWorkCenterCode()); scheduleShiftCalendar.setWorkCenterName(scheduleShiftCalendarCreateVO.getWorkCenterName()); scheduleShiftCalendar.setShiftModelType(e.getShiftModelType()); scheduleShiftCalendar.setShiftModelCode(e.getShiftModelCode()); scheduleShiftCalendar.setShiftModelName(e.getShiftModelName()); scheduleShiftCalendar.setShiftCode(g.getShiftCode()); scheduleShiftCalendar.setShiftName(g.getShiftName()); String calDateStr = MomDateUtil.currentDateStr(scheduleShiftCalendarCreateVO.getCalDate(), MomDateUtil.YYYYMMDD); String workStartTime = calDateStr+" "+MomDateUtil.currentDateStr(g.getWorkStartTime(), MomDateUtil.HHMMSS); if(YesOrNoEnum.YES.getCode().equals(g.getNextDay())){ // 如果跨天了 calDateStr = MomDateUtil.currentDateStr(MomDateUtil.addOrSubtractsDate(scheduleShiftCalendarCreateVO.getCalDate(),1), MomDateUtil.YYYYMMDD); if(g.getWorkStartTime().compareTo(g.getWorkEndTime())<0){ workStartTime = calDateStr+" "+MomDateUtil.currentDateStr(g.getWorkStartTime(), MomDateUtil.HHMMSS); } } String workEndTime = calDateStr+" "+MomDateUtil.currentDateStr(g.getWorkEndTime(), MomDateUtil.HHMMSS); scheduleShiftCalendar.setWorkStartTime(MomDateUtil.covertToDate(workStartTime,MomDateUtil.YYYYMMDDHHMMSS)); scheduleShiftCalendar.setWorkEndTime(MomDateUtil.covertToDate(workEndTime,MomDateUtil.YYYYMMDDHHMMSS)); scheduleShiftCalendar.setTimeDuration(g.getTimeDuration()); if(StringUtils.isBlank(scheduleShiftCalendarCreateVO.getDefaultFlag())){ scheduleShiftCalendar.setDefaultFlag(YesOrNoEnum.YES.getCode()); } //班组 Pair<String,String> teamPair = shiftMap.get(g.getShiftCode()); if(ObjectUtil.isNotNull(teamPair)){ scheduleShiftCalendar.setTeamCode(teamPair.getKey()); scheduleShiftCalendar.setShiftName(teamPair.getValue()); } scheduleShiftCalendarList.add(scheduleShiftCalendar); }))); //校验时间重叠;因为涉及到跨天日期,所以在此处才校验 checkDateOverlapping(scheduleShiftCalendarList); if(!CollectionUtils.isEmpty(scheduleShiftCalendarList)){ batchInsert(scheduleShiftCalendarList); } return scheduleShiftCalendarList; } /** * 校验时间重叠 * @param scheduleShiftCalendarList scheduleShiftCalendarList */ private void checkDateOverlapping(List<ScheduleShiftCalendar> scheduleShiftCalendarList) { for(int i = 0; i<scheduleShiftCalendarList.size();i++){ Date start1 = scheduleShiftCalendarList.get(i).getWorkStartTime(); Date end1 = scheduleShiftCalendarList.get(i).getWorkEndTime(); for(int j = i+1; j<scheduleShiftCalendarList.size();j++){ Date start2 = scheduleShiftCalendarList.get(j).getWorkStartTime(); Date end2 = scheduleShiftCalendarList.get(j).getWorkEndTime(); if(MomDateUtil.isOverlapping(start1,end1,start2,end2)){ throw BusinessException.e(ErrorCode.ERROR,"日历绑定失败,班次模型中时间段%s-%s与时间段%s-%s有重叠" ,MomDateUtil.currentDateStr(start1, MomDateUtil.HHMMSS) ,MomDateUtil.currentDateStr(end1, MomDateUtil.HHMMSS) ,MomDateUtil.currentDateStr(start2, MomDateUtil.HHMMSS) ,MomDateUtil.currentDateStr(end2, MomDateUtil.HHMMSS)); } } } } @Override @Transactional(rollbackFor = Exception.class) public List<ScheduleShiftCalendar> updateById(ScheduleShiftCalendarUpdateVO updateVO) { updateVO.setCalDate(updateVO.getStartCalDate()); ScheduleShiftCalendarQueryVO vo = new ScheduleShiftCalendarQueryVO(); vo.setCalDate(updateVO.getCalDate()); vo.setWorkCenterCode(updateVO.getWorkCenterCode()); vo.setDefaultFlag(YesOrNoEnum.YES.getCode()); List<ScheduleShiftCalendarDTO> list = list(vo); // 可以修改的列表 List<ScheduleShiftCalendarDTO> canModifyList = list.stream().filter(f->BusinessConstants.DB_STR_DEFAULT.equals(f.getTaskVersion())).collect(Collectors.toList()); // 不可修改的列表 List<ScheduleShiftCalendarDTO> cannotModifyList = list.stream().filter(f->!BusinessConstants.DB_STR_DEFAULT.equals(f.getTaskVersion())).collect(Collectors.toList()); // 不可以修改的已保存的班次模型code List<String> cannotModifySaveShiftModelCodeList = cannotModifyList.stream().map(ScheduleShiftCalendarDTO::getShiftModelCode).distinct().collect(Collectors.toList()); // 本次修改的班次模型code List<String> updateShiftModelCodeList = updateVO.getShiftModelCreateVOList().stream().map(ShiftModelCreateVO::getShiftModelCode).distinct().collect(Collectors.toList()); // 去除不可修改的班次模型 List<String> canModifyShiftModelCodeList = updateShiftModelCodeList.stream().filter(f->!cannotModifySaveShiftModelCodeList.contains(f)).collect(Collectors.toList()); List<ShiftModelCreateVO> sourceList = updateVO.getShiftModelCreateVOList(); List<ShiftModelCreateVO> canModifySourceList = sourceList.stream().filter(item->canModifyShiftModelCodeList.contains(item.getShiftModelCode())).collect(Collectors.toList()); Map<String,ShiftModelCreateVO> shiftModelMap = canModifySourceList.stream().collect(Collectors.toMap(ShiftModelCreateVO::getShiftModelCode, Function.identity())); // 先删除 batchPhysicalDelete(BeanUtil.copyToList(canModifyList, ScheduleShiftCalendar.class)); // 再保存 List<ShiftModelCreateVO> shiftModelCreateVOList = canModifyShiftModelCodeList.stream().map(m->{ ShiftModelCreateVO shiftModelCreateVO = new ShiftModelCreateVO(); shiftModelCreateVO.setShiftModelCode(m); ShiftModelCreateVO resourceShiftModelCreateVO = shiftModelMap.get(m); shiftModelCreateVO.setShiftVOList(resourceShiftModelCreateVO.getShiftVOList()); return shiftModelCreateVO; }).collect(Collectors.toList()); updateVO.setShiftModelCreateVOList(shiftModelCreateVOList); return bind(updateVO,list.stream().anyMatch(m->ShiftModelTypeEnum.SPECIAL.getCode().equals(m.getShiftModelType()))); } @Override @Transactional(rollbackFor = Exception.class) public void updateEffectAndDelInvalid(List<ScheduleShiftCalendarDTO> currentScheduleVersionCalendarList, List<ScheduleShiftCalendarDTO> defalutCalendarList, List<ScheduleShiftCalendarDTO> otherScheduleVersionCalendarList ) { // 删除版本未使用日历数据数据 List<ScheduleShiftCalendarDTO> delCalendarList = currentScheduleVersionCalendarList.stream().filter(e->!defalutCalendarList.contains(e)).collect(Collectors.toList()); if(!CollectionUtils.isEmpty(delCalendarList)){ otherScheduleVersionCalendarList.addAll(delCalendarList); } if(!CollectionUtils.isEmpty(defalutCalendarList)){ // 查询是否有默认的数据,先删除 后更新 Date minCalDate = defalutCalendarList.stream().min(Comparator.comparing(ScheduleShiftCalendarDTO::getCalDate)) .orElseThrow(()->BusinessException.e(ErrorCode.ERROR,"日历数据错误")).getCalDate(); Date maxCalDate = defalutCalendarList.stream().max(Comparator.comparing(ScheduleShiftCalendarDTO::getCalDate)) .orElseThrow(()->BusinessException.e(ErrorCode.ERROR,"日历数据错误")).getCalDate(); List<String> workcenterList = defalutCalendarList.stream().map(ScheduleShiftCalendarDTO::getWorkCenterCode).distinct().collect(Collectors.toList()); ScheduleShiftCalendarQueryVO vo = new ScheduleShiftCalendarQueryVO(); vo.setStartCalDate(TimeUtil.convertedDate2LocalDateTime(minCalDate).toLocalDate()); vo.setEndCalDate(TimeUtil.convertedDate2LocalDateTime(maxCalDate).toLocalDate()); vo.setWorkCenterCodeList(workcenterList); vo.setTaskCode(BusinessConstants.DB_STR_DEFAULT); vo.setDefaultFlag(YesOrNoEnum.YES.getCode()); List<ScheduleShiftCalendarDTO> defaultList = list(vo); otherScheduleVersionCalendarList.addAll(defaultList); } if(!CollectionUtils.isEmpty(otherScheduleVersionCalendarList)){ batchPhysicalDelete(BeanUtil.copyToList(otherScheduleVersionCalendarList, ScheduleShiftCalendar.class)); } if(!CollectionUtils.isEmpty(defalutCalendarList)){ batchUpdate(BeanUtil.copyToList(defalutCalendarList, ScheduleShiftCalendar.class)); } } @Override public List<ScheduleShiftCalendarDTO> list(ScheduleShiftCalendarQueryVO scheduleShiftCalendarQueryVO) { List<ScheduleShiftCalendar> list = super.list(assembleQueryWrapper(scheduleShiftCalendarQueryVO)); return BeanUtil.copyToList(list, ScheduleShiftCalendarDTO.class); } @Override public List<WorkcenterShiftCalendarDTO> query(String taskCode, String taskVersion,Pair<LocalDate,LocalDate> datePair, List<String> workCenterCodeList) { // 排程开始日期 LocalDate startDate = datePair.getKey(); // 排程结束日期 LocalDate endDate = datePair.getValue(); //当前版本日历数据 List<ScheduleShiftCalendarDTO> versionDataList = findScheduleShiftCalendarList(taskCode,taskVersion,startDate,endDate,workCenterCodeList); Map<Pair<String,String>,List<ScheduleShiftCalendarDTO>> mapping = versionDataList.stream().collect(Collectors.groupingBy(d->Pair.of(d.getWorkCenterCode(),d.getWorkCenterName()))); //结果数据组装 List<WorkcenterShiftCalendarDTO> resultList = new ArrayList<>(); mapping.forEach((k,v)->{ WorkcenterShiftCalendarDTO workCenter = new WorkcenterShiftCalendarDTO(); workCenter.setWorkcenterCode(k.getKey()); workCenter.setWorkcenterName(k.getValue()); workCenter.setScheduleShiftCalendarList(v); resultList.add(workCenter); }); return resultList; } @Override @Transactional(rollbackFor = Exception.class) public void syncCalendar(ScheduleTask scheduleTask) { String taskVersion = "0"; //结果 List<ScheduleShiftCalendar> resultList = new ArrayList<>(); // 获取所有工作中心 List<WorkCenterDTO> workCenterList = workcenterQueryService.findAll(); //遍历树结构,获取叶子节点工作中心数据 List<WorkCenterDTO> leafNodeList = workcenterQueryService.findLeafNodeList(); leafNodeList.addAll(workCenterList); List<ScheduleShiftCalendar> list = getGeneralCalendarListForSync(scheduleTask); //当前workCenter-日历Map Map<Date, Map<String, List<ScheduleShiftCalendar>>> currentWorkCenterMapping = list.stream().collect(Collectors.groupingBy(ScheduleShiftCalendar::getCalDate, Collectors.groupingBy(ScheduleShiftCalendar::getWorkCenterCode))); //循环最下层的子节点 List<String> workCenterCodeList = leafNodeList.stream().map(WorkCenterDTO::getWorkCenterCode).collect(Collectors.toList()); //查询已存在日历 QueryWrapper<ScheduleShiftCalendar> scheduleShiftCalendarQueryWrapper = new QueryWrapper<>(); scheduleShiftCalendarQueryWrapper.lambda().in(ScheduleShiftCalendar::getWorkCenterCode,workCenterCodeList) .eq(ScheduleShiftCalendar::getDelFlag,BaseModel.DEL_FLAG_NORMAL); List<ScheduleShiftCalendar> alCalendarList = super.list(scheduleShiftCalendarQueryWrapper); Map<Pair<String, Date>, List<ScheduleShiftCalendar>> calendarMap = alCalendarList.stream().collect(Collectors.groupingBy(i -> Pair.of(i.getWorkCenterCode(), i.getCalDate()))); for(WorkCenterDTO workCenter:leafNodeList){ String workCenterCode = workCenter.getWorkCenterCode(); Long parentId = workCenter.getParentId(); if(ObjectUtil.isEmpty(parentId)){ continue; } //循环查日历 List<ScheduleShiftCalendar> calendarList = new ArrayList<>(); for(Date key:currentWorkCenterMapping.keySet()){ Map<String, List<ScheduleShiftCalendar>> stringListMap = currentWorkCenterMapping.get(key); List<ScheduleShiftCalendar> tmpList = loop2FindCalendar(workCenterCode,parentId,workCenterList,stringListMap); calendarList.addAll(tmpList); } //将查到的日历批量复制 List<ScheduleShiftCalendar> copyCalendarList = Lists.newArrayList(); for(ScheduleShiftCalendar source:calendarList){ if(ObjectUtil.isNotEmpty(calendarMap.get(Pair.of(workCenterCode,source.getCalDate())))){ continue; } ScheduleShiftCalendar calendar = new ScheduleShiftCalendar(); calendar.setTaskCode(scheduleTask.getTaskCode()); calendar.setTaskVersion(taskVersion); calendar.setWorkCenterCode(workCenterCode); calendar.setWorkCenterName(workCenter.getWorkCenterName()); calendar.setDefaultFlag(YesOrNoEnum.YES.getCode()); calendar.setShiftName(source.getShiftName()); calendar.setShiftCode(source.getShiftCode()); calendar.setTeamName(source.getTeamName()); calendar.setTeamCode(source.getTeamCode()); calendar.setCalDate(source.getCalDate()); calendar.setShiftModelType(source.getShiftModelType()); calendar.setShiftModelCode(source.getShiftModelCode()); calendar.setShiftModelName(source.getShiftModelName()); calendar.setWorkStartTime(source.getWorkStartTime()); calendar.setWorkEndTime(source.getWorkEndTime()); calendar.setTimeDuration(source.getTimeDuration()); copyCalendarList.add(calendar); } resultList.addAll(copyCalendarList); } for (List<ScheduleShiftCalendar> calendarTmp : ListUtil.split(resultList, 2000)) { super.saveBatch(calendarTmp); } } private List<ScheduleShiftCalendarDTO> findScheduleShiftCalendarList(String taskCode,String taskVersion, LocalDate startDate,LocalDate endDate, List<String> workCenterCode){ ScheduleShiftCalendarQueryVO vo = new ScheduleShiftCalendarQueryVO(); vo.setTaskCode(taskCode); vo.setTaskVersion(taskVersion); vo.setStartCalDate(startDate); vo.setEndCalDate(endDate); vo.setWorkCenterCodeList(workCenterCode); // 查询时间范围内所有日历 return list(vo); } @Override public int countByShiftModelCode(String shiftModelCode) { LambdaQueryWrapper<ScheduleShiftCalendar> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(ScheduleShiftCalendar::getShiftModelCode,shiftModelCode) .eq(ScheduleShiftCalendar::getDelFlag,BaseModel.DEL_FLAG_NORMAL); return super.count(queryWrapper); } @Override public Map<String,List<CalDateShiftCalendarDTO>> findInfos(ScheduleShiftCalendarQueryVO vo) { // 当前月开始第一天 vo.setStartCalDate(vo.getCalDateOfMonth().with(TemporalAdjusters.firstDayOfMonth())); // 当前月最后一天 vo.setEndCalDate(vo.getCalDateOfMonth().with(TemporalAdjusters.lastDayOfMonth())); vo.setDefaultFlag(YesOrNoEnum.YES.getCode()); List<ScheduleShiftCalendarDTO> list = list(vo); return assembleSearchResult(list); } @Override public Pair<String,Map<String,List<CalDateShiftCalendarDTO>>> findWiInfoList(ScheduleShiftCalendarQueryVO vo) { if(ObjectUtil.isNull(vo.getCalDateOfMonth())){ vo.setCalDateOfMonth(LocalDate.now()); } LocalDate startDate = vo.getCalDateOfMonth().with(TemporalAdjusters.firstDayOfMonth()) ; LocalDate endDate = vo.getCalDateOfMonth().with(TemporalAdjusters.lastDayOfMonth()); //当前版本日历数据 List<ScheduleShiftCalendarDTO> versionDataList = findScheduleShiftCalendarList(vo.getTaskCode(), vo.getTaskVersion(),startDate,endDate, Lists.newArrayList(vo.getWorkCenterCode())); Map<String,List<CalDateShiftCalendarDTO>> value = assembleSearchResult(versionDataList); return Pair.of(TimeUtil.convertedLocalDate2String(vo.getCalDateOfMonth()),value); } /** * 拼装查询结构数据 * @param list 日历查询结果 * @return 返回页面结果 */ private Map<String,List<CalDateShiftCalendarDTO>> assembleSearchResult(List<ScheduleShiftCalendarDTO> list){ List<String> shiftModelCodeList = list.stream().map(ScheduleShiftCalendarDTO::getShiftModelCode).distinct().collect(Collectors.toList()); List<ShiftModelDTO> shiftModelDTOList = shiftModelService.findByShiftModelCodeList(shiftModelCodeList,null); Map<Date, List<ScheduleShiftCalendarDTO>> map = list.stream().collect(Collectors.groupingBy(ScheduleShiftCalendarDTO::getCalDate)); Map<String,List<CalDateShiftCalendarDTO>> resultMap = new HashMap<>(16); map.forEach((k,v)->{ Map<CalDateShiftCalendarDTO,List<ScheduleShiftCalendarDTO>> modelShiftMap = v.stream().collect(Collectors.groupingBy(e->{ CalDateShiftCalendarDTO calDateShiftCalendarDTO = new CalDateShiftCalendarDTO(); if(!BusinessConstants.DB_STR_DEFAULT.equals(e.getTaskCode()) && !BusinessConstants.DB_STR_DEFAULT.equals(e.getTaskVersion())){ calDateShiftCalendarDTO.setTaskCode(e.getTaskCode()); calDateShiftCalendarDTO.setTaskVersion(e.getTaskVersion()); } calDateShiftCalendarDTO.setShiftModelCode(e.getShiftModelCode()); calDateShiftCalendarDTO.setShiftModelName(e.getShiftModelName()); calDateShiftCalendarDTO.setDefaultFlag(e.getDefaultFlag()); calDateShiftCalendarDTO.setShiftModelType(shiftModelDTOList.stream() .filter(f->f.getShiftModelCode().equals(e.getShiftModelCode())) .findFirst().orElse(new ShiftModelDTO()).getShiftModelType()); return calDateShiftCalendarDTO; })); List<CalDateShiftCalendarDTO> resultList = new ArrayList<>(); modelShiftMap.forEach((obj,calendarList)->{ long timeDuration = calendarList.stream().mapToLong(ScheduleShiftCalendarDTO::getTimeDuration).sum(); obj.setTimeDuration(timeDuration/60000); resultList.add(obj); List<CalDateShiftCalendarDTO> calDateShiftCalendarDTOList = resultList.stream() .sorted(Comparator.comparing(CalDateShiftCalendarDTO::getShiftModelType)) .collect(Collectors.toList()); String dateKey = TimeUtil.convertedLocalDate2String(TimeUtil.convertedDate2LocalDateTime(k).toLocalDate()); // 赋值 resultMap.computeIfPresent(dateKey, (key, value) -> calDateShiftCalendarDTOList); // 初始化 resultMap.computeIfAbsent(dateKey, key -> calDateShiftCalendarDTOList); }); }); return resultMap; } @Override @Transactional(rollbackFor = Exception.class) public void deleteByCalDate(String startCalDate,String endCalDate,String workCenterCode) { // 删除非版本日历 ScheduleShiftCalendarQueryVO scheduleShiftCalendarQueryVO = new ScheduleShiftCalendarQueryVO(); scheduleShiftCalendarQueryVO.setStartCalDate(TimeUtil.convertedString2LocalDate(startCalDate)); scheduleShiftCalendarQueryVO.setEndCalDate(TimeUtil.convertedString2LocalDate(endCalDate)); scheduleShiftCalendarQueryVO.setWorkCenterCode(workCenterCode); scheduleShiftCalendarQueryVO.setTaskCode(BusinessConstants.DB_STR_DEFAULT); scheduleShiftCalendarQueryVO.setTaskVersion(BusinessConstants.DB_STR_DEFAULT); scheduleShiftCalendarQueryVO.setDefaultFlag(YesOrNoEnum.YES.getCode()); List<ScheduleShiftCalendarDTO> list = list(scheduleShiftCalendarQueryVO); batchPhysicalDelete(BeanUtil.copyToList(list, ScheduleShiftCalendar.class)); } @Override @Transactional(rollbackFor = Exception.class) public void wiCalendarInit(ScheduleTask scheduleTask,String taskVersion,List<String> sourceCodeList) { Set<String> stationCode = getStationCodeList(scheduleTask,sourceCodeList); List<ScheduleShiftCalendar> resultList = wiCalendarInitDataSearch2(scheduleTask, taskVersion,stationCode); super.saveBatch(resultList); } @Override @Transactional(rollbackFor = Exception.class) public void wiCalendarUpdate(ScheduleTask scheduleTask,String taskVersion,List<String> sourceCodeList) { Set<String> stationSet = new HashSet<>(); Set<String> stationCode = getStationCodeList(scheduleTask,sourceCodeList); //获取日历下的所有工位 List<String> stationCodeDb = scheduleShiftCalendarDao.getStationCode(scheduleTask.getTaskCode(),taskVersion); //剔除 stationCode.forEach(item->{ if(!stationCodeDb.contains(item)){ stationSet.add(item); } }); if(CollectionUtils.isEmpty(stationSet)){ return; } List<ScheduleShiftCalendar> resultList = wiCalendarInitDataSearch2(scheduleTask, taskVersion,stationSet); super.saveBatch(resultList); } public List<ScheduleShiftCalendar> wiCalendarInitDataSearch2(ScheduleTask scheduleTask,String taskVersion,Set<String> stationCode) { //结果 List<ScheduleShiftCalendar> resultList = new ArrayList<>(); // 获取所有工作中心 List<WorkCenterDTO> workCenterList = workcenterQueryService.findAll(); //遍历树结构,获取叶子节点工作中心数据 List<WorkCenterDTO> leafNodeList = workcenterQueryService.findLeafNodeList(); leafNodeList = leafNodeList.stream().filter(f->stationCode.contains(f.getWorkCenterCode())).collect(Collectors.toList()); List<ScheduleShiftCalendar> list = getGeneralCalendarList(scheduleTask); //当前workCenter-日历Map Map<String,List<ScheduleShiftCalendar>> currentWorkCenterMapping = list.stream().collect(Collectors.groupingBy(ScheduleShiftCalendar::getWorkCenterCode)); //循环最下层的子节点 for(WorkCenterDTO workCenter:leafNodeList){ String workCenterCode = workCenter.getWorkCenterCode(); Long parentId = workCenter.getParentId(); //循环查日历 List<ScheduleShiftCalendar> calendarList = loop2FindCalendar(workCenterCode,parentId,workCenterList,currentWorkCenterMapping); //将查到的日历批量复制 List<ScheduleShiftCalendar> copyCalendarList = Lists.newArrayList(); for(ScheduleShiftCalendar source:calendarList){ ScheduleShiftCalendar calendar = new ScheduleShiftCalendar(); calendar.setTaskCode(scheduleTask.getTaskCode()); calendar.setTaskVersion(taskVersion); calendar.setWorkCenterCode(workCenterCode); calendar.setWorkCenterName(workCenter.getWorkCenterName()); calendar.setDefaultFlag(YesOrNoEnum.NO.getCode()); calendar.setShiftName(source.getShiftName()); calendar.setShiftCode(source.getShiftCode()); calendar.setTeamName(source.getTeamName()); calendar.setTeamCode(source.getTeamCode()); calendar.setCalDate(source.getCalDate()); calendar.setShiftModelType(source.getShiftModelType()); calendar.setShiftModelCode(source.getShiftModelCode()); calendar.setShiftModelName(source.getShiftModelName()); calendar.setWorkStartTime(source.getWorkStartTime()); calendar.setWorkEndTime(source.getWorkEndTime()); calendar.setTimeDuration(source.getTimeDuration()); copyCalendarList.add(calendar); } resultList.addAll(copyCalendarList); } return resultList; } private List<ScheduleShiftCalendar> getGeneralCalendarList(ScheduleTask scheduleTask){ QueryWrapper<ScheduleShiftCalendar> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda() .eq(ScheduleShiftCalendar::getTaskCode,BusinessConstants.DB_STR_DEFAULT) .eq(ScheduleShiftCalendar::getTaskVersion,BusinessConstants.DB_STR_DEFAULT) .ge(ScheduleShiftCalendar::getCalDate,scheduleTask.getStartDate()) .le(ScheduleShiftCalendar::getCalDate,MomDateUtil.addOrSubtractsMonth(scheduleTask.getStartDate(),4)); return super.list(queryWrapper); } private List<ScheduleShiftCalendar> getGeneralCalendarListForSync(ScheduleTask scheduleTask){ QueryWrapper<ScheduleShiftCalendar> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda() .eq(ScheduleShiftCalendar::getTaskCode,BusinessConstants.DB_STR_DEFAULT) .eq(ScheduleShiftCalendar::getTaskVersion,BusinessConstants.DB_STR_DEFAULT) .ge(ScheduleShiftCalendar::getCalDate, DateUtil.format(scheduleTask.getStartDate(),"yyyy-MM-dd")) .le(ScheduleShiftCalendar::getCalDate,DateUtil.format(scheduleTask.getEndDate(),"yyyy-MM-dd")); return super.list(queryWrapper); } private List<ScheduleShiftCalendar> loop2FindCalendar(String workCenterCode,Long parentId, List<WorkCenterDTO> workCenterList, Map<String,List<ScheduleShiftCalendar>> currentWorkCenterMapping){ List<ScheduleShiftCalendar> calendarList =currentWorkCenterMapping.get(workCenterCode); if(CollectionUtil.isEmpty(calendarList)){ //找上级 for(WorkCenterDTO parentWorkCenter :workCenterList){ if(parentId.compareTo(parentWorkCenter.getId())==0){ workCenterCode = parentWorkCenter.getWorkCenterCode(); parentId = parentWorkCenter.getParentId(); return loop2FindCalendar(workCenterCode,parentId,workCenterList,currentWorkCenterMapping); } } } return calendarList; } @Override @Transactional(rollbackFor = Exception.class) public void wiCalendarCopy(String taskCode, String sourceTaskVersion, String taskVersion) { // 查询原版本日历信息 QueryWrapper<ScheduleShiftCalendar> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(ScheduleShiftCalendar::getTaskCode, taskCode).eq(ScheduleShiftCalendar::getTaskVersion, sourceTaskVersion); List<ScheduleShiftCalendar> list = list(queryWrapper); list.forEach(e->{ e.setTaskVersion(taskVersion); e.setId(null); e.setVersion(null); }); batchRepositoryHelper.batchInsert(list); } @Override @Transactional(rollbackFor = Exception.class) public void delete(String taskCode) { scheduleShiftCalendarDao.deleteData(taskCode); } @Override @Transactional(rollbackFor = Exception.class) public void wiUpdate(ScheduleShiftCalendarWiUpdateVO scheduleShiftCalendarWiUpdateVO) { ScheduleShiftCalendarQueryVO vo = new ScheduleShiftCalendarQueryVO(); vo.setStartCalDate(scheduleShiftCalendarWiUpdateVO.getStartCalDate()); vo.setEndCalDate(scheduleShiftCalendarWiUpdateVO.getEndCalDate()); vo.setWorkCenterCode(scheduleShiftCalendarWiUpdateVO.getWorkCenterCode()); List<ScheduleShiftCalendarDTO> list = list(vo); // 删除列表 List<String> deleteShiftModelCodeList= scheduleShiftCalendarWiUpdateVO.getChangeEntries().getDeleteItems().stream() .map(ShiftModelCreateVO::getShiftModelCode).distinct().collect(Collectors.toList()); // 时间重叠校验列表 List<ScheduleShiftCalendar> checkList = new ArrayList<>(); if(!CollectionUtils.isEmpty(deleteShiftModelCodeList)){ // 删除数据列表 List<ScheduleShiftCalendarDTO> deleteList = list.stream().filter(e-> deleteShiftModelCodeList.contains(e.getShiftModelCode())) .collect(Collectors.toList()); // 锁定不能删除列表,增加到校验列表中 checkList.addAll(BeanUtil.copyToList(list.stream().filter(e->YesOrNoEnum.YES.getCode().equals(e.getDefaultFlag())) .collect(Collectors.toList()), ScheduleShiftCalendar.class)); // 删除 batchPhysicalDelete(BeanUtil.copyToList(deleteList, ScheduleShiftCalendar.class)); // 未修改列表 List<ScheduleShiftCalendarDTO> nochangeList = list.stream().filter(f->!deleteShiftModelCodeList.contains(f.getShiftModelCode())).collect(Collectors.toList()); if(!CollectionUtils.isEmpty(nochangeList)){ checkList.addAll(BeanUtil.copyToList(nochangeList, ScheduleShiftCalendar.class)); } } // 新增列表 List<ShiftModelCreateVO> increasedItems = scheduleShiftCalendarWiUpdateVO.getChangeEntries().getIncreasedItems(); if(!CollectionUtils.isEmpty(increasedItems)){ // 再保存 ScheduleShiftCalendarCreateVO scheduleShiftCalendarCreateVO = BeanUtil.copyProperties(scheduleShiftCalendarWiUpdateVO, ScheduleShiftCalendarCreateVO.class); scheduleShiftCalendarCreateVO.setDefaultFlag(YesOrNoEnum.NO.getCode()); scheduleShiftCalendarCreateVO.setShiftModelCreateVOList(increasedItems); checkList.addAll(create(scheduleShiftCalendarCreateVO)); } // 时间重叠校验 checkDateOverlapping(checkList); } @Override public List<InnerWorkShiftModelScheduleDTO> findByWorkcenterCodeAndCalDate(String workcenterCode, String calDate) { return baseMapper.findByWorkcenterCodeAndCalDate(workcenterCode, calDate); } @Override public List<InnerWorkShiftModelScheduleDTO> findListByShiftModelCodeAndWorkTime(String shiftModelCode, String calDate) { ScheduleShiftCalendarQueryVO scheduleShiftCalendarQueryVO = new ScheduleShiftCalendarQueryVO(); scheduleShiftCalendarQueryVO.setShiftModelCode(shiftModelCode); scheduleShiftCalendarQueryVO.setCalDateStr(calDate); return BeanUtil.copyToList(list(scheduleShiftCalendarQueryVO),InnerWorkShiftModelScheduleDTO.class); } @Override public List<ScheduleShiftCalendarDTO> queryByShiftModelCode(List<String> shiftModelCodeList, Date date) { QueryWrapper<ScheduleShiftCalendar> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().in(CollectionUtil.isNotEmpty(shiftModelCodeList),ScheduleShiftCalendar::getShiftModelCode, shiftModelCodeList) .eq(ObjectUtil.isNotNull(date),ScheduleShiftCalendar::getCalDate, date); List<ScheduleShiftCalendar> list = list(queryWrapper); return BeanUtil.copyToList(list, ScheduleShiftCalendarDTO.class); } @Override public void deleteCalendar(ScheduleTask scheduleTask, String taskVersion, List<String> lineCodeList) { Set<String> stationCode = getStationCodeList(scheduleTask,lineCodeList); scheduleShiftCalendarDao.deleteCalendar(scheduleTask.getTaskCode(), taskVersion, stationCode); } /** * 查询工作中心日历数据(当前获取不到,获取上级数据) * @param dataList 结果数据 * @param versionDataList 日历数据 * @param workCenterList 工作中心集合 * @param currentWorkCenterList 当前层级工作中心集合 */ private void findScheduleShiftCalendarDataList(List<ScheduleShiftCalendarDTO> dataList ,List<ScheduleShiftCalendarDTO> versionDataList ,List<WorkCenterDTO> workCenterList ,List<WorkCenterDTO> currentWorkCenterList ){ List<WorkCenterDTO> hasNoCalendarWorkcenterList = new ArrayList<>(); currentWorkCenterList.forEach(e -> { List<ScheduleShiftCalendarDTO> list = versionDataList.stream() .filter(f -> f.getWorkCenterCode().equals(e.getWorkCenterCode())) .collect(Collectors.toList()); if (!CollectionUtils.isEmpty(list)) { // 系统包含默认数据,再过滤非默认版本数据 list = list.stream().filter(m->BusinessConstants.DB_STR_DEFAULT.equals(m.getTaskVersion())).collect(Collectors.toList()); if (!CollectionUtils.isEmpty(list)) { dataList.addAll(list); } } else { hasNoCalendarWorkcenterList.add(e); } }); //获取上级工作中心日历数据 hasNoCalendarWorkcenterList.forEach(e->{ List<ScheduleShiftCalendarDTO> parentScheduleShiftCalendarDataList = findParentScheduleShiftCalendarDataList(e,versionDataList,workCenterList); List<ScheduleShiftCalendarDTO> copyList = BeanUtil.copyToList(parentScheduleShiftCalendarDataList,ScheduleShiftCalendarDTO.class); copyList.forEach(p->{ //父级日历工作中心信息赋值为当前叶子节点工作中心 p.setWorkCenterCode(e.getWorkCenterCode()); p.setWorkCenterName(e.getWorkCenterName()); }); dataList.addAll(copyList); }); } /** * 查询父级工作中心日历数据(当前获取不到,获取上级数据) * @param hasNoCalendarWorkcenter 当前未获取到日历的对象 * @param versionDataList 日历数据 * @param workcenterList 工作中心集合 */ private List<ScheduleShiftCalendarDTO> findParentScheduleShiftCalendarDataList(WorkCenterDTO hasNoCalendarWorkcenter , List<ScheduleShiftCalendarDTO> versionDataList , List<WorkCenterDTO> workcenterList){ Long parentId = hasNoCalendarWorkcenter.getParentId(); WorkCenterDTO parentWorkcenter = workcenterList.stream() .filter(e -> parentId.compareTo(e.getId()) == 0).findFirst().orElse(null); if( parentWorkcenter == null){ // 无上级工作中心 return new ArrayList<>(); } // 上级工作中心日历数据获取 List<ScheduleShiftCalendarDTO> parentScheduleShiftCalendarList = versionDataList.stream() .filter(e -> e.getWorkCenterCode().equals(parentWorkcenter.getWorkCenterCode())) .collect(Collectors.toList()); if(!CollectionUtils.isEmpty(parentScheduleShiftCalendarList) || parentWorkcenter.getParentId()==null){ // 获取到日历返回 或者 已经无上级的情况 return parentScheduleShiftCalendarList; }else{ //未获取到工作日历继续获取上层日历 return findParentScheduleShiftCalendarDataList(parentWorkcenter,versionDataList,workcenterList); } } /** * 组装查询条件包装器。 * * @param vo 查询条件对象,封装了所有的查询参数。 * @return QueryWrapper<ScheduleShiftCalendarDTO> 查询条件包装器,用于Hibernate或MyBatis等框架的查询操作。 */ private QueryWrapper<ScheduleShiftCalendar> assembleQueryWrapper(ScheduleShiftCalendarQueryVO vo) { QueryWrapper<ScheduleShiftCalendar> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(ScheduleShiftCalendar::getDelFlag, BaseModel.DEL_FLAG_NORMAL) .eq(StringUtils.isNotBlank(vo.getWorkCenterCode()), ScheduleShiftCalendar::getWorkCenterCode, vo.getWorkCenterCode()) .eq(StringUtils.isNotBlank(vo.getDefaultFlag()), ScheduleShiftCalendar::getDefaultFlag, vo.getDefaultFlag()) .in(!CollectionUtils.isEmpty(vo.getWorkCenterCodeList()), ScheduleShiftCalendar::getWorkCenterCode, vo.getWorkCenterCodeList()) .eq(ObjectUtil.isNotEmpty(vo.getCalDate()), ScheduleShiftCalendar::getCalDate, vo.getCalDate()) .eq(StringUtils.isNotBlank(vo.getTaskCode()), ScheduleShiftCalendar::getTaskCode, vo.getTaskCode()) .eq(StringUtils.isNotBlank(vo.getTaskVersion()), ScheduleShiftCalendar::getTaskVersion, vo.getTaskVersion()); if(ObjectUtil.isNotEmpty(vo.getStartCalDate()) && (ObjectUtil.isNotEmpty(vo.getEndCalDate()))){ queryWrapper.lambda().between(ScheduleShiftCalendar::getCalDate, vo.getStartCalDate(), vo.getEndCalDate()); } return queryWrapper; } private Set<String> getStationCodeList(ScheduleTask scheduleTask,List<String> sourceCodeList) { //找到总成,精工,压铸所有车间的计划单 List<SchedulingOrder> productOrderList = scheduleGateway.queryScheduleProductOrderList(sourceCodeList, scheduleTask.getWeek()); //计划数量为0,不参与排产 productOrderList = productOrderList.stream().filter(order -> order.getQuantity() > 0).collect(Collectors.toList()); //设备集合 Set<String> scheduleStationCodeSet = new HashSet<>(); //工艺路线 List<org.apache.commons.lang3.tuple.Pair<String, String>> processRoutePairList = Lists.newArrayList(); productOrderList.forEach(scheduleOrder -> processRoutePairList.add(org.apache.commons.lang3.tuple.Pair.of(scheduleOrder.getProcessRouteCode(), scheduleOrder.getProcessRouteVersion()))); List<ProcessRouteDetailsDTO> processRouteList = scheduleGateway.queryProcessRouteListFormMes(processRoutePairList); if (CollectionUtil.isEmpty(processRouteList) ) { throw BusinessException.e(ErrorCode.ERROR, "排程失败,未获取到工艺路线"); } if(processRoutePairList.size() != processRouteList.size()){ throw BusinessException.e(ErrorCode.ERROR, "排程失败,找到的工艺路线不全"); } Map<org.apache.commons.lang3.tuple.Pair<String, String>, ProcessRouteDetailsDTO> processRouteMapping = processRouteList.stream().collect(Collectors.toMap(item -> org.apache.commons.lang3.tuple.Pair.of(item.getProcessRouteCode(), item.getProcessRouteVersion()), Function.identity())); productOrderList.forEach(scheduleOrder -> { //工艺路线 ProcessRouteDetailsDTO processRoute = processRouteMapping.get(org.apache.commons.lang3.tuple.Pair.of(scheduleOrder.getProcessRouteCode(), scheduleOrder.getProcessRouteVersion())); List<OperationDTO> operationDTOList = processRoute.getOperationList(); operationDTOList.forEach(operationDTO -> operationDTO.getStationList().forEach(stationDTO -> scheduleStationCodeSet.add(stationDTO.getCode()))); }); return scheduleStationCodeSet; } @Component protected static class ScheduleShiftCalendarBatchRepositoryImpl extends BatchRepositoryHelperImpl<ScheduleShiftCalendarDao, ScheduleShiftCalendar> { } }
最新发布
09-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值