设备维修设备日历修改

parent 5f4dee85
...@@ -106,6 +106,11 @@ ...@@ -106,6 +106,11 @@
<version>2.15.2</version> <!-- 建议与jackson-databind版本一致 --> <version>2.15.2</version> <!-- 建议与jackson-databind版本一致 -->
</dependency> </dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
...@@ -16,6 +16,7 @@ import org.springframework.web.bind.annotation.*; ...@@ -16,6 +16,7 @@ import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture;
@RestController @RestController
@RequestMapping("/lanuch") @RequestMapping("/lanuch")
...@@ -44,8 +45,8 @@ public class LanuchController { ...@@ -44,8 +45,8 @@ public class LanuchController {
R<ProdSceneConfig> result = lanuchService.lanuch(sceneName, userId); R<ProdSceneConfig> result = lanuchService.lanuch(sceneName, userId);
// 异步更新物料和设备缓存 // 异步更新物料和设备缓存,不等待完成
updateMaterialAndEquipmentCacheAsync(); CompletableFuture.runAsync(this::updateMaterialAndEquipmentCacheAsync);
return result; return result;
} }
...@@ -56,7 +57,6 @@ public class LanuchController { ...@@ -56,7 +57,6 @@ public class LanuchController {
log.info("开始异步更新物料缓存"); log.info("开始异步更新物料缓存");
planResultService.getMaterials(); planResultService.getMaterials();
log.info("物料缓存更新完成"); log.info("物料缓存更新完成");
log.info("开始异步更新设备缓存"); log.info("开始异步更新设备缓存");
planResultService.InitCalendarToAllMachines(); planResultService.InitCalendarToAllMachines();
log.info("设备缓存更新完成"); log.info("设备缓存更新完成");
......
...@@ -13,19 +13,21 @@ import java.util.Map; ...@@ -13,19 +13,21 @@ import java.util.Map;
@RestController @RestController
@RequestMapping("/queryChromosome") @RequestMapping("/queryChromosome")
@Tag(name = "染色体数据查询", description = "根据实体名称查询染色体中的数据") @Tag(name = "甘特图数据查询", description = "甘特图数据查询")
public class ChromosomeDataController { public class ChromosomeDataController {
@Autowired @Autowired
private ChromosomeDataService chromosomeDataService; private ChromosomeDataService chromosomeDataService;
/** /**
* 通用接口,根据实体名称查询Chromosome中的数据,支持分页和条件过滤 * 通用接口,根据实体名称查询Chromosome中的数据,支持分页和条件过滤
* 示例: POST /queryChromosome/order/page * 示例:
* - 文件实体: POST /queryChromosome/order/page
* Body: { "sceneId": "SCENE001", "pageIndex": 1, "pageSize": 10, "conditions": [...] } * Body: { "sceneId": "SCENE001", "pageIndex": 1, "pageSize": 10, "conditions": [...] }
* - 数据库实体: POST /queryChromosome/user/page
* Body: { "pageIndex": 1, "pageSize": 10, "conditions": [...] }
* *
* @param entityName 实体名称 (如: order, entry, machine等) * @param entityName 实体名称 (如: order, entry, machine, user, department等)
* @param paged 分页和条件对象 * @param paged 分页和条件对象
* @return 分页数据 * @return 分页数据
*/ */
...@@ -34,24 +36,33 @@ public class ChromosomeDataController { ...@@ -34,24 +36,33 @@ public class ChromosomeDataController {
@PathVariable String entityName, @PathVariable String entityName,
@RequestBody Paged paged) { @RequestBody Paged paged) {
try {
// 获取sceneId(文件实体需要,数据库实体可选)
String sceneId = paged.getCondition("sceneId") != null ? String sceneId = paged.getCondition("sceneId") != null ?
paged.getCondition("sceneId").getFieldValue() : null; paged.getCondition("sceneId").getFieldValue() : null;
if (sceneId == null || sceneId.isEmpty()) { // 文件实体必须要有sceneId
return R.failed("sceneId不能为空"); if (isFileEntity(entityName) && (sceneId == null || sceneId.isEmpty())) {
return R.failed("文件实体查询时sceneId不能为空");
} }
Map<String, Object> result = chromosomeDataService.queryChromosomeDataWithConditions( Map<String, Object> result = chromosomeDataService.queryChromosomeDataWithConditions(
sceneId, entityName, paged); sceneId, entityName, paged);
return R.ok(result); return R.ok(result);
} catch (Exception e) {
return R.failed("查询失败: " + e.getMessage());
}
} }
/** /**
* 通用接口,根据实体名称查询Chromosome中的列表数据,支持条件过滤 * 通用接口,根据实体名称查询Chromosome中的列表数据,支持条件过滤
* 示例: POST /queryChromosome/order/list * 示例:
* - 文件实体: POST /queryChromosome/order/list
* Body: { "sceneId": "SCENE001", "conditions": [...] } * Body: { "sceneId": "SCENE001", "conditions": [...] }
* - 数据库实体: POST /queryChromosome/user/list
* Body: { "conditions": [...] }
* *
* @param entityName 实体名称 (如: order, entry, machine等) * @param entityName 实体名称 (如: order, entry, machine, user, department等)
* @param paged 条件对象 * @param paged 条件对象
* @return 列表数据 * @return 列表数据
*/ */
...@@ -60,178 +71,76 @@ public class ChromosomeDataController { ...@@ -60,178 +71,76 @@ public class ChromosomeDataController {
@PathVariable String entityName, @PathVariable String entityName,
@RequestBody Paged paged) { @RequestBody Paged paged) {
try {
// 获取sceneId(文件实体需要,数据库实体可选)
String sceneId = paged.getCondition("sceneId") != null ? String sceneId = paged.getCondition("sceneId") != null ?
paged.getCondition("sceneId").getFieldValue() : null; paged.getCondition("sceneId").getFieldValue() : null;
if (sceneId == null || sceneId.isEmpty()) { // 文件实体必须要有sceneId
return R.failed("sceneId不能为空"); if (isFileEntity(entityName) && (sceneId == null || sceneId.isEmpty())) {
return R.failed("文件实体查询时sceneId不能为空");
} }
Object result = chromosomeDataService.queryChromosomeData(sceneId, entityName); // 直接调用服务层的list查询方法
List<Object> result = chromosomeDataService.queryChromosomeDataList(sceneId, entityName, paged);
// 如果结果是List类型,则应用条件过滤
if (result instanceof List) {
List<Object> dataList = (List<Object>) result;
// 应用条件过滤 System.out.println("查询结果: " + result);
if (!paged.getConditions().isEmpty()) { if (result == null) {
// 这里可以调用服务层的过滤方法 return R.ok(Collections.emptyList(), "查询成功,但未找到匹配的数据");
Map<String, Object> filteredResult = chromosomeDataService.queryChromosomeDataWithConditions(
sceneId, entityName, paged);
dataList = (List<Object>) filteredResult.get("records");
} }
return R.ok(dataList); return R.ok(result);
} else { } catch (Exception e) {
return R.ok(Collections.singletonList(result)); return R.failed("查询失败: " + e.getMessage());
} }
} }
/** /**
* 通用接口,根据实体名称和ID查询Chromosome中的单个数据 * 通用接口,根据实体名称和ID查询Chromosome中的单个数据
* 示例: /queryChromosome/order/get?sceneId=xxx&id=123 * 示例:
* - 文件实体: GET /queryChromosome/order/get?sceneId=xxx&id=123
* - 数据库实体: GET /queryChromosome/user/get?id=123
* *
* @param sceneId 场景ID * @param sceneId 场景ID (文件实体必需,数据库实体可选)
* @param entityName 实体名称 (如: order, entry, machine等) * @param entityName 实体名称
* @param id 数据ID * @param id 数据ID
* @return 单个数据对象 * @return 单个数据对象
*/ */
@GetMapping("/{entityName}/get") @GetMapping("/{entityName}/get")
public R<Object> queryChromosomeDataById( public R<Object> queryChromosomeDataById(
@RequestParam String sceneId, @RequestParam(required = false) String sceneId,
@PathVariable String entityName, @PathVariable String entityName,
@RequestParam String id) { @RequestParam String id) {
Object result = chromosomeDataService.queryChromosomeData(sceneId, entityName);
// 如果结果是List类型,则根据ID查找特定项
if (result instanceof List) {
List<Object> dataList = (List<Object>) result;
Object item = dataList.stream()
.filter(obj -> {
try {
// 尝试获取对象的id字段
java.lang.reflect.Field idField = obj.getClass().getDeclaredField("id");
idField.setAccessible(true);
Object itemId = idField.get(obj);
return itemId != null && itemId.toString().equals(id);
} catch (Exception e) {
// 如果没有id字段或访问失败,尝试使用Id字段
try { try {
java.lang.reflect.Field idField = obj.getClass().getDeclaredField("Id"); // 文件实体必须要有sceneId
idField.setAccessible(true); if (isFileEntity(entityName) && (sceneId == null || sceneId.isEmpty())) {
Object itemId = idField.get(obj); return R.failed("文件实体查询时sceneId不能为空");
return itemId != null && itemId.toString().equals(id);
} catch (Exception ex) {
return false;
}
} }
})
.findFirst()
.orElse(null);
if (item != null) { Object result = chromosomeDataService.queryChromosomeDataById(sceneId, entityName, id);
return R.ok(item); if (result != null) {
return R.ok(result);
} else { } else {
return R.failed("未找到ID为 " + id + " 的数据"); return R.failed("未找到ID为 " + id + " 的数据");
} }
} else { } catch (Exception e) {
// 如果不是列表,直接返回结果 return R.failed("查询失败: " + e.getMessage());
return R.ok(result);
} }
} }
// /**
// * 通用接口,根据实体名称更新Chromosome中的数据 /**
// * 示例: POST /queryChromosome/order/update * 判断是否为文件实体
// * Body: { "sceneId": "SCENE001", "data": {...} } */
// * private boolean isFileEntity(String entityName) {
// * @param entityName 实体名称 (如: order, entry, machine等) // 这里列出所有文件实体的名称
// * @param requestBody 包含sceneId和更新数据的请求体 String[] fileEntities = {"order", "entry", "machine", "globaloperationinfo", "groupresult", "prodprocessexec"};
// * @return 更新结果 for (String fileEntity : fileEntities) {
// */ if (fileEntity.equalsIgnoreCase(entityName)) {
// @PostMapping("/{entityName}/update") return true;
// public R<String> updateChromosomeData( }
// @PathVariable String entityName, }
// @RequestBody Map<String, Object> requestBody) { return false;
// }
// String sceneId = (String) requestBody.get("sceneId");
// @SuppressWarnings("unchecked")
// Map<String, Object> data = (Map<String, Object>) requestBody.get("data");
//
// if (sceneId == null || sceneId.isEmpty()) {
// return R.failed("sceneId不能为空");
// }
//
// if (data == null || data.isEmpty()) {
// return R.failed("更新数据不能为空");
// }
//
// boolean success = chromosomeDataService.updateChromosomeData(sceneId, entityName, data);
// if (success) {
// return R.ok("数据更新成功");
// } else {
// return R.failed("数据更新失败");
// }
// }
//
// /**
// * 通用接口,根据实体名称批量操作Chromosome中的数据
// * 示例: POST /queryChromosome/order/batch
// * Body: { "sceneId": "SCENE001", "data": [...] }
// *
// * @param entityName 实体名称 (如: order, entry, machine等)
// * @param requestBody 包含sceneId和批量数据的请求体
// * @return 批量操作结果
// */
// @PostMapping("/{entityName}/batch")
// public R<String> batchChromosomeData(
// @PathVariable String entityName,
// @RequestBody Map<String, Object> requestBody) {
//
// String sceneId = (String) requestBody.get("sceneId");
// @SuppressWarnings("unchecked")
// List<Map<String, Object>> data = (List<Map<String, Object>>) requestBody.get("data");
//
// if (sceneId == null || sceneId.isEmpty()) {
// return R.failed("sceneId不能为空");
// }
//
// if (data == null || data.isEmpty()) {
// return R.failed("批量数据不能为空");
// }
//
// int successCount = chromosomeDataService.batchChromosomeData(sceneId, entityName, data);
// return R.ok("批量操作成功,共处理 " + data.size() + " 条数据,成功更新 " + successCount + " 条");
// }
//
// /**
// * 通用接口,根据实体名称删除Chromosome中的数据
// * 示例: POST /queryChromosome/order/delete
// * Body: { "sceneId": "SCENE001", "ids": [...] }
// *
// * @param entityName 实体名称 (如: order, entry, machine等)
// * @param requestBody 包含sceneId和要删除的数据ID列表的请求体
// * @return 删除操作结果
// */
// @PostMapping("/{entityName}/delete")
// public R<String> deleteChromosomeData(
// @PathVariable String entityName,
// @RequestBody Map<String, Object> requestBody) {
//
// String sceneId = (String) requestBody.get("sceneId");
// @SuppressWarnings("unchecked")
// List<Object> ids = (List<Object>) requestBody.get("ids");
//
// if (sceneId == null || sceneId.isEmpty()) {
// return R.failed("sceneId不能为空");
// }
//
// if (ids == null || ids.isEmpty()) {
// return R.failed("删除ID列表不能为空");
// }
//
// int deleteCount = chromosomeDataService.deleteChromosomeData(sceneId, entityName, ids);
// return R.ok("删除成功,共删除 " + ids.size() + " 条数据,实际删除 " + deleteCount + " 条");
// }
} }
\ No newline at end of file
package com.aps.controller.gantt; package com.aps.controller.gantt;
import cn.hutool.core.bean.BeanUtil;
import com.aps.common.util.ParamValidator; import com.aps.common.util.ParamValidator;
import com.aps.common.util.R; import com.aps.common.util.R;
import com.aps.entity.Algorithm.Chromosome; import com.aps.entity.Algorithm.Chromosome;
...@@ -38,16 +39,15 @@ public class MaintenanceWindowController { ...@@ -38,16 +39,15 @@ public class MaintenanceWindowController {
) )
) )
) )
public R<Chromosome> addMaintenanceWindow(@RequestBody Map<String, Object> params) { public R<String> addMaintenanceWindow(@RequestBody Map<String, Object> params) {
String sceneId = ParamValidator.getString(params, "sceneId", "场景ID"); String sceneId = ParamValidator.getString(params, "sceneId", "场景ID");
Long machineId = ParamValidator.getLong(params, "machineId", "机器ID"); Long machineId = ParamValidator.getLong(params, "machineId", "机器ID");
MaintenanceWindow maintenanceWindow = (MaintenanceWindow) params.get("maintenanceWindow"); MaintenanceWindow maintenanceWindow = BeanUtil.toBean(params.get("maintenanceWindow"), MaintenanceWindow.class);
Chromosome result = planResultService.AddMaintenanceWindow(sceneId, machineId, maintenanceWindow); Chromosome result = planResultService.AddMaintenanceWindow(sceneId, machineId, maintenanceWindow);
return R.ok(result); return R.ok("添加成功");
} }
@DeleteMapping("/delete") @PostMapping("/delete")
@Operation(summary = "删除维护窗口", description = "删除指定机器的维护窗口", @Operation(summary = "删除维护窗口", description = "删除指定机器的维护窗口",
requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody( requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "删除维护窗口请求参数", description = "删除维护窗口请求参数",
...@@ -60,13 +60,13 @@ public class MaintenanceWindowController { ...@@ -60,13 +60,13 @@ public class MaintenanceWindowController {
) )
) )
) )
public R<Chromosome> delMaintenanceWindow(@RequestBody Map<String, Object> params) { public R<String> delMaintenanceWindow(@RequestBody Map<String, Object> params) {
String sceneId = ParamValidator.getString(params, "sceneId", "场景ID"); String sceneId = ParamValidator.getString(params, "sceneId", "场景ID");
Long machineId = ParamValidator.getLong(params, "machineId", "机器ID"); Long machineId = ParamValidator.getLong(params, "machineId", "机器ID");
String maintenanceId = ParamValidator.getString(params, "maintenanceId", "维护窗口ID"); String maintenanceId = ParamValidator.getString(params, "maintenanceId", "维护窗口ID");
Chromosome result = planResultService.DelMaintenanceWindow(sceneId, machineId, maintenanceId); Chromosome result = planResultService.DelMaintenanceWindow(sceneId, machineId, maintenanceId);
return R.ok(result); return R.ok("删除成功");
} }
@PostMapping("/get") @PostMapping("/get")
......
...@@ -806,7 +806,7 @@ public class ResourceGanttController { ...@@ -806,7 +806,7 @@ public class ResourceGanttController {
return new ArrayList<>(); return new ArrayList<>();
} }
List<Machine> machineList = planResultService.InitCalendarToAllMachines2(sceneId); List<Machine> machineList = planResultService.InitCalendarToAllMachines3(schedule);
// 转换为 ResourceGanttVO 格式 // 转换为 ResourceGanttVO 格式
List<ResourceGanttVO> resourceGanttVOList = new ArrayList<>(); List<ResourceGanttVO> resourceGanttVOList = new ArrayList<>();
......
...@@ -22,7 +22,7 @@ public class Entry { ...@@ -22,7 +22,7 @@ public class Entry {
/** /**
* 基因编号 * 基因编号
*/ */
public int Id ; public int id ;
/** /**
* 所属组ID 需要按照前后顺序生产的工单给一组 * 所属组ID 需要按照前后顺序生产的工单给一组
*/ */
......
...@@ -12,6 +12,9 @@ public class MaintenanceWindow { ...@@ -12,6 +12,9 @@ public class MaintenanceWindow {
private String reason; private String reason;
private String equipCode;
private String equipName;
public MaintenanceWindow() {} public MaintenanceWindow() {}
public MaintenanceWindow(LocalDateTime startTime, LocalDateTime endTime, String reason) { public MaintenanceWindow(LocalDateTime startTime, LocalDateTime endTime, String reason) {
...@@ -70,6 +73,21 @@ public class MaintenanceWindow { ...@@ -70,6 +73,21 @@ public class MaintenanceWindow {
this.id = id; this.id = id;
} }
public String getEquipCode() {
return equipCode;
}
public void setEquipCode(String equipCode) {
this.equipCode = equipCode;
}
public String getEquipName() {
return equipName;
}
public void setEquipName(String equipName) {
this.equipName = equipName;
}
@Override @Override
......
// DataSourceType.java
package com.aps.entity.common;
public enum DataSourceType {
FILE("file"), // 文件数据源(现有)
DATABASE("db"); // 数据库数据源(新增)
private String type;
DataSourceType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public static DataSourceType fromString(String type) {
for (DataSourceType dataSource : DataSourceType.values()) {
if (dataSource.getType().equalsIgnoreCase(type)) {
return dataSource;
}
}
return FILE; // 默认返回FILE
}
}
\ No newline at end of file
// EntityConfig.java
package com.aps.entity.common;
public class EntityConfig {
private String entityName;
private DataSourceType dataSource;
private String tableName; // 数据库表名(如果是数据库源)
private String fieldName; // Chromosome字段名(如果是文件源)
private Class<?> entityClass; // 实体类(数据库实体使用)
// 构造方法
public EntityConfig() {}
public EntityConfig(String entityName, DataSourceType dataSource, String fieldName, String tableName, Class<?> entityClass) {
this.entityName = entityName;
this.dataSource = dataSource;
this.fieldName = fieldName;
this.tableName = tableName;
this.entityClass = entityClass;
}
// getter/setter
public String getEntityName() { return entityName; }
public void setEntityName(String entityName) { this.entityName = entityName; }
public DataSourceType getDataSource() { return dataSource; }
public void setDataSource(DataSourceType dataSource) { this.dataSource = dataSource; }
public String getTableName() { return tableName; }
public void setTableName(String tableName) { this.tableName = tableName; }
public String getFieldName() { return fieldName; }
public void setFieldName(String fieldName) { this.fieldName = fieldName; }
public Class<?> getEntityClass() { return entityClass; }
public void setEntityClass(Class<?> entityClass) { this.entityClass = entityClass; }
@Override
public String toString() {
return "EntityConfig{" +
"entityName='" + entityName + '\'' +
", dataSource=" + dataSource +
", tableName='" + tableName + '\'' +
", fieldName='" + fieldName + '\'' +
", entityClass=" + entityClass +
'}';
}
}
\ No newline at end of file
package com.aps.entity.common;
import com.aps.entity.ProdEquipment;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class EntityConfigConfiguration {
@Bean
public Map<String, EntityConfig> entityConfigMap() {
Map<String, EntityConfig> configMap = new HashMap<>();
// ========== 文件实体配置 ==========
addFileEntity(configMap, "order", "orders");
addFileEntity(configMap, "entry", "allOperations");
addFileEntity(configMap, "machine", "InitMachines");
addFileEntity(configMap, "globaloperationinfo", "globalOpList");
addFileEntity(configMap, "groupresult", "OperatRel");
// ========== 数据库实体配置 ==========
// 设备表配置
addDbEntity(configMap, "prod_equipment", "PROD_EQUIPMENT", ProdEquipment.class);
return configMap;
}
/**
* 添加文件实体配置
*/
private void addFileEntity(Map<String, EntityConfig> configMap, String entityName, String fieldName) {
EntityConfig config = new EntityConfig();
config.setEntityName(entityName);
config.setDataSource(DataSourceType.FILE);
config.setFieldName(fieldName);
config.setTableName(null);
config.setEntityClass(null);
configMap.put(entityName.toLowerCase(), config);
}
/**
* 添加数据库实体配置
*/
private void addDbEntity(Map<String, EntityConfig> configMap, String entityName, String tableName, Class<?> entityClass) {
EntityConfig config = new EntityConfig();
config.setEntityName(entityName);
config.setDataSource(DataSourceType.DATABASE);
config.setTableName(tableName);
config.setEntityClass(entityClass);
config.setFieldName(null);
configMap.put(entityName.toLowerCase(), config);
}
}
\ No newline at end of file
...@@ -300,7 +300,7 @@ if(finishedOrder==null||finishedOrder.size()==0) ...@@ -300,7 +300,7 @@ if(finishedOrder==null||finishedOrder.size()==0)
int opSequence = currentOp.getSequence(); int opSequence = currentOp.getSequence();
GAScheduleResult existingResult = chromosome.getResultOld().stream() GAScheduleResult existingResult = chromosome.getResultOld().stream()
.filter(r-> r.getOperationId() == currentOp.Id) .filter(r-> r.getOperationId() == currentOp.getId())
.findFirst().orElse(null); .findFirst().orElse(null);
if(existingResult!=null) { if(existingResult!=null) {
if(existingResult.isIsLocked()) if(existingResult.isIsLocked())
...@@ -429,7 +429,7 @@ if(finishedOrder==null||finishedOrder.size()==0) ...@@ -429,7 +429,7 @@ if(finishedOrder==null||finishedOrder.size()==0)
// System.out.println(" 标准模式:安排主处理+" + setupTime + "分钟换型=" + processingTimeTotal + "分钟"); // System.out.println(" 标准模式:安排主处理+" + setupTime + "分钟换型=" + processingTimeTotal + "分钟");
} }
GAScheduleResult existingResult = chromosome.getResultOld().stream().filter(r-> r.getOperationId() == operation.Id).findFirst().orElse(null); GAScheduleResult existingResult = chromosome.getResultOld().stream().filter(r-> r.getOperationId() == operation.getId()).findFirst().orElse(null);
if(existingResult!=null) if(existingResult!=null)
{ {
earliestStartTime = Math.max(earliestStartTime,existingResult.getDesignatedStartTime()); earliestStartTime = Math.max(earliestStartTime,existingResult.getDesignatedStartTime());
......
...@@ -313,8 +313,9 @@ if(routingIds.size()==0) ...@@ -313,8 +313,9 @@ if(routingIds.size()==0)
order.setRoutingId(headers1.getId()); order.setRoutingId(headers1.getId());
ProdLaunchOrder prodOrderMain= convertToLaunchOrder(order,""); ProdLaunchOrder prodOrderMain= convertToLaunchOrder(order,"");
List<RoutingDetailEquip> finalRoutingDetailEquips = routingDetailEquips;
List<ProdProcessExec> processExecList = RoutingDetails.stream() List<ProdProcessExec> processExecList = RoutingDetails.stream()
.map(detail -> lanuchService.createProcessExec(prodOrderMain, detail, sceneId)) .map(detail -> lanuchService.createProcessExec(prodOrderMain, detail, sceneId, finalRoutingDetailEquips))
.collect(Collectors.toList()); .collect(Collectors.toList());
List<ProdEquipment> ProdEquipmentList= lanuchService.batchInsertEquipMent(routingDetailEquips, sceneId,processExecList,false); List<ProdEquipment> ProdEquipmentList= lanuchService.batchInsertEquipMent(routingDetailEquips, sceneId,processExecList,false);
......
...@@ -543,6 +543,8 @@ public class RoutingDataService { ...@@ -543,6 +543,8 @@ public class RoutingDataService {
maintenanceWindow.setId(equipMaintainTask.getId().toString()); maintenanceWindow.setId(equipMaintainTask.getId().toString());
maintenanceWindow.setStartTime(equipMaintainTask.getPlanStartTime()); maintenanceWindow.setStartTime(equipMaintainTask.getPlanStartTime());
maintenanceWindow.setEndTime(equipMaintainTask.getPlanFinishTime()); maintenanceWindow.setEndTime(equipMaintainTask.getPlanFinishTime());
maintenanceWindow.setEquipCode(equipMaintainTask.getEquipCode());
maintenanceWindow.setEquipName(equipMaintainTask.getEquipName());
maintenanceWindow.setReason(""); maintenanceWindow.setReason("");
maintenanceWindows.add(maintenanceWindow); maintenanceWindows.add(maintenanceWindow);
} }
...@@ -623,6 +625,8 @@ public class RoutingDataService { ...@@ -623,6 +625,8 @@ public class RoutingDataService {
maintenanceWindow.setId(equipMaintainTask.getId().toString()); maintenanceWindow.setId(equipMaintainTask.getId().toString());
maintenanceWindow.setStartTime(equipMaintainTask.getPlanStartTime()); maintenanceWindow.setStartTime(equipMaintainTask.getPlanStartTime());
maintenanceWindow.setEndTime(equipMaintainTask.getPlanFinishTime()); maintenanceWindow.setEndTime(equipMaintainTask.getPlanFinishTime());
maintenanceWindow.setEquipCode(equipMaintainTask.getEquipCode());
maintenanceWindow.setEquipName(equipMaintainTask.getEquipName());
maintenanceWindow.setReason(""); maintenanceWindow.setReason("");
maintenanceWindows.add(maintenanceWindow); maintenanceWindows.add(maintenanceWindow);
} }
......
...@@ -155,6 +155,9 @@ Integer newMachineId1=newMachineId.intValue(); ...@@ -155,6 +155,9 @@ Integer newMachineId1=newMachineId.intValue();
.findFirst().orElse(null); .findFirst().orElse(null);
if(machine!=null) if(machine!=null)
{ {
maintenanceWindow.setEquipCode(machine.getCode());
maintenanceWindow.setEquipName(machine.getName());
maintenanceWindow.setId(UUID.randomUUID().toString()); maintenanceWindow.setId(UUID.randomUUID().toString());
machine.getMaintenanceWindows().add(maintenanceWindow); machine.getMaintenanceWindows().add(maintenanceWindow);
......
...@@ -40,7 +40,7 @@ public interface LanuchService { ...@@ -40,7 +40,7 @@ public interface LanuchService {
ProdProcessExec createProcessExec(ProdLaunchOrder prodOrderMain, ProdProcessExec createProcessExec(ProdLaunchOrder prodOrderMain,
RoutingDetail detail, RoutingDetail detail,
String sceneId); String sceneId,List<RoutingDetailEquip> routingDetailEquip);
List<ProdEquipment> batchInsertEquipMent( List<ProdEquipment> batchInsertEquipMent(
List<RoutingDetailEquip> routingDetailEquips, List<RoutingDetailEquip> routingDetailEquips,
......
package com.aps.service.common; package com.aps.service.common;
import com.aps.entity.Algorithm.Chromosome; import com.aps.entity.Algorithm.Chromosome;
import com.aps.entity.common.Paged; import com.aps.entity.ProdProcessExec;
import com.aps.entity.basic.Entry;
import com.aps.entity.basic.MachineOption;
import com.aps.entity.common.*;
import com.aps.service.plan.SceneService; import com.aps.service.plan.SceneService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.HashMap; import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/**
* Chromosome数据服务类
* 提供对Chromosome对象中各种实体数据的查询服务
*/
@Service @Service
public class ChromosomeDataService { public class ChromosomeDataService {
@Autowired @Autowired
private SceneService sceneService; private SceneService sceneService;
@Autowired
private DatabaseQueryService databaseQueryService;
@Autowired
private Map<String, EntityConfig> entityConfigMap;
/** /**
* 根据场景ID和实体名称查询Chromosome中的数据 * 根据场景ID和实体名称查询Chromosome中的数据
*
* @param sceneId 场景ID
* @param entityName 实体名称 (如: order, entry, machine等)
* @return 对应的数据对象
*/ */
public Object queryChromosomeData(String sceneId, String entityName) { public Object queryChromosomeData(String sceneId, String entityName) {
// 从文件中加载Chromosome对象 EntityConfig config = getEntityConfig(entityName);
if (config.getDataSource() == DataSourceType.FILE) {
return queryFileData(sceneId, config);
} else {
// 数据库实体不需要sceneId,创建空的Paged对象
Paged paged = new Paged();
List<Object> result = databaseQueryService.queryDatabaseDataList(config, paged);
return result;
}
}
/**
* 驼峰命名转下划线大写:prodProduct -> PROD_PRODUCT
*/
private String camelCaseToUnderScoreUpperCase(String camelCase) {
if (camelCase == null || camelCase.isEmpty()) {
return camelCase;
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < camelCase.length(); i++) {
char c = camelCase.charAt(i);
// 遇到大写字母且不是第一个字符时,添加下划线
if (Character.isUpperCase(c) && i > 0) {
// 检查前一个字符是否是小写,避免连续大写的情况
char prevChar = camelCase.charAt(i - 1);
if (Character.isLowerCase(prevChar)) {
result.append('_');
}
}
result.append(Character.toUpperCase(c));
}
return result.toString();
}
/**
* 根据场景ID和实体名称查询Chromosome中的分页数据,带条件过滤
*/
public Map<String, Object> queryChromosomeDataWithConditions(String sceneId, String entityName, Paged paged) {
EntityConfig config = getEntityConfig(entityName);
if (config.getDataSource() == DataSourceType.FILE) {
return queryFileDataWithConditions(sceneId, config, paged);
} else {
// 数据库查询
return databaseQueryService.queryDatabaseDataWithConditions(config, paged);
}
}
/**
* 查询文件数据列表(支持条件过滤)
*/
public List<Object> queryChromosomeDataList(String sceneId, String entityName, Paged paged) {
EntityConfig config = getEntityConfig(entityName);
if (config.getDataSource() == DataSourceType.FILE) {
Object data = queryFileData(sceneId, config);
return applyConditionsToList(data, paged);
} else {
// 数据库查询
return databaseQueryService.queryDatabaseDataList(config, paged);
}
}
/**
* 根据ID查询单条数据
*/
public Object queryChromosomeDataById(String sceneId, String entityName, String id) {
EntityConfig config = getEntityConfig(entityName);
if (config.getDataSource() == DataSourceType.FILE) {
return queryFileDataById(sceneId, config, id);
} else {
// 数据库查询
return databaseQueryService.queryDatabaseDataById(config, id);
}
}
/**
* 获取实体配置(智能默认)
*/
private EntityConfig getEntityConfig(String entityName) {
if (entityName == null || entityName.isEmpty()) {
throw new RuntimeException("实体名称不能为空");
}
String key = entityName.toLowerCase();
EntityConfig config = entityConfigMap.get(key);
if (config == null) {
// 特殊处理:当实体是ProdProcessExec时,映射到allOperations字段
if ("prodprocessexec".equalsIgnoreCase(key)) {
config = new EntityConfig();
config.setEntityName(entityName);
config.setDataSource(DataSourceType.FILE);
config.setFieldName("allOperations");
} else {
// 自动创建数据库配置(默认行为)
config = createDefaultDbConfig(entityName);
System.out.println(config.getTableName()
);
}
// 缓存这个自动创建的配置
entityConfigMap.put(key, config);
}
return config;
}
//
// /**
// * 创建默认的数据库配置
// */
// private EntityConfig createDefaultDbConfig(String entityName) {
// EntityConfig config = new EntityConfig();
// config.setEntityName(entityName);
// config.setDataSource(DataSourceType.DATABASE);
//
// // 默认表名与实体名相同
// String tableName = "t_" + entityName.toUpperCase(); // Oracle表名通常大写
// config.setTableName(tableName);
//
// // 如果没有对应的实体类,设置为null,查询返回Map
// config.setEntityClass(null);
//
// return config;
// }
private EntityConfig createDefaultDbConfig(String entityName) {
EntityConfig config = new EntityConfig();
config.setEntityName(entityName);
config.setDataSource(DataSourceType.DATABASE);
// 智能表名映射
String tableName = mapEntityNameToTableName(entityName);
System.out.println("智能表名映射:" + entityName + " -> " + tableName);
config.setTableName(tableName);
// 如果没有对应的实体类,设置为null,查询返回Map
config.setEntityClass(null);
return config;
}
/**
* 将实体名映射为数据库表名
* 规则:ProdProduct -> PROD_PRODUCT
*/
private String mapEntityNameToTableName(String entityName) {
if (entityName == null || entityName.isEmpty()) {
return entityName;
}
// 处理常见的命名约定
String[] commonPrefixes = {"Prod", "Sys", "Tbl", "Tab", "Biz"};
String processedName = entityName;
// 检查是否有常见前缀
for (String prefix : commonPrefixes) {
if (entityName.startsWith(prefix) && entityName.length() > prefix.length()) {
// 保留前缀,如ProdProduct -> PROD_PRODUCT
break;
}
}
// 驼峰命名转下划线大写
return camelCaseToUnderScoreUpperCase(processedName);
}
/**
* 驼峰命名转下划线大写:ProdProduct -> PROD_PRODUCT
*/
// private String camelCaseToUnderScoreUpperCase(String camelCase) {
// if (camelCase == null || camelCase.isEmpty()) {
// return camelCase;
// }
//
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < camelCase.length(); i++) {
// char c = camelCase.charAt(i);
// if (Character.isUpperCase(c) && i > 0) {
// result.append('_');
// }
// result.append(Character.toUpperCase(c));
// }
// return result.toString();
// }
/**
* 查询文件数据
*/
private Object queryFileData(String sceneId, EntityConfig config) {
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId); Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome == null) { if (chromosome == null) {
throw new RuntimeException("未找到场景ID为 " + sceneId + " 的Chromosome数据"); throw new RuntimeException("未找到场景ID为 " + sceneId + " 的Chromosome数据");
} }
try { try {
// 根据实体名称映射到Chromosome中的字段名 String fieldName = config.getFieldName();
String fieldName = mapEntityToField(entityName);
// 特殊处理:当实体是ProdProcessExec时,使用allOperations字段
if ("prodprocessexec".equalsIgnoreCase(config.getEntityName())) {
fieldName = "allOperations";
}
// 使用反射获取字段值
Field field = Chromosome.class.getDeclaredField(fieldName); Field field = Chromosome.class.getDeclaredField(fieldName);
field.setAccessible(true); field.setAccessible(true);
Object result = field.get(chromosome);
// 如果实体是ProdProcessExec,但数据源是Entry,则进行转换
if ("prodprocessexec".equalsIgnoreCase(config.getEntityName())) {
return convertEntryToProdProcessExec(result);
}
return field.get(chromosome); return result;
} catch (NoSuchFieldException e) { } catch (NoSuchFieldException e) {
throw new RuntimeException("Chromosome类中未找到字段: " + entityName, e); throw new RuntimeException("Chromosome类中未找到字段: " + config.getFieldName(), e);
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new RuntimeException("访问Chromosome字段失败: " + e.getMessage(), e); throw new RuntimeException("访问Chromosome字段失败: " + e.getMessage(), e);
} }
} }
/** /**
* 根据场景ID和实体名称查询Chromosome中的分页数据 * 查询文件数据(分页+条件)
*
* @param sceneId 场景ID
* @param entityName 实体名称
* @param page 页码(从1开始)
* @param size 每页大小
* @return 分页数据
*/ */
public Map<String, Object> queryChromosomeDataWithPagination(String sceneId, String entityName, int page, int size) { private Map<String, Object> queryFileDataWithConditions(String sceneId, EntityConfig config, Paged paged) {
Object data = queryChromosomeData(sceneId, entityName); Object data = queryFileData(sceneId, config);
Map<String, Object> result = new HashMap<>(); Map<String, Object> result = new HashMap<>();
int page = paged.getPageIndex() != null ? paged.getPageIndex() : 1;
int size = paged.getPageSize() != null ? paged.getPageSize() : 10;
// 处理分页逻辑(如果数据是List类型)
if (data instanceof List) { if (data instanceof List) {
List<?> dataList = (List<?>) data; List<?> dataList = (List<?>) data;
// 应用条件过滤
if (!CollectionUtils.isEmpty(paged.getConditions())) {
dataList = filterDataByConditions(dataList, paged.getConditions());
}
int total = dataList.size(); int total = dataList.size();
int fromIndex = (page - 1) * size; int fromIndex = (page - 1) * size;
// 确保起始索引不超出范围
fromIndex = Math.min(fromIndex, total); fromIndex = Math.min(fromIndex, total);
int toIndex = Math.min(fromIndex + size, total); int toIndex = Math.min(fromIndex + size, total);
// 分页数据
List<?> pagedData = dataList.subList(fromIndex, toIndex); List<?> pagedData = dataList.subList(fromIndex, toIndex);
result.put("records", pagedData); result.put("records", pagedData);
...@@ -94,119 +311,248 @@ public class ChromosomeDataService { ...@@ -94,119 +311,248 @@ public class ChromosomeDataService {
} }
/** /**
* 根据场景ID和实体名称查询Chromosome中的分页数据,带条件过滤 * 根据ID查询文件数据
*
* @param sceneId 场景ID
* @param entityName 实体名称
* @param paged 分页和条件对象
* @return 分页数据
*/ */
public Map<String, Object> queryChromosomeDataWithConditions(String sceneId, String entityName, Paged paged) { private Object queryFileDataById(String sceneId, EntityConfig config, String id) {
Object data = queryChromosomeData(sceneId, entityName); Object result = queryFileData(sceneId, config);
// 如果结果是List类型,则根据ID查找特定项
if (result instanceof List) {
List<Object> dataList = (List<Object>) result;
Object item = dataList.stream()
.filter(obj -> {
try {
// 尝试获取对象的id字段(兼容大小写)
Field idField = getFieldIgnoreCase(obj.getClass(), "id");
if (idField != null) {
idField.setAccessible(true);
Object itemId = idField.get(obj);
return itemId != null && itemId.toString().equals(id);
}
return false;
} catch (Exception e) {
return false;
}
})
.findFirst()
.orElse(null);
Map<String, Object> result = new HashMap<>(); if (item != null) {
int page = paged.getPageIndex() != null ? paged.getPageIndex() : 1; return item;
int size = paged.getPageSize() != null ? paged.getPageSize() : 10; } else {
throw new RuntimeException("未找到ID为 " + id + " 的数据");
}
} else {
// 如果不是列表,直接返回结果
return result;
}
}
// 处理分页和条件逻辑(如果数据是List类型) /**
* 忽略大小写获取字段
*/
private Field getFieldIgnoreCase(Class<?> clazz, String fieldName) {
try {
return clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
// 尝试大写
try {
return clazz.getDeclaredField(fieldName.toUpperCase());
} catch (NoSuchFieldException e1) {
// 尝试小写
try {
return clazz.getDeclaredField(fieldName.toLowerCase());
} catch (NoSuchFieldException e2) {
return null;
}
}
}
}
/**
* 将数据应用条件过滤并返回列表
*/
private List<Object> applyConditionsToList(Object data, Paged paged) {
if (data instanceof List) { if (data instanceof List) {
List<?> dataList = (List<?>) data; List<Object> dataList = (List<Object>) data;
// 应用条件过滤 // 应用条件过滤
if (!CollectionUtils.isEmpty(paged.getConditions())) { if (!CollectionUtils.isEmpty(paged.getConditions())) {
dataList = filterDataByConditions(dataList, paged.getConditions()); dataList = filterDataByConditions(dataList, paged.getConditions());
} }
int total = dataList.size(); return dataList;
int fromIndex = (page - 1) * size; } else {
// 确保起始索引不超出范围 List<Object> resultList = new ArrayList<>();
fromIndex = Math.min(fromIndex, total); resultList.add(data);
int toIndex = Math.min(fromIndex + size, total); return resultList;
}
}
// 分页数据 /**
List<?> pagedData = dataList.subList(fromIndex, toIndex); * 根据条件过滤数据(文件数据使用)- 修复版本
*/
private List<Object> filterDataByConditions(List<?> dataList, List<ConditionEntity> conditions) {
if (CollectionUtils.isEmpty(conditions)) {
return new ArrayList<>(dataList);
}
result.put("records", pagedData); List<Object> filteredList = new ArrayList<>(dataList);
result.put("total", total);
result.put("current", page); for (ConditionEntity condition : conditions) {
result.put("size", size); if (condition == null || condition.getFieldName() == null || condition.getFieldValue() == null) {
} else { continue;
result.put("records", data);
result.put("total", 1);
result.put("current", 1);
result.put("size", 1);
} }
return result; final String fieldName = condition.getFieldName();
final String fieldValue = condition.getFieldValue();
ConditionEnum conditionType = ConditionEnum.getByName(condition.getConditionalType());
if (conditionType == null) {
conditionType = ConditionEnum.Equal;
}
final ConditionEnum finalConditionType = conditionType;
// 特殊处理:sceneId条件应该在查询层面处理,这里跳过
if ("sceneId".equalsIgnoreCase(fieldName)) {
continue;
}
// 使用增强的for循环替代stream,避免lambda变量问题
List<Object> tempList = new ArrayList<>();
for (Object item : filteredList) {
if (matchesCondition(item, fieldName, fieldValue, finalConditionType)) {
tempList.add(item);
}
}
filteredList = tempList;
}
return filteredList;
} }
/** /**
* 根据条件过滤数据 * 判断单个对象是否匹配条件
* @param dataList 原始数据列表
* @param conditions 条件列表
* @return 过滤后的数据列表
*/ */
private List<?> filterDataByConditions(List<?> dataList, List<com.aps.entity.common.ConditionEntity> conditions) { private boolean matchesCondition(Object item, String fieldName, String fieldValue, ConditionEnum conditionType) {
// 简单实现:按字段相等条件过滤
List<?> filteredList = dataList;
for (com.aps.entity.common.ConditionEntity condition : conditions) {
String fieldName = condition.getFieldName();
String fieldValue = condition.getFieldValue();
com.aps.entity.common.ConditionEnum conditionType =
com.aps.entity.common.ConditionEnum.getByName(condition.getConditionalType());
if (conditionType == com.aps.entity.common.ConditionEnum.Equal) {
filteredList = filteredList.stream()
.filter(item -> {
try { try {
Field field = item.getClass().getDeclaredField(fieldName); // 获取字段值
field.setAccessible(true); Object actualValue = getFieldValue(item, fieldName);
Object value = field.get(item); if (actualValue == null) {
return value != null && value.toString().equals(fieldValue); return conditionType == ConditionEnum.IsEmpty;
}
String actualValueStr = actualValue.toString();
switch (conditionType) {
case Equal:
return actualValueStr.equals(fieldValue);
case NoEqual:
return !actualValueStr.equals(fieldValue);
case Like:
return actualValueStr.contains(fieldValue);
case GreaterThan:
return compareValues(actualValueStr, fieldValue) > 0;
case GreaterThanOrEqual:
return compareValues(actualValueStr, fieldValue) >= 0;
case LessThan:
return compareValues(actualValueStr, fieldValue) < 0;
case LessThanOrEqual:
return compareValues(actualValueStr, fieldValue) <= 0;
case In:
return Arrays.asList(fieldValue.split(",")).contains(actualValueStr);
case NotIn:
return !Arrays.asList(fieldValue.split(",")).contains(actualValueStr);
case IsEmpty:
return actualValueStr.isEmpty();
case NotEmpty:
return !actualValueStr.isEmpty();
default:
return actualValueStr.equals(fieldValue);
}
} catch (Exception e) { } catch (Exception e) {
// 字段不存在或访问异常,跳过该条件 // 如果匹配过程中出错,保守起见返回true(不过滤掉数据)
return true; return true;
} }
})
.collect(Collectors.toList());
} }
// 可以继续添加其他条件类型的处理
/**
* 安全获取字段值(支持多种字段名格式)
*/
private Object getFieldValue(Object item, String fieldName) {
// 尝试多种可能的字段名
String[] possibleNames = {
fieldName,
fieldName.toLowerCase(),
fieldName.toUpperCase(),
toCamelCase(fieldName),
toUnderScoreCase(fieldName)
};
for (String name : possibleNames) {
try {
Field field = item.getClass().getDeclaredField(name);
field.setAccessible(true);
Object value = field.get(item);
if (value != null) {
return value;
}
} catch (Exception e) {
// 继续尝试下一个名称
}
} }
return filteredList; return null;
} }
/** /**
* 将实体名称映射到Chromosome中的字段名 * 比较值(支持数字和字符串)
* @param entityName 实体名称
* @return Chromosome中的字段名
*/ */
private String mapEntityToField(String entityName) { private int compareValues(String str1, String str2) {
switch (entityName.toLowerCase()) { try {
case "order": // 尝试数字比较
return "orders"; Double num1 = Double.parseDouble(str1);
case "entry": Double num2 = Double.parseDouble(str2);
return "allOperations"; return num1.compareTo(num2);
case "machine": } catch (NumberFormatException e) {
return "InitMachines"; // 数字解析失败,使用字符串比较
case "globaloperationinfo": return str1.compareTo(str2);
return "globalOpList"; }
case "groupresult":
return "OperatRel";
default:
return entityName; // 如果名称相同则直接返回
} }
/**
* 转换为驼峰命名
*/
private String toCamelCase(String str) {
if (str == null || str.isEmpty()) return str;
if (str.length() == 1) return str.toLowerCase();
return str.substring(0, 1).toLowerCase() + str.substring(1);
} }
/** /**
* 更新Chromosome中的数据 * 转换为下划线命名
* @param sceneId 场景ID */
* @param entityName 实体名称 private String toUnderScoreCase(String str) {
* @param data 更新的数据 if (str == null || str.isEmpty()) return str;
* @return 是否更新成功 StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isUpperCase(c) && i > 0) {
result.append('_');
}
result.append(Character.toLowerCase(c));
}
return result.toString();
}
/**
* 更新Chromosome中的数据(仅支持文件实体)
*/ */
public boolean updateChromosomeData(String sceneId, String entityName, Map<String, Object> data) { public boolean updateChromosomeData(String sceneId, String entityName, Map<String, Object> data) {
EntityConfig config = getEntityConfig(entityName);
if (config.getDataSource() == DataSourceType.DATABASE) {
throw new RuntimeException("数据库实体暂不支持更新操作");
}
// 从文件中加载Chromosome对象 // 从文件中加载Chromosome对象
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId); Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome == null) { if (chromosome == null) {
...@@ -215,7 +561,7 @@ public class ChromosomeDataService { ...@@ -215,7 +561,7 @@ public class ChromosomeDataService {
try { try {
// 根据实体名称映射到Chromosome中的字段名 // 根据实体名称映射到Chromosome中的字段名
String fieldName = mapEntityToField(entityName); String fieldName = config.getFieldName();
// 使用反射设置字段值 // 使用反射设置字段值
Field field = Chromosome.class.getDeclaredField(fieldName); Field field = Chromosome.class.getDeclaredField(fieldName);
...@@ -272,13 +618,15 @@ public class ChromosomeDataService { ...@@ -272,13 +618,15 @@ public class ChromosomeDataService {
} }
/** /**
* 批量操作Chromosome中的数据 * 批量操作Chromosome中的数据(仅支持文件实体)
* @param sceneId 场景ID
* @param entityName 实体名称
* @param dataList 批量数据
* @return 操作成功的数量
*/ */
public int batchChromosomeData(String sceneId, String entityName, List<Map<String, Object>> dataList) { public int batchChromosomeData(String sceneId, String entityName, List<Map<String, Object>> dataList) {
EntityConfig config = getEntityConfig(entityName);
if (config.getDataSource() == DataSourceType.DATABASE) {
throw new RuntimeException("数据库实体暂不支持批量操作");
}
// 从文件中加载Chromosome对象 // 从文件中加载Chromosome对象
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId); Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome == null) { if (chromosome == null) {
...@@ -287,7 +635,7 @@ public class ChromosomeDataService { ...@@ -287,7 +635,7 @@ public class ChromosomeDataService {
try { try {
// 根据实体名称映射到Chromosome中的字段名 // 根据实体名称映射到Chromosome中的字段名
String fieldName = mapEntityToField(entityName); String fieldName = config.getFieldName();
// 使用反射获取字段值 // 使用反射获取字段值
Field field = Chromosome.class.getDeclaredField(fieldName); Field field = Chromosome.class.getDeclaredField(fieldName);
...@@ -355,13 +703,15 @@ public class ChromosomeDataService { ...@@ -355,13 +703,15 @@ public class ChromosomeDataService {
} }
/** /**
* 删除Chromosome中的数据 * 删除Chromosome中的数据(仅支持文件实体)
* @param sceneId 场景ID
* @param entityName 实体名称
* @param ids 要删除的数据ID列表
* @return 删除成功的数量
*/ */
public int deleteChromosomeData(String sceneId, String entityName, List<Object> ids) { public int deleteChromosomeData(String sceneId, String entityName, List<Object> ids) {
EntityConfig config = getEntityConfig(entityName);
if (config.getDataSource() == DataSourceType.DATABASE) {
throw new RuntimeException("数据库实体暂不支持删除操作");
}
// 从文件中加载Chromosome对象 // 从文件中加载Chromosome对象
Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId); Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
if (chromosome == null) { if (chromosome == null) {
...@@ -370,7 +720,7 @@ public class ChromosomeDataService { ...@@ -370,7 +720,7 @@ public class ChromosomeDataService {
try { try {
// 根据实体名称映射到Chromosome中的字段名 // 根据实体名称映射到Chromosome中的字段名
String fieldName = mapEntityToField(entityName); String fieldName = config.getFieldName();
// 使用反射获取字段值 // 使用反射获取字段值
Field field = Chromosome.class.getDeclaredField(fieldName); Field field = Chromosome.class.getDeclaredField(fieldName);
...@@ -390,7 +740,7 @@ public class ChromosomeDataService { ...@@ -390,7 +740,7 @@ public class ChromosomeDataService {
.collect(Collectors.toList()); .collect(Collectors.toList());
// 使用迭代器安全地删除元素 // 使用迭代器安全地删除元素
java.util.Iterator<Object> iterator = originalList.iterator(); Iterator<Object> iterator = originalList.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Object item = iterator.next(); Object item = iterator.next();
try { try {
...@@ -434,8 +784,6 @@ public class ChromosomeDataService { ...@@ -434,8 +784,6 @@ public class ChromosomeDataService {
/** /**
* 更新对象的字段值 * 更新对象的字段值
* @param obj 要更新的对象
* @param data 新的字段值
*/ */
private void updateObjectFields(Object obj, Map<String, Object> data) { private void updateObjectFields(Object obj, Map<String, Object> data) {
Class<?> clazz = obj.getClass(); Class<?> clazz = obj.getClass();
...@@ -446,10 +794,96 @@ public class ChromosomeDataService { ...@@ -446,10 +794,96 @@ public class ChromosomeDataService {
try { try {
Field field = clazz.getDeclaredField(fieldName); Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true); field.setAccessible(true);
// 简单的类型转换处理
if (fieldValue != null) {
Class<?> fieldType = field.getType();
if (fieldType == String.class) {
field.set(obj, fieldValue.toString());
} else if (fieldType == Integer.class || fieldType == int.class) {
field.set(obj, Integer.parseInt(fieldValue.toString()));
} else if (fieldType == Long.class || fieldType == long.class) {
field.set(obj, Long.parseLong(fieldValue.toString()));
} else if (fieldType == Double.class || fieldType == double.class) {
field.set(obj, Double.parseDouble(fieldValue.toString()));
} else if (fieldType == Boolean.class || fieldType == boolean.class) {
field.set(obj, Boolean.parseBoolean(fieldValue.toString()));
} else {
field.set(obj, fieldValue); field.set(obj, fieldValue);
}
} else {
field.set(obj, null);
}
} catch (Exception e) { } catch (Exception e) {
// 忽略无法设置的字段 // 忽略无法设置的字段
} }
} }
} }
/**
* 将Entry列表转换为ProdProcessExec列表
*/
private Object convertEntryToProdProcessExec(Object data) {
if (data instanceof List) {
List<?> entryList = (List<?>) data;
List<ProdProcessExec> result = new ArrayList<>();
for (Object obj : entryList) {
if (obj instanceof Entry) {
Entry entry = (Entry) obj;
ProdProcessExec prodProcessExec = convertEntryToProdProcessExecSingle(entry);
result.add(prodProcessExec);
}
}
return result;
} else if (data instanceof Entry) {
Entry entry = (Entry) data;
return convertEntryToProdProcessExecSingle(entry);
}
return data; // 如果不是Entry类型,直接返回原数据
}
/**
* 将单个Entry转换为ProdProcessExec
*/
private ProdProcessExec convertEntryToProdProcessExecSingle(Entry entry) {
ProdProcessExec prodProcessExec = new ProdProcessExec();
// 基本字段映射
prodProcessExec.setExecId(entry.ExecId);
prodProcessExec.setSceneId(entry.SceneId);
prodProcessExec.setOrderId(entry.OrderId);
prodProcessExec.setRoutingDetailId(entry.getRoutingDetailId());
prodProcessExec.setTaskSeq(entry.getTaskSeq());
prodProcessExec.setRoutingDetailName(entry.getRoutingDetailName());
prodProcessExec.setMachineId(entry.getSelectMachineID());
prodProcessExec.setEquipTypeName(entry.getEquipTypeName());
prodProcessExec.setEquipTypeCode(entry.getEquipTypeCode());
// prodProcessExec.setMachineId(entry.getEquipTypeID());
prodProcessExec.setRuntime(entry.getRuntime());
prodProcessExec.setSingleOut(entry.getSingleOut());
prodProcessExec.setPlanQty(entry.getQuantity());
prodProcessExec.setLogicalOrder((long) entry.getSequence());
// 设置ID字段
prodProcessExec.setId(String.valueOf(entry.getId()));
// 其他字段根据需要进行映射
prodProcessExec.setCanInterrupt(entry.getIsInterrupt());
prodProcessExec.setRoutingId(entry.getRoutingId());
List<MachineOption> machineOptions = entry.getMachineOptions();
MachineOption machineOption1 = machineOptions.stream()
.filter(machineOption -> machineOption.getMachineId().equals(entry.getSelectMachineID()) )
.findFirst()
.orElse(null);
prodProcessExec.setChangeLineTime(machineOption1.getSetupTime());
prodProcessExec.setChangeLineTime(machineOption1.getSetupTime());
prodProcessExec.setPreprocessingTime(machineOption1.getPreTime());
prodProcessExec.setPostprocessingTime(machineOption1.getTeardownTime());
return prodProcessExec;
}
} }
\ No newline at end of file
package com.aps.service.common;
import com.aps.entity.common.ConditionEntity;
import com.aps.entity.common.ConditionEnum;
import com.aps.entity.common.EntityConfig;
import com.aps.entity.common.Paged;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class DatabaseQueryService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
/**
* 查询数据库数据(分页+条件)- 修复Oracle分页问题
*/
public Map<String, Object> queryDatabaseDataWithConditions(EntityConfig config, Paged paged) {
String tableName = config.getTableName();
// 构建基础SQL和参数
StringBuilder whereClause = new StringBuilder(" WHERE 1=1");
MapSqlParameterSource params = new MapSqlParameterSource();
// 处理条件
int paramIndex = 1;
if (paged.getConditions() != null && !paged.getConditions().isEmpty()) {
for (ConditionEntity condition : paged.getConditions()) {
String conditionSql = buildConditionSql(condition, params, paramIndex);
if (conditionSql != null) {
whereClause.append(" AND ").append(conditionSql);
paramIndex++;
}
}
}
// 构建排序
String orderBy = buildOrderBy(paged);
// 分页参数
int page = paged.getPageIndex() != null ? paged.getPageIndex() : 1;
int size = paged.getPageSize() != null ? paged.getPageSize() : 10;
// 先查询总数
String countSql = "SELECT COUNT(*) FROM " + tableName + whereClause.toString();
Integer total;
try {
if (params.getValues().isEmpty()) {
total = jdbcTemplate.queryForObject(countSql, Integer.class);
} else {
total = namedParameterJdbcTemplate.queryForObject(countSql, params, Integer.class);
}
} catch (Exception e) {
total = 0;
}
// 查询数据(使用Oracle分页语法)
List<?> records = Collections.emptyList();
if (total != null && total > 0) {
String dataSql = buildOraclePaginationSql(tableName, whereClause.toString(), orderBy, page, size);
try {
if (config.getEntityClass() != null) {
// 使用实体类映射
if (params.getValues().isEmpty()) {
records = jdbcTemplate.query(dataSql, new BeanPropertyRowMapper<>(config.getEntityClass()));
} else {
records = namedParameterJdbcTemplate.query(dataSql, params, new BeanPropertyRowMapper<>(config.getEntityClass()));
}
} else {
// 返回Map列表
if (params.getValues().isEmpty()) {
records = jdbcTemplate.queryForList(dataSql);
} else {
records = namedParameterJdbcTemplate.queryForList(dataSql, params);
}
}
} catch (Exception e) {
throw new RuntimeException("查询数据失败: " + e.getMessage(), e);
}
}
Map<String, Object> result = new HashMap<>();
result.put("records", records);
result.put("total", total != null ? total : 0);
result.put("current", page);
result.put("size", size);
return result;
}
/**
* 查询数据库数据列表(不分页)
*/
public List<Object> queryDatabaseDataList(EntityConfig config, Paged paged) {
String tableName = config.getTableName();
StringBuilder whereClause = new StringBuilder(" WHERE 1=1");
MapSqlParameterSource params = new MapSqlParameterSource();
// 处理条件
int paramIndex = 1;
if (paged.getConditions() != null && !paged.getConditions().isEmpty()) {
for (ConditionEntity condition : paged.getConditions()) {
String conditionSql = buildConditionSql(condition, params, paramIndex);
if (conditionSql != null) {
whereClause.append(" AND ").append(conditionSql);
paramIndex++;
}
}
}
// 构建排序
String orderBy = buildOrderBy(paged);
String sql = "SELECT * FROM " + tableName + whereClause.toString() + orderBy;
try {
if (config.getEntityClass() != null) {
if (params.getValues().isEmpty()) {
return new ArrayList<>(jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(config.getEntityClass())));
} else {
return new ArrayList<>(namedParameterJdbcTemplate.query(sql, params, new BeanPropertyRowMapper<>(config.getEntityClass())));
}
} else {
if (params.getValues().isEmpty()) {
return new ArrayList<>(jdbcTemplate.queryForList(sql));
} else {
return new ArrayList<>(namedParameterJdbcTemplate.queryForList(sql, params));
}
}
} catch (Exception e) {
throw new RuntimeException("查询数据列表失败: " + e.getMessage(), e);
}
}
/**
* 根据ID查询单条数据
*/
public Object queryDatabaseDataById(EntityConfig config, String id) {
String tableName = config.getTableName();
// 尝试不同的ID字段名(兼容大小写)
String[] idFields = {"ID", "Id", "id"};
for (String idField : idFields) {
try {
String sql = "SELECT * FROM " + tableName + " WHERE " + idField + " = ?";
if (config.getEntityClass() != null) {
return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(config.getEntityClass()), id);
} else {
return jdbcTemplate.queryForMap(sql, id);
}
} catch (Exception e) {
// 继续尝试下一个字段名
}
}
throw new RuntimeException("未找到ID为 " + id + " 的数据");
}
/**
* 构建Oracle分页SQL
*/
private String buildOraclePaginationSql(String tableName, String whereClause, String orderBy, int page, int size) {
int startRow = (page - 1) * size + 1;
int endRow = page * size;
StringBuilder sql = new StringBuilder();
sql.append("SELECT * FROM (");
sql.append(" SELECT a.*, ROWNUM rn FROM (");
sql.append(" SELECT * FROM ").append(tableName).append(whereClause).append(orderBy);
sql.append(" ) a WHERE ROWNUM <= ").append(endRow);
sql.append(") WHERE rn >= ").append(startRow);
return sql.toString();
}
/**
* 构建排序子句
*/
private String buildOrderBy(Paged paged) {
if (paged.getSortBy() != null && !paged.getSortBy().isEmpty()) {
String direction = Boolean.TRUE.equals(paged.getDesc()) ? "DESC" : "ASC";
return " ORDER BY " + paged.getSortBy() + " " + direction;
}
return " ORDER BY ID DESC"; // 默认按ID降序
}
/**
* 构建条件SQL
*/
private String buildConditionSql(ConditionEntity condition, MapSqlParameterSource params, int paramIndex) {
if (condition == null || condition.getFieldName() == null || condition.getFieldValue() == null) {
return null;
}
String paramName = "param" + paramIndex;
ConditionEnum conditionType = ConditionEnum.getByName(condition.getConditionalType());
if (conditionType == null) {
conditionType = ConditionEnum.Equal;
}
// 处理字段名大小写问题:将驼峰命名转换为下划线大写(数据库字段格式)
String fieldName = camelCaseToUnderScoreUpperCase(condition.getFieldName()).toUpperCase();
switch (conditionType) {
case Equal:
params.addValue(paramName, condition.getSafeValue());
return fieldName + " = :" + paramName;
case NoEqual:
params.addValue(paramName, condition.getSafeValue());
return fieldName + " != :" + paramName;
case Like:
params.addValue(paramName, "%" + condition.getSafeValue() + "%");
return fieldName + " LIKE :" + paramName;
case GreaterThan:
params.addValue(paramName, condition.getSafeValue());
return fieldName + " > :" + paramName;
case GreaterThanOrEqual:
params.addValue(paramName, condition.getSafeValue());
return fieldName + " >= :" + paramName;
case LessThan:
params.addValue(paramName, condition.getSafeValue());
return fieldName + " < :" + paramName;
case LessThanOrEqual:
params.addValue(paramName, condition.getSafeValue());
return fieldName + " <= :" + paramName;
case In:
// IN查询需要特殊处理
String[] inValues = condition.getSafeValue().split(",");
List<String> paramNames = new ArrayList<>();
for (int i = 0; i < inValues.length; i++) {
String inParamName = paramName + "_" + i;
params.addValue(inParamName, inValues[i].trim());
paramNames.add(":" + inParamName);
}
return fieldName + " IN (" + String.join(",", paramNames) + ")";
case NotIn:
String[] notInValues = condition.getSafeValue().split(",");
List<String> notInParamNames = new ArrayList<>();
for (int i = 0; i < notInValues.length; i++) {
String notInParamName = paramName + "_" + i;
params.addValue(notInParamName, notInValues[i].trim());
notInParamNames.add(":" + notInParamName);
}
return fieldName + " NOT IN (" + String.join(",", notInParamNames) + ")";
case IsEmpty:
return "(" + fieldName + " IS NULL OR " + fieldName + " = '')";
case NotEmpty:
return "(" + fieldName + " IS NOT NULL AND " + fieldName + " != '')";
default:
params.addValue(paramName, condition.getSafeValue());
return fieldName + " = :" + paramName;
}
}
/**
* 驼峰命名转下划线大写:prodProduct -> PROD_PRODUCT
*/
private String camelCaseToUnderScoreUpperCase(String camelCase) {
if (camelCase == null || camelCase.isEmpty()) {
return camelCase;
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < camelCase.length(); i++) {
char c = camelCase.charAt(i);
if (Character.isUpperCase(c) && i > 0) {
result.append('_');
}
result.append(Character.toUpperCase(c));
}
return result.toString();
}
}
\ No newline at end of file
...@@ -6,6 +6,7 @@ import com.aps.common.util.SnowFlackIdWorker; ...@@ -6,6 +6,7 @@ import com.aps.common.util.SnowFlackIdWorker;
import com.aps.entity.*; import com.aps.entity.*;
import com.aps.entity.Algorithm.Chromosome; import com.aps.entity.Algorithm.Chromosome;
import com.aps.entity.Algorithm.GAScheduleResult; import com.aps.entity.Algorithm.GAScheduleResult;
import com.aps.entity.basic.Entry;
import com.aps.entity.basic.Order; import com.aps.entity.basic.Order;
import com.aps.mapper.RoutingDetailMapper; import com.aps.mapper.RoutingDetailMapper;
import com.aps.mapper.RoutingHeaderMapper; import com.aps.mapper.RoutingHeaderMapper;
...@@ -245,15 +246,15 @@ public class LanuchServiceImpl implements LanuchService { ...@@ -245,15 +246,15 @@ public class LanuchServiceImpl implements LanuchService {
throw new RuntimeException("插入mes_order失败"); throw new RuntimeException("插入mes_order失败");
} }
List<ProdProcessExec> processExecList = prodProcessExecService.lambdaQuery() // List<ProdProcessExec> processExecList = prodProcessExecService.lambdaQuery()
.eq(ProdProcessExec::getSceneId, sceneId) // .eq(ProdProcessExec::getSceneId, sceneId)
.list(); // .list();
List<Entry> entrys= chromosome.getAllOperations();
// 遍历GAScheduleResult结果并转换为dispatch // 遍历GAScheduleResult结果并转换为dispatch
List<Dispatch> dispatches = new ArrayList<>(); List<Dispatch> dispatches = new ArrayList<>();
for (GAScheduleResult gaResult : chromosome.getResult()) { for (GAScheduleResult gaResult : chromosome.getResult()) {
ProdProcessExec prodProcessExec = processExecList.stream() Entry entry1 = entrys.stream()
.filter(processExec -> processExec.getExecId().equals(gaResult.getExecId())) .filter(entry -> entry.getExecId().equals(gaResult.getExecId()))
.findFirst() .findFirst()
.orElse(null); .orElse(null);
...@@ -267,10 +268,10 @@ public class LanuchServiceImpl implements LanuchService { ...@@ -267,10 +268,10 @@ public class LanuchServiceImpl implements LanuchService {
dispatch.setEndTime(baseTime.plusSeconds(gaResult.getEndTime())); dispatch.setEndTime(baseTime.plusSeconds(gaResult.getEndTime()));
dispatch.setENof(gaResult.getOrderId()); dispatch.setENof(gaResult.getOrderId());
// 设置状态等其他字段 // 设置状态等其他字段
dispatch.setTaskSeq(prodProcessExec.getTaskSeq()); dispatch.setTaskSeq(entry1.getTaskSeq());
dispatch.setMesCode(gaResult.getOrderId()); dispatch.setMesCode(gaResult.getOrderId());
dispatch.setRoutingDetailId(prodProcessExec.getRoutingDetailId()); dispatch.setRoutingDetailId(entry1.getRoutingDetailId());
dispatch.setOpe(prodProcessExec.getRoutingDetailName()); dispatch.setOpe(entry1.getRoutingDetailName());
// 添加到列表中 // 添加到列表中
dispatches.add(dispatch); dispatches.add(dispatch);
} }
...@@ -619,7 +620,7 @@ public class LanuchServiceImpl implements LanuchService { ...@@ -619,7 +620,7 @@ public class LanuchServiceImpl implements LanuchService {
List<RoutingDetail> routingDetails, List<RoutingDetail> routingDetails,
String sceneId, List<RoutingDetailEquip> routingDetailEquip) { String sceneId, List<RoutingDetailEquip> routingDetailEquip) {
List<ProdProcessExec> processExecList = routingDetails.stream() List<ProdProcessExec> processExecList = routingDetails.stream()
.map(detail -> createProcessExec(prodOrderMain, detail, sceneId)) .map(detail -> createProcessExec(prodOrderMain, detail, sceneId,routingDetailEquip))
.collect(Collectors.toList()); .collect(Collectors.toList());
batchInsertEquipMent(routingDetailEquip, sceneId,processExecList,true); batchInsertEquipMent(routingDetailEquip, sceneId,processExecList,true);
...@@ -645,7 +646,7 @@ public class LanuchServiceImpl implements LanuchService { ...@@ -645,7 +646,7 @@ public class LanuchServiceImpl implements LanuchService {
*/ */
public ProdProcessExec createProcessExec(ProdLaunchOrder prodOrderMain, public ProdProcessExec createProcessExec(ProdLaunchOrder prodOrderMain,
RoutingDetail detail, RoutingDetail detail,
String sceneId) { String sceneId,List<RoutingDetailEquip> routingDetailEquip) {
ProdProcessExec prodProcessExec = new ProdProcessExec(); ProdProcessExec prodProcessExec = new ProdProcessExec();
prodProcessExec.setExecId(UUID.randomUUID().toString().replace("-", "")); prodProcessExec.setExecId(UUID.randomUUID().toString().replace("-", ""));
...@@ -653,7 +654,18 @@ public class LanuchServiceImpl implements LanuchService { ...@@ -653,7 +654,18 @@ public class LanuchServiceImpl implements LanuchService {
prodProcessExec.setRoutingDetailId(detail.getId()); prodProcessExec.setRoutingDetailId(detail.getId());
prodProcessExec.setTaskSeq(detail.getTaskSeq()); prodProcessExec.setTaskSeq(detail.getTaskSeq());
prodProcessExec.setRoutingDetailName(detail.getName()); prodProcessExec.setRoutingDetailName(detail.getName());
prodProcessExec.setMachineId(detail.getEquipTypeId());
RoutingDetailEquip routingDetailEquip1 = routingDetailEquip.stream().
filter(detailEquip -> detailEquip.getRoutingDetailId().equals(detail.getId()))
.filter(detailEquip -> detailEquip.getType1() != null)
.filter(detailEquip -> detailEquip.getIsdeleted() == 0)
.findFirst()
.orElse(null);
prodProcessExec.setMachineId(routingDetailEquip1.getType1());
prodProcessExec.setRuntime(detail.getRuntime()); prodProcessExec.setRuntime(detail.getRuntime());
prodProcessExec.setSingleOut(detail.getSingleOut()); prodProcessExec.setSingleOut(detail.getSingleOut());
if (detail.getEquipTypeId() != null) if (detail.getEquipTypeId() != null)
......
...@@ -1725,6 +1725,8 @@ private GlobalParam InitGlobalParam() ...@@ -1725,6 +1725,8 @@ private GlobalParam InitGlobalParam()
maintenanceWindow.setStartTime(equipMaintainTask.getPlanStartTime()); maintenanceWindow.setStartTime(equipMaintainTask.getPlanStartTime());
maintenanceWindow.setEndTime(equipMaintainTask.getPlanFinishTime()); maintenanceWindow.setEndTime(equipMaintainTask.getPlanFinishTime());
maintenanceWindow.setReason(""); maintenanceWindow.setReason("");
maintenanceWindow.setEquipCode(equipMaintainTask.getEquipCode());
maintenanceWindow.setEquipName(equipMaintainTask.getEquipName());
maintenanceWindows.add(maintenanceWindow); maintenanceWindows.add(maintenanceWindow);
} }
...@@ -1881,4 +1883,62 @@ private GlobalParam InitGlobalParam() ...@@ -1881,4 +1883,62 @@ private GlobalParam InitGlobalParam()
} }
}
\ No newline at end of file
public List<Machine> InitCalendarToAllMachines3(Chromosome chromosome) {
List<Machine> machines = chromosome.getInitMachines();
Set<Long> machineIds = chromosome.getResult().stream()
.map(GAScheduleResult::getMachineId)
.collect(Collectors.toSet());
machines = machines.stream()
.filter(machine -> machineIds.contains(machine.getId()))
.collect(Collectors.toList());
for (Machine machine:machines) {
{
List<Shift> result = new ArrayList<>();
List<Shift> shifts = machine.getShifts();
for (Shift shift : shifts) {
// 处理跨天班次(开始时间晚于结束时间的情况,如 7:30 到 3:30)
if (shift.getEndTime().isBefore(shift.getStartTime())) {
// 创建第一天的班次 (开始时间到24:00)
Shift firstShift = new Shift();
firstShift.setStartTime(shift.getStartTime());
firstShift.setEndTime(LocalTime.of(23, 59, 59)); // 23:59:59代替24:00
firstShift.setDays(new HashSet<>(shift.getDays()));
firstShift.setStatus(shift.getStatus());
firstShift.setStartDate(shift.getStartDate());
firstShift.setEndDate(shift.getEndDate());
firstShift.setSpecial(shift.isSpecial());
// 创建第二天的班次 (00:00到结束时间)
Shift secondShift = new Shift();
secondShift.setStartTime(LocalTime.MIDNIGHT);
secondShift.setEndTime(shift.getEndTime());
secondShift.setDays(new HashSet<>(shift.getDays()));
secondShift.setStatus(shift.getStatus());
secondShift.setStartDate(shift.getStartDate().plusDays(1));
secondShift.setEndDate(shift.getEndDate().plusDays(1));
secondShift.setSpecial(shift.isSpecial());
result.add(firstShift);
result.add(secondShift);
} else {
// 正常班次直接添加
result.add(shift);
}
}
machine.setShifts(result);
}
}
return machines;
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment