Compare commits
48 Commits
2c834b9b2f
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| e30884ee09 | |||
| aa1357cf13 | |||
| 80e90cf87f | |||
| b48c17821d | |||
| 487fffc2d2 | |||
| 1e7e639ee0 | |||
| 4f71fc815b | |||
| 1cde930bb1 | |||
| c9125c8902 | |||
| 59bd191810 | |||
| 7a16b0643e | |||
| 2509b30382 | |||
| ec716df946 | |||
| abe0315536 | |||
| 4252b3f514 | |||
| c597c3c01f | |||
| 4933c2c14e | |||
| 3d0ba1d77c | |||
| 0cd8455c9d | |||
| ced438c725 | |||
| 9bea71e414 | |||
| 2ea04b98f8 | |||
| 8afd87b690 | |||
| 71bb45f6a0 | |||
| 931804555f | |||
| ae01a2aa01 | |||
| c3a6661d2a | |||
| 1de4f9db8d | |||
| 65d99bb7a8 | |||
| 39b04d8b73 | |||
| 4d5f966b0a | |||
| 0cd142bb82 | |||
| bcaaf1da4f | |||
| d310c5ae7b | |||
| 1e38170420 | |||
| 4330be8d0e | |||
| 28cd9c131b | |||
| 27a5dc8e02 | |||
| 243a42ca5c | |||
| b56d57af44 | |||
| 012939829c | |||
| 82027fc6aa | |||
| 6610e06991 | |||
| 40655dd557 | |||
| 5079f17df0 | |||
| 913dea7afa | |||
| 6f48a06438 | |||
| 6941954e14 |
6
.gitignore
vendored
6
.gitignore
vendored
@@ -53,6 +53,11 @@ nbdist/
|
||||
!*/build/*.xml
|
||||
modeler/pnpm-lock.yaml
|
||||
|
||||
# Application configuration files (may contain sensitive info)
|
||||
**/application.yml
|
||||
**/application-*.yml
|
||||
!**/application-example.yml
|
||||
|
||||
######################################################################
|
||||
# Mock bundled cache files
|
||||
**/*.bundled_*.mjs
|
||||
@@ -60,3 +65,4 @@ modeler/pnpm-lock.yaml
|
||||
**/___*.bundled_*.mjs
|
||||
modeler/types/components.d.ts
|
||||
modeler/types/auto-imports.d.ts
|
||||
.DS_Store
|
||||
|
||||
@@ -81,6 +81,21 @@
|
||||
<artifactId>solution-scene</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- 单元测试依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Security 测试支持(如果接口有权限控制) -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -3,20 +3,14 @@ package com.solution.web.controller.behaviour;
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.solution.system.domain.PlatFormDTO;
|
||||
import com.solution.web.core.BehaviortreeProcessor;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.checkerframework.checker.units.qual.A;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import com.solution.common.annotation.Log;
|
||||
import com.solution.common.core.controller.BaseController;
|
||||
import com.solution.common.core.domain.AjaxResult;
|
||||
@@ -93,7 +87,7 @@ public class BehaviortreeController extends BaseController
|
||||
@PreAuthorize("@ss.hasPermi('system:behaviortree:add')")
|
||||
@Log(title = "行为树主", businessType = BusinessType.INSERT)
|
||||
@PostMapping
|
||||
public AjaxResult add(@RequestBody Behaviortree behaviortree)
|
||||
public AjaxResult add(@RequestBody Behaviortree behaviortree)
|
||||
{
|
||||
return toAjax(behaviortreeProcessor.create(behaviortree));
|
||||
}
|
||||
@@ -158,4 +152,14 @@ public class BehaviortreeController extends BaseController
|
||||
return success(behaviortreeService.getCommander(scenarioId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改平台关联的行为树id
|
||||
* @param platFormDTO
|
||||
* @return
|
||||
*/
|
||||
@ApiOperation("修改平台关联的行为树id")
|
||||
@PutMapping("/behaviortreeId")
|
||||
public AjaxResult updateBehaviortreeId(@RequestBody PlatFormDTO platFormDTO){
|
||||
return toAjax(behaviortreeService.updateBehaviortreeId(platFormDTO));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ public class FireRuleController extends BaseController {
|
||||
/**
|
||||
* 开始执行规则匹配
|
||||
* @param task 敌方参数
|
||||
* @return
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/rule")
|
||||
@ApiOperation("开始执行规则匹配")
|
||||
|
||||
@@ -5,10 +5,15 @@ import com.solution.common.core.controller.BaseController;
|
||||
import com.solution.common.core.domain.AjaxResult;
|
||||
import com.solution.common.core.page.TableDataInfo;
|
||||
import com.solution.common.enums.BusinessType;
|
||||
import com.solution.common.utils.poi.ExcelUtil;
|
||||
import com.solution.rule.domain.Rule;
|
||||
import com.solution.rule.domain.config.RuleConfig;
|
||||
import com.solution.rule.domain.config.RuleConfigExcelRow;
|
||||
import com.solution.rule.domain.config.RuleConfigQuery;
|
||||
import com.solution.rule.domain.config.RuleParamMeta;
|
||||
import com.solution.rule.domain.config.vo.RuleDecisionTreeVO;
|
||||
import com.solution.rule.domain.config.vo.RuleFourBlocksGraphVO;
|
||||
import com.solution.rule.domain.config.vo.RuleGraphVO;
|
||||
import com.solution.rule.service.IRuleService;
|
||||
import com.solution.rule.service.IRuleConfigService;
|
||||
import io.swagger.annotations.Api;
|
||||
@@ -16,7 +21,9 @@ import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.List;
|
||||
|
||||
@Api("红蓝对抗规则管理")
|
||||
@@ -77,6 +84,34 @@ import java.util.List;
|
||||
return getDataTable(ruleConfigService.selectRuleConfigList(query));
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('system:rule:list')")
|
||||
@GetMapping("/config/graph")
|
||||
@ApiOperation("规则知识图谱(与列表相同的分页与筛选条件)")
|
||||
public AjaxResult configGraph(RuleConfigQuery query) {
|
||||
startPage();
|
||||
List<RuleConfig> list = ruleConfigService.selectRuleConfigList(query);
|
||||
RuleGraphVO graph = ruleConfigService.buildKnowledgeGraph(list);
|
||||
return success(graph);
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('system:rule:list')")
|
||||
@GetMapping("/config/decision-tree")
|
||||
@ApiOperation("规则决策树(围绕装备/目标/阵位/航迹四类规则,展示参数进入后的决策路径)")
|
||||
public AjaxResult configDecisionTree(RuleConfigQuery query) {
|
||||
startPage();
|
||||
List<RuleConfig> list = ruleConfigService.selectRuleConfigList(query);
|
||||
RuleDecisionTreeVO tree = ruleConfigService.buildDecisionTree(list);
|
||||
return success(tree);
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('system:rule:list')")
|
||||
@GetMapping("/config/graph/four-blocks")
|
||||
@ApiOperation("四块规则知识图谱(装备/目标/阵位/航迹;参数值与运行时 globalParams 一致)")
|
||||
public AjaxResult configGraphFourBlocks() {
|
||||
RuleFourBlocksGraphVO vo = ruleConfigService.buildFourBlocksKnowledgeGraph();
|
||||
return success(vo);
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('system:rule:query')")
|
||||
@GetMapping("/config/{ruleCode}")
|
||||
@ApiOperation("查询规则聚合详情")
|
||||
@@ -122,4 +157,26 @@ import java.util.List;
|
||||
List<RuleParamMeta> metas = ruleConfigService.selectParamMetaList();
|
||||
return success(metas);
|
||||
}
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('system:rule:query')")
|
||||
@Log(title = "Rule Config", businessType = BusinessType.EXPORT)
|
||||
@PostMapping("/config/export")
|
||||
@ApiOperation("Export rule config")
|
||||
public void exportConfig(HttpServletResponse response, @RequestBody(required = false) RuleConfigQuery query) {
|
||||
List<RuleConfigExcelRow> rows = ruleConfigService.exportRuleConfigRows(query == null ? new RuleConfigQuery() : query);
|
||||
ExcelUtil<RuleConfigExcelRow> util = new ExcelUtil<>(RuleConfigExcelRow.class);
|
||||
util.exportExcel(response, rows, "rule-config");
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('system:rule:edit')")
|
||||
@Log(title = "Rule Config", businessType = BusinessType.IMPORT)
|
||||
@PostMapping("/config/importData")
|
||||
@ApiOperation("Import rule config")
|
||||
public AjaxResult importConfig(MultipartFile file,
|
||||
@RequestParam(value = "updateSupport", defaultValue = "true") boolean updateSupport) throws Exception {
|
||||
ExcelUtil<RuleConfigExcelRow> util = new ExcelUtil<>(RuleConfigExcelRow.class);
|
||||
List<RuleConfigExcelRow> rows = util.importExcel(file.getInputStream());
|
||||
String result = ruleConfigService.importRuleConfigRows(rows, updateSupport);
|
||||
return success(result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,9 +247,23 @@ public class BehaviortreeProcessor {
|
||||
//获取行为树重复名称个数
|
||||
Integer num = behaviortreeService.getCountName(newName);
|
||||
if(num > 0){
|
||||
Integer count = num + 1;
|
||||
behaviortree.setName(newName + count);
|
||||
behaviortree.setEnglishName(newEnglishName + count);
|
||||
// 从2开始尝试,因为基础名称已经存在
|
||||
int count = 2;
|
||||
String finalName;
|
||||
String finalEnglishName;
|
||||
do {
|
||||
finalName = newName + "_" + count;
|
||||
finalEnglishName = newEnglishName + "_" + count;
|
||||
// 检查当前生成的名称是否存在
|
||||
num = behaviortreeService.getCountName(finalName);
|
||||
count++;
|
||||
} while(num > 0);
|
||||
|
||||
behaviortree.setName(finalName);
|
||||
behaviortree.setEnglishName(finalEnglishName);
|
||||
} else {
|
||||
behaviortree.setName(newName);
|
||||
behaviortree.setEnglishName(newEnglishName);
|
||||
}
|
||||
return this.create(behaviortree);
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ public class Nodeparameter extends BaseEntity
|
||||
@Excel(name = "节点实例设置的具体参数值 (覆盖模板默认值)")
|
||||
private String value;
|
||||
|
||||
private int groupIndex;
|
||||
private Integer groupIndex;
|
||||
|
||||
public void setId(Long id)
|
||||
{
|
||||
@@ -48,6 +48,14 @@ public class Nodeparameter extends BaseEntity
|
||||
return treeId;
|
||||
}
|
||||
|
||||
public Integer getGroupIndex() {
|
||||
return groupIndex;
|
||||
}
|
||||
|
||||
public void setGroupIndex(Integer groupIndex) {
|
||||
this.groupIndex = groupIndex;
|
||||
}
|
||||
|
||||
public void setTreeId(Long treeId) {
|
||||
this.treeId = treeId;
|
||||
}
|
||||
@@ -82,13 +90,6 @@ public class Nodeparameter extends BaseEntity
|
||||
return value;
|
||||
}
|
||||
|
||||
public int getGroupIndex() {
|
||||
return groupIndex;
|
||||
}
|
||||
|
||||
public void setGroupIndex(int groupIndex) {
|
||||
this.groupIndex = groupIndex;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.solution.system.domain;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class PlatFormDTO {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private Integer behaviortreeId;
|
||||
|
||||
}
|
||||
@@ -39,11 +39,11 @@ public class Treenodeinstance extends BaseEntity
|
||||
private Long preconditionTempleteId;
|
||||
|
||||
@Excel(name = "节点介绍")
|
||||
private String desciption;
|
||||
private String nodeValue;
|
||||
|
||||
/** $column.columnComment */
|
||||
@Excel(name = "${comment}", readConverterExp = "$column.readConverterExp()")
|
||||
private String uuid;
|
||||
@Excel(name = "是否外部节点", readConverterExp = "0=否,1=是")
|
||||
private String isExtern;
|
||||
|
||||
public void setId(Long id)
|
||||
{
|
||||
@@ -105,36 +105,33 @@ public class Treenodeinstance extends BaseEntity
|
||||
return preconditionTempleteId;
|
||||
}
|
||||
|
||||
public void setUuid(String uuid)
|
||||
{
|
||||
this.uuid = uuid;
|
||||
public String getNodeValue() {
|
||||
return nodeValue;
|
||||
}
|
||||
|
||||
public String getUuid()
|
||||
{
|
||||
return uuid;
|
||||
public void setNodeValue(String nodeValue) {
|
||||
this.nodeValue = nodeValue;
|
||||
}
|
||||
|
||||
public String getDesciption() {
|
||||
return desciption;
|
||||
public String getIsExtern() {
|
||||
return isExtern;
|
||||
}
|
||||
|
||||
public void setDesciption(String desciption) {
|
||||
this.desciption = desciption;
|
||||
public void setIsExtern(String isExtern) {
|
||||
this.isExtern = isExtern;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
|
||||
.append("id", getId())
|
||||
.append("treeId", getTreeId())
|
||||
.append("templateId", getTemplateId())
|
||||
.append("instanceName", getInstanceName())
|
||||
.append("isRoot", getIsRoot())
|
||||
.append("preconditionTempleteId", getPreconditionTempleteId())
|
||||
.append("uuid", getUuid())
|
||||
.append("desciption", getDesciption())
|
||||
.toString();
|
||||
return "Treenodeinstance{" +
|
||||
"id=" + id +
|
||||
", treeId=" + treeId +
|
||||
", templateId=" + templateId +
|
||||
", instanceName='" + instanceName + '\'' +
|
||||
", isRoot=" + isRoot +
|
||||
", preconditionTempleteId=" + preconditionTempleteId +
|
||||
", nodeValue='" + nodeValue + '\'' +
|
||||
", isExtern='" + isExtern + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.solution.system.mapper;
|
||||
|
||||
import com.solution.system.domain.PlatFormDTO;
|
||||
import com.solution.system.domain.PlatformTree;
|
||||
import com.solution.system.domain.PlatformVO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
@@ -32,4 +33,11 @@ public interface PlatformMapper {
|
||||
* @return
|
||||
*/
|
||||
List<PlatformVO> getPlatformByEnglishName(@Param("underlingEnglishName") List<String> underlingEnglishName);
|
||||
|
||||
/**
|
||||
* 修改平台关联的行为树id
|
||||
* @param platFormDTO
|
||||
* @return
|
||||
*/
|
||||
Integer updateBehaviortreeId(PlatFormDTO platFormDTO);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.solution.system.service;
|
||||
import java.util.List;
|
||||
|
||||
import com.solution.system.domain.Behaviortree;
|
||||
import com.solution.system.domain.PlatFormDTO;
|
||||
import com.solution.system.domain.PlatformChiefCommander;
|
||||
import com.solution.system.domain.PlatformVO;
|
||||
|
||||
@@ -35,7 +36,6 @@ public interface IBehaviortreeService
|
||||
|
||||
/**
|
||||
* 新增行为树主
|
||||
*
|
||||
* @param behaviortree 行为树主
|
||||
* @return 结果
|
||||
*/
|
||||
@@ -85,4 +85,11 @@ public interface IBehaviortreeService
|
||||
* @return
|
||||
*/
|
||||
Integer getCountName(String newName);
|
||||
|
||||
/**
|
||||
* 修改平台关联的行为树id
|
||||
* @param platFormDTO
|
||||
* @return
|
||||
*/
|
||||
Integer updateBehaviortreeId(PlatFormDTO platFormDTO);
|
||||
}
|
||||
|
||||
@@ -5,15 +5,12 @@ import java.util.List;
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.solution.common.constant.ExceptionConstants;
|
||||
import com.solution.system.domain.PlatformChiefCommander;
|
||||
import com.solution.system.domain.PlatformTree;
|
||||
import com.solution.system.domain.PlatformVO;
|
||||
import com.solution.system.domain.*;
|
||||
import com.solution.system.mapper.PlatformCommunicationMapper;
|
||||
import com.solution.system.mapper.PlatformMapper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import com.solution.system.mapper.BehaviortreeMapper;
|
||||
import com.solution.system.domain.Behaviortree;
|
||||
import com.solution.system.service.IBehaviortreeService;
|
||||
|
||||
/**
|
||||
@@ -156,4 +153,17 @@ public class BehaviortreeServiceImpl implements IBehaviortreeService
|
||||
public Integer getCountName(String newName) {
|
||||
return behaviortreeMapper.getCountName(newName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改平台关联的行为树id
|
||||
* @param platFormDTO
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public Integer updateBehaviortreeId(PlatFormDTO platFormDTO) {
|
||||
if(ObjectUtil.isEmpty(platFormDTO)){
|
||||
throw new RuntimeException(ExceptionConstants.PARAMETER_EXCEPTION);
|
||||
}
|
||||
return platformMapper.updateBehaviortreeId(platFormDTO);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import com.solution.system.service.INodeparameterService;
|
||||
* @date 2026-02-05
|
||||
*/
|
||||
@Service
|
||||
public class NodeparameterServiceImpl implements INodeparameterService
|
||||
public class NodeparameterServiceImpl implements INodeparameterService
|
||||
{
|
||||
@Autowired
|
||||
private NodeparameterMapper nodeparameterMapper;
|
||||
|
||||
@@ -72,6 +72,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="englishName != null and englishName != ''">english_name,</if>
|
||||
<if test="xmlContent != null">xml_content,</if>
|
||||
<if test="platformId != null">platform_id,</if>
|
||||
<if test="scenarioId != null">scenario_id,</if>
|
||||
</trim>
|
||||
<trim prefix="values (" suffix=")" suffixOverrides=",">
|
||||
<if test="name != null and name != ''">#{name},</if>
|
||||
@@ -81,6 +82,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="englishName != null and englishName != ''">#{englishName},</if>
|
||||
<if test="xmlContent != null">#{xmlContent},</if>
|
||||
<if test="platformId != null">#{platformId},</if>
|
||||
<if test="scenarioId != null">#{scenarioId},</if>
|
||||
</trim>
|
||||
</insert>
|
||||
|
||||
|
||||
@@ -18,15 +18,18 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
</delete>
|
||||
|
||||
<sql id="selectNodeparameterVo">
|
||||
select id, treeId, node_instance_id, param_def_id,`value`, group_index from nodeparameter
|
||||
select id, tree_id, node_instance_id, param_def_id,`value`, group_index from nodeparameter
|
||||
</sql>
|
||||
|
||||
<select id="selectNodeparameterList" parameterType="Nodeparameter" resultMap="NodeparameterResult">
|
||||
<include refid="selectNodeparameterVo"/>
|
||||
<where>
|
||||
<where>
|
||||
<if test="id != null"> and id = #{id}</if>
|
||||
<if test="treeId != null"> and tree_id = #{treeId}</if>
|
||||
<if test="nodeInstanceId != null "> and node_instance_id = #{nodeInstanceId}</if>
|
||||
<if test="paramDefId != null "> and param_def_id = #{paramDefId}</if>
|
||||
<if test="value != null and value != ''"> and value = #{value}</if>
|
||||
<if test="value != null and value != ''"> and `value` = #{value}</if>
|
||||
<if test="groupIndex != null"> and group_index = #{groupIndex}</if>
|
||||
</where>
|
||||
</select>
|
||||
|
||||
|
||||
@@ -3,8 +3,11 @@
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.solution.system.mapper.PlatformMapper">
|
||||
|
||||
|
||||
<update id="updateBehaviortreeId">
|
||||
UPDATE platform
|
||||
SET behaviortree_id = #{behaviortreeId}
|
||||
WHERE id = #{id}
|
||||
</update>
|
||||
|
||||
<select id="selectPlatformChineseName" resultType="java.lang.String"
|
||||
parameterType="java.util.List">
|
||||
|
||||
@@ -20,7 +20,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
|
||||
<select id="selectTemplateparameterdefList" parameterType="templateparameterdef" resultMap="TemplateparameterdefResult">
|
||||
<include refid="selectTemplateparameterdefVo"/>
|
||||
<where>
|
||||
<where>
|
||||
<if test="id != null"> and id = #{id}</if>
|
||||
<if test="templateId != null "> and template_id = #{templateId}</if>
|
||||
<if test="paramKey != null and paramKey != ''"> and param_key = #{paramKey}</if>
|
||||
<if test="dataType != null and dataType != ''"> and data_type = #{dataType}</if>
|
||||
|
||||
@@ -11,16 +11,16 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<result property="instanceName" column="instance_name" />
|
||||
<result property="isRoot" column="is_root" />
|
||||
<result property="preconditionTempleteId" column="precondition_templete_id" />
|
||||
<result property="uuid" column="uuid" />
|
||||
<result property="desciption" column="desciption" />
|
||||
<result property="nodeValue" column="node_value" />
|
||||
<result property="isExtern" column="is_extern" />
|
||||
</resultMap>
|
||||
|
||||
<delete id="deleteByTreeId">
|
||||
delete from treenodeinstance where tree_id=#{treeId}
|
||||
delete from treenodeinstance where tree_id = #{treeId}
|
||||
</delete>
|
||||
|
||||
<sql id="selectTreenodeinstanceVo">
|
||||
select id, tree_id, template_id, instance_name, is_root, precondition_templete_id, uuid,desciption from treenodeinstance
|
||||
select id, tree_id, template_id, instance_name, is_root, precondition_templete_id, node_value,is_extern from treenodeinstance
|
||||
</sql>
|
||||
|
||||
<select id="selectTreenodeinstanceList" parameterType="Treenodeinstance" resultMap="TreenodeinstanceResult">
|
||||
@@ -31,8 +31,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="instanceName != null and instanceName != ''"> and instance_name like concat('%', #{instanceName}, '%')</if>
|
||||
<if test="isRoot != null "> and is_root = #{isRoot}</if>
|
||||
<if test="preconditionTempleteId != null "> and precondition_templete_id = #{preconditionTempleteId}</if>
|
||||
<if test="uuid != null and uuid != ''"> and uuid = #{uuid}</if>
|
||||
<if test="desciption != null and desciption != ''"> and desciption = #{desciption}</if>
|
||||
<if test="nodeValue != null and nodeValue != ''"> and node_value = #{nodeValue}</if>
|
||||
<if test="isExtern != null and isExtern != ''"> and is_extern = #{isExtern}</if>
|
||||
</where>
|
||||
</select>
|
||||
|
||||
@@ -49,8 +49,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="instanceName != null">instance_name,</if>
|
||||
<if test="isRoot != null">is_root,</if>
|
||||
<if test="preconditionTempleteId != null">precondition_templete_id,</if>
|
||||
<if test="uuid != null">uuid,</if>
|
||||
<if test="desciption != null">desciption,</if>
|
||||
<if test="nodeValue != null">node_value,</if>
|
||||
<if test="isExtern != null">is_extern,</if>
|
||||
</trim>
|
||||
<trim prefix="values (" suffix=")" suffixOverrides=",">
|
||||
<if test="treeId != null">#{treeId},</if>
|
||||
@@ -58,8 +58,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="instanceName != null">#{instanceName},</if>
|
||||
<if test="isRoot != null">#{isRoot},</if>
|
||||
<if test="preconditionTempleteId != null">#{preconditionTempleteId},</if>
|
||||
<if test="uuid != null">#{uuid},</if>
|
||||
<if test="desciption != null">#{desciption},</if>
|
||||
<if test="nodeValue != null">#{node_value},</if>
|
||||
<if test="isExtern != null">#{is_extern},</if>
|
||||
</trim>
|
||||
</insert>
|
||||
|
||||
@@ -71,8 +71,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="instanceName != null">instance_name = #{instanceName},</if>
|
||||
<if test="isRoot != null">is_root = #{isRoot},</if>
|
||||
<if test="preconditionTempleteId != null">precondition_templete_id = #{preconditionTempleteId},</if>
|
||||
<if test="uuid != null">uuid = #{uuid},</if>
|
||||
<if test="desciption != null">desciption = #{desciption},</if>
|
||||
<if test="nodeValue != null">#{node_value},</if>
|
||||
<if test="isExtern != null">#{is_extern},</if>
|
||||
</trim>
|
||||
where id = #{id}
|
||||
</update>
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.solution.rule.controller;
|
||||
|
||||
import com.solution.rule.domain.tasks.Kj3PostResult;
|
||||
import com.solution.rule.service.Kj3TaskDataService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/rule/kj3")
|
||||
public class Kj3TaskDataController {
|
||||
|
||||
@Autowired
|
||||
private Kj3TaskDataService kj3TaskDataService;
|
||||
|
||||
/**
|
||||
* 接收外部传入的 kj-3 JSON,筛选红方任务并转换后 POST 到目标地址。
|
||||
*
|
||||
* @param kj3Json 外部请求体 JSON
|
||||
* @return 处理结果
|
||||
*/
|
||||
@PostMapping("/parse-and-post")
|
||||
public Kj3PostResult parseAndPost(@RequestBody String kj3Json) {
|
||||
return kj3TaskDataService.parseAndPostRedTasks(kj3Json);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,16 @@ public class BasicPlatform implements Serializable {
|
||||
|
||||
private String description;
|
||||
|
||||
private Integer behaviortreeId;
|
||||
|
||||
public Integer getBehaviortreeId() {
|
||||
return behaviortreeId;
|
||||
}
|
||||
|
||||
public void setBehaviortreeId(Integer behaviortreeId) {
|
||||
this.behaviortreeId = behaviortreeId;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.solution.rule.domain.config;
|
||||
|
||||
import com.solution.common.annotation.Excel;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class RuleConfigExcelRow {
|
||||
|
||||
@Excel(name = "规则编码")
|
||||
private String ruleCode;
|
||||
|
||||
@Excel(name = "规则名称")
|
||||
private String ruleName;
|
||||
|
||||
@Excel(name = "层级编码")
|
||||
private String levelCode;
|
||||
|
||||
@Excel(name = "类别编码")
|
||||
private String kindCode;
|
||||
|
||||
@Excel(name = "模块编码")
|
||||
private String moduleCode;
|
||||
|
||||
@Excel(name = "优先级", cellType = Excel.ColumnType.NUMERIC)
|
||||
private Integer priorityNo;
|
||||
|
||||
@Excel(name = "条件表达式", width = 24)
|
||||
private String conditionExpr;
|
||||
|
||||
@Excel(name = "动作表达式", width = 24)
|
||||
private String actionExpr;
|
||||
|
||||
@Excel(name = "版本号", cellType = Excel.ColumnType.NUMERIC)
|
||||
private Integer versionNo;
|
||||
|
||||
@Excel(name = "规则启用", cellType = Excel.ColumnType.NUMERIC, prompt = "1=启用,0=停用")
|
||||
private Integer enabled;
|
||||
|
||||
@Excel(name = "备注", width = 20)
|
||||
private String remark;
|
||||
|
||||
@Excel(name = "任务类型列表", width = 20, prompt = "多个任务类型用英文逗号分隔")
|
||||
private String taskTypesCsv;
|
||||
|
||||
@Excel(name = "参数名称")
|
||||
private String paramName;
|
||||
|
||||
@Excel(name = "参数键")
|
||||
private String paramKey;
|
||||
|
||||
@Excel(name = "参数值", width = 24)
|
||||
private String paramVal;
|
||||
|
||||
@Excel(name = "参数值类型")
|
||||
private String valType;
|
||||
|
||||
@Excel(name = "参数排序", cellType = Excel.ColumnType.NUMERIC)
|
||||
private Integer sortNo;
|
||||
|
||||
@Excel(name = "参数启用", cellType = Excel.ColumnType.NUMERIC, prompt = "1=启用,0=停用")
|
||||
private Integer paramEnabled;
|
||||
|
||||
@Excel(name = "参数备注", width = 20)
|
||||
private String paramRemark;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.solution.rule.domain.config;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* rule_item_task_type 批量查询行
|
||||
*/
|
||||
@Data
|
||||
public class RuleConfigTaskTypeRow implements Serializable {
|
||||
|
||||
private String ruleCode;
|
||||
|
||||
private String taskTypeCode;
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.solution.rule.domain.config.graph;
|
||||
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 与 {@code rules/rule.drl} 中「装备/目标/阵位/航迹」四个主规则一一对应,仅用于知识图谱分块展示(与 module_code 一致)。
|
||||
|
||||
*/
|
||||
|
||||
public enum RuleFourBlockDefinition {
|
||||
|
||||
|
||||
|
||||
EQUIPMENT(
|
||||
|
||||
"equipment",
|
||||
|
||||
"装备匹配",
|
||||
|
||||
100,
|
||||
|
||||
Arrays.asList(
|
||||
|
||||
"抽取蓝方任务与武器文案、红方装备类型与名称等,拼接为可对齐的蓝/红文本特征",
|
||||
|
||||
"规则槽关键词与兼容层叠加计分,再乘以全局权重得到每件红装的匹配总分",
|
||||
|
||||
"低于最低入选分则丢弃;并列最高分按既定策略决胜,并写入火力输入与任务名后缀"),
|
||||
|
||||
"DroolsFact(task != null)",
|
||||
|
||||
"mergeDefaultParams(globalParams); equipmentRule($fact, globalParams);"),
|
||||
|
||||
TARGET(
|
||||
|
||||
"target",
|
||||
|
||||
"目标匹配",
|
||||
|
||||
90,
|
||||
|
||||
Arrays.asList(
|
||||
|
||||
"根据命中率映射、射程解析与分配模式,确定每套红方可承载的目标数量与目标标识",
|
||||
|
||||
"向任务 execute 写入目标列表与默认行动类型等执行侧字段",
|
||||
|
||||
"命中率低于阈值时,在轮次与件数限制内补充选取装备并更新任务"),
|
||||
|
||||
"DroolsFact(task != null)",
|
||||
|
||||
"mergeDefaultParams(globalParams); target($fact, globalParams);"),
|
||||
|
||||
POSITION(
|
||||
|
||||
"position",
|
||||
|
||||
"阵位匹配",
|
||||
|
||||
80,
|
||||
|
||||
Arrays.asList(
|
||||
|
||||
"结合锚点模式、航向与部署距离区间、编队样式与间距,计算红方平台目标点位",
|
||||
|
||||
"按平台最小间距离散多个平台坐标,必要时叠加上述默认高度与跟随比例",
|
||||
|
||||
"若启用作战区约束,将越界阵位沿策略回拉到战争区内"),
|
||||
|
||||
"DroolsFact(task != null)",
|
||||
|
||||
"mergeDefaultParams(globalParams); position($fact, globalParams);"),
|
||||
|
||||
TRACK(
|
||||
|
||||
"track",
|
||||
|
||||
"航迹匹配",
|
||||
|
||||
70,
|
||||
|
||||
Arrays.asList(
|
||||
|
||||
"依据蓝方航迹与数据类型判定空中/地面航迹类别,选择对应变形算法生成航迹折线",
|
||||
|
||||
"生成航迹标识并与任务 execute 中的目标绑定移动路由",
|
||||
|
||||
"若启用航迹作战区约束,将航迹点约束在战争区多边形内"),
|
||||
|
||||
"DroolsFact(task != null)",
|
||||
|
||||
"mergeDefaultParams(globalParams); trackRoute($fact, globalParams);");
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.solution.rule.domain.config.graph;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 冻结「参数键 → 四大展示块」归属(与 rule.drl / {@code 002_rule_seed_from_drl.sql} 中的 rule_item.module_code 一致)。
|
||||
* 图谱优先按库表 rule_item_param.rule_code 所属模块归类;若某键仅存在于 globalParams 快照且无法关联模块时,再用本映射兜底。
|
||||
*/
|
||||
public final class RuleFourBlockParamMapping {
|
||||
|
||||
private static final Set<String> EQUIPMENT = set(
|
||||
"weight", "minSelectedScore", "tieBreak", "outputDrawNameSuffix", "ruleSlotCount",
|
||||
"blueRuleKeywords_1", "redRuleKeywords_1", "ruleScore_1",
|
||||
"blueRuleKeywords_2", "redRuleKeywords_2", "ruleScore_2",
|
||||
"blueRuleKeywords_3", "redRuleKeywords_3", "ruleScore_3",
|
||||
"bluePlatformKeywords_air", "redPreferredWhenBlueAir", "airScore",
|
||||
"airTaskKeywords", "airTaskScore",
|
||||
"groundTaskKeywords", "redPreferredWhenGround", "groundScore",
|
||||
"tankKeywords", "redMatchKeywords_tank", "tankScore",
|
||||
"missileKeywords", "redMatchKeywords_missile", "missileScore");
|
||||
private static final Set<String> TARGET = set(
|
||||
"executeTypeDefault", "targetPickMode", "minTargetsPerRed", "maxTargetsPerRedCap",
|
||||
"radToTargetsCsv", "rangeParseRegex", "rangeUnit", "minRangeToAllowAssignKm",
|
||||
"redHitRateThreshold", "maxExtraWeaponsPerTask", "maxSupplementRounds", "extraPickMinScore");
|
||||
private static final Set<String> POSITION = set(
|
||||
"positionRuleEnabled", "positionAnchorMode", "trackPointDirectionMode",
|
||||
"fallbackBearingDeg", "deployDistanceKmMin", "deployDistanceKmMax", "deployDistanceKmDefault",
|
||||
"distanceByPlatformCsv", "formationType", "formationSpacingMeters", "formationHeadingOffsetDeg",
|
||||
"defaultDeployHeight", "heightFollowBlueRatio", "enableWarZoneClamp", "warZoneClampMode",
|
||||
"minInterPlatformDistanceMeters");
|
||||
private static final Set<String> TRACK = set(
|
||||
"trackRuleEnabled", "trackRouteAlgorithm", "trackRouteNameSuffix",
|
||||
"trackAirDataTypeCsv", "trackAirKeywordsCsv", "trackGroundTrackType",
|
||||
"trackFallbackBearingDeg", "enableTrackWarZoneClamp",
|
||||
"trackExtraNodesMax", "trackShortPathSegments",
|
||||
"trackFlankOffsetMeters", "trackFlankSideMode",
|
||||
"trackJamWobbleMeters", "trackJamSegments");
|
||||
|
||||
private RuleFourBlockParamMapping() {
|
||||
}
|
||||
|
||||
private static Set<String> set(String... keys) {
|
||||
return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(keys)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param paramKey 参数键
|
||||
* @param slotRuleKeys 形如 blueRuleKeywords_i / redRuleKeywords_i / ruleScore_i,视为装备块
|
||||
*/
|
||||
public static RuleFourBlockDefinition fallbackBlockForKey(String paramKey, boolean slotRuleKeys) {
|
||||
if (paramKey == null || paramKey.isEmpty()) {
|
||||
return RuleFourBlockDefinition.EQUIPMENT;
|
||||
}
|
||||
String k = paramKey.trim();
|
||||
if (slotRuleKeys) {
|
||||
return RuleFourBlockDefinition.EQUIPMENT;
|
||||
}
|
||||
if (EQUIPMENT.contains(k)) {
|
||||
return RuleFourBlockDefinition.EQUIPMENT;
|
||||
}
|
||||
if (TARGET.contains(k)) {
|
||||
return RuleFourBlockDefinition.TARGET;
|
||||
}
|
||||
if (POSITION.contains(k)) {
|
||||
return RuleFourBlockDefinition.POSITION;
|
||||
}
|
||||
if (TRACK.contains(k)) {
|
||||
return RuleFourBlockDefinition.TRACK;
|
||||
}
|
||||
String lower = k.toLowerCase(Locale.ROOT);
|
||||
if (lower.startsWith("track")) {
|
||||
return RuleFourBlockDefinition.TRACK;
|
||||
}
|
||||
if (lower.startsWith("position") || lower.startsWith("deploy") || lower.startsWith("formation")
|
||||
|| lower.contains("warzone") || lower.contains("platform")) {
|
||||
return RuleFourBlockDefinition.POSITION;
|
||||
}
|
||||
if (lower.contains("target") || lower.contains("execute") || lower.contains("assign") || lower.contains("supplement")) {
|
||||
return RuleFourBlockDefinition.TARGET;
|
||||
}
|
||||
return RuleFourBlockDefinition.EQUIPMENT;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.solution.rule.domain.config.graph;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 四块图谱展示用:每条 rule_item 对应的「运行时产出/写回」中文说明(静态目录,与 RuleFunction 行为一致即可)。
|
||||
*/
|
||||
public final class RuleFourBlockRuleOutputCatalog {
|
||||
|
||||
private static final Map<String, Map<String, List<String>>> BY_MODULE_AND_RULE = new HashMap<>();
|
||||
|
||||
static {
|
||||
Map<String, List<String>> equipment = new HashMap<>();
|
||||
equipment.put("R_TASK_SELECT_BASE", list(
|
||||
"汇总匹配结果并写入火力规则输入(fireRuleInputs 等匹配行)",
|
||||
"为任务名称追加输出后缀(outputDrawNameSuffix)"));
|
||||
equipment.put("R_TASK_SELECT_SLOT_1", list(
|
||||
"若槽1蓝红关键词同时命中,为当前候选装备累加 ruleScore_1×weight 分值"));
|
||||
equipment.put("R_TASK_SELECT_SLOT_2", list(
|
||||
"若槽2蓝红关键词同时命中,累加 ruleScore_2×weight 分值"));
|
||||
equipment.put("R_TASK_SELECT_SLOT_3", list(
|
||||
"若槽3蓝红关键词同时命中,累加 ruleScore_3×weight 分值"));
|
||||
equipment.put("R_TASK_REL_AIR_PLATFORM", list(
|
||||
"空中平台关键词命中时累加 airScore×weight 兼容层分值"));
|
||||
equipment.put("R_TASK_REL_AIR_TASK", list(
|
||||
"空中任务文案命中时累加 airTaskScore×weight 分值"));
|
||||
equipment.put("R_TASK_REL_GROUND_TASK", list(
|
||||
"地面任务与红方偏好同时命中时累加 groundScore×weight 分值"));
|
||||
equipment.put("R_TASK_REL_TANK", list(
|
||||
"坦克类关键词匹配时累加 tankScore×weight 分值"));
|
||||
equipment.put("R_TASK_REL_MISSILE", list(
|
||||
"导弹类关键词匹配时累加 missileScore×weight 分值"));
|
||||
BY_MODULE_AND_RULE.put("equipment", Collections.unmodifiableMap(equipment));
|
||||
|
||||
Map<String, List<String>> target = new HashMap<>();
|
||||
target.put("R_TASK_ASSIGN_TARGET", list(
|
||||
"填充任务 execute 中目标列表与默认行动类型(executeTypeDefault 等)",
|
||||
"按命中率映射与分配模式更新 targetId / 目标数量"));
|
||||
target.put("R_TASK_LIMIT_SUPPLEMENT", list(
|
||||
"命中率低于阈值时按轮次与件数上限补充选取装备并回写任务武器列表"));
|
||||
BY_MODULE_AND_RULE.put("target", Collections.unmodifiableMap(target));
|
||||
|
||||
Map<String, List<String>> position = new HashMap<>();
|
||||
position.put("R_PLATFORM_DEPLOY", list(
|
||||
"计算并写回红方 SubComponents.platform[].positions(部署点、编队间距与高度)"));
|
||||
position.put("R_PLATFORM_SPACETIME", list(
|
||||
"在启用作战区约束时,将越界阵位回拉到 warZoneLocation 多边形内"));
|
||||
BY_MODULE_AND_RULE.put("position", Collections.unmodifiableMap(position));
|
||||
|
||||
Map<String, List<String>> track = new HashMap<>();
|
||||
track.put("R_ACTION_TRACK_ROUTE", list(
|
||||
"生成/更新 TrackParam 中航迹节点,并为 execute 绑定 moveRouteId",
|
||||
"按算法(followBlue 等)变形蓝方航迹并写航迹名称后缀"));
|
||||
track.put("R_ACTION_TRACK_SPACETIME", list(
|
||||
"在启用约束时将航迹点限制在作战区边界内"));
|
||||
BY_MODULE_AND_RULE.put("track", Collections.unmodifiableMap(track));
|
||||
}
|
||||
|
||||
private RuleFourBlockRuleOutputCatalog() {
|
||||
}
|
||||
|
||||
private static List<String> list(String... lines) {
|
||||
List<String> l = new ArrayList<>();
|
||||
for (String s : lines) {
|
||||
if (s != null && !s.isEmpty()) {
|
||||
l.add(s);
|
||||
}
|
||||
}
|
||||
return Collections.unmodifiableList(l);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param moduleCode equipment / target / position / track
|
||||
* @param ruleCode rule_item.rule_code
|
||||
*/
|
||||
public static List<String> outputsForRule(String moduleCode, String ruleCode) {
|
||||
if (moduleCode == null || ruleCode == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
Map<String, List<String>> m = BY_MODULE_AND_RULE.get(moduleCode);
|
||||
if (m == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<String> list = m.get(ruleCode);
|
||||
return list != null ? list : Collections.emptyList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.solution.rule.domain.config.graph;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
|
||||
/**
|
||||
* 参数在「产出」列中的一行静态说明(与 globalParams 生效值拼接展示)。
|
||||
*/
|
||||
public final class RuleParamOutputHint {
|
||||
|
||||
private static final String GENERIC = "写入 globalParams 并由当前块对应 Java 算子读取";
|
||||
|
||||
private RuleParamOutputHint() {
|
||||
}
|
||||
|
||||
public static String effectLine(String paramKey, String moduleCode) {
|
||||
if (ObjectUtil.isEmpty(paramKey)) {
|
||||
return GENERIC;
|
||||
}
|
||||
String k = paramKey.trim();
|
||||
switch (k) {
|
||||
case "weight":
|
||||
return "参与装备/目标等环节的评分加权";
|
||||
case "minSelectedScore":
|
||||
return "低于该分则本规则对应环节不选中/不生效";
|
||||
case "tieBreak":
|
||||
return "同分时的决胜策略(如按装备 ID)";
|
||||
case "outputDrawNameSuffix":
|
||||
return "影响任务/输出名称后缀展示";
|
||||
case "ruleSlotCount":
|
||||
return "规则槽数量上限(装备匹配)";
|
||||
case "executeTypeDefault":
|
||||
return "写入任务 execute 的默认行动类型";
|
||||
case "targetPickMode":
|
||||
return "目标分配挑选模式(轮询/随机等)";
|
||||
case "radToTargetsCsv":
|
||||
return "命中率到目标数量的映射";
|
||||
case "redHitRateThreshold":
|
||||
return "命中率阈值,触发补拿等逻辑";
|
||||
case "maxExtraWeaponsPerTask":
|
||||
case "maxSupplementRounds":
|
||||
case "extraPickMinScore":
|
||||
return "补拿装备轮次与分数约束";
|
||||
case "positionRuleEnabled":
|
||||
case "trackRuleEnabled":
|
||||
case "groupRuleEnabled":
|
||||
return "控制对应环节是否执行";
|
||||
case "deployDistanceKmMin":
|
||||
case "deployDistanceKmMax":
|
||||
case "deployDistanceKmDefault":
|
||||
return "部署距离区间与默认值(阵位)";
|
||||
case "formationType":
|
||||
case "formationSpacingMeters":
|
||||
return "编队几何与间距";
|
||||
case "enableWarZoneClamp":
|
||||
case "enableTrackWarZoneClamp":
|
||||
return "作战区约束开关";
|
||||
case "trackRouteAlgorithm":
|
||||
return "航迹生成算法选择";
|
||||
default:
|
||||
if (k.startsWith("blueRuleKeywords_") || k.startsWith("redRuleKeywords_") || k.startsWith("ruleScore_")) {
|
||||
return "规则槽关键词/分值,参与装备匹配打分";
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(moduleCode) && "track".equals(moduleCode) && k.toLowerCase().startsWith("track")) {
|
||||
return "航迹生成与约束相关配置";
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(moduleCode) && "position".equals(moduleCode)) {
|
||||
return "阵位/部署与空间约束相关配置";
|
||||
}
|
||||
return GENERIC;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.solution.rule.domain.config.vo;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@ApiModel("单个规则决策树分块")
|
||||
public class RuleDecisionBlockVO implements Serializable {
|
||||
|
||||
@ApiModelProperty("分块标识:equipment/target/position/track")
|
||||
private String blockId;
|
||||
|
||||
@ApiModelProperty("模块编码")
|
||||
private String moduleCode;
|
||||
|
||||
@ApiModelProperty("标题")
|
||||
private String title;
|
||||
|
||||
@ApiModelProperty("Drools 规则名")
|
||||
private String droolsRuleName;
|
||||
|
||||
@ApiModelProperty("salience")
|
||||
private Integer salience;
|
||||
|
||||
@ApiModelProperty("树节点")
|
||||
private List<RuleDecisionNodeVO> nodes;
|
||||
|
||||
public List<RuleDecisionNodeVO> safeNodes() {
|
||||
if (nodes == null) {
|
||||
nodes = new ArrayList<>();
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.solution.rule.domain.config.vo;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@ApiModel("规则决策树节点")
|
||||
public class RuleDecisionNodeVO implements Serializable {
|
||||
|
||||
@ApiModelProperty("节点唯一键")
|
||||
private String key;
|
||||
|
||||
@ApiModelProperty("节点标题")
|
||||
private String title;
|
||||
|
||||
@ApiModelProperty("节点类型")
|
||||
private String nodeType;
|
||||
|
||||
@ApiModelProperty("补充说明")
|
||||
private String description;
|
||||
|
||||
@ApiModelProperty("右侧值文本")
|
||||
private String valueText;
|
||||
|
||||
@ApiModelProperty("子节点")
|
||||
private List<RuleDecisionNodeVO> children;
|
||||
|
||||
public List<RuleDecisionNodeVO> safeChildren() {
|
||||
if (children == null) {
|
||||
children = new ArrayList<>();
|
||||
}
|
||||
return children;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.solution.rule.domain.config.vo;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
@ApiModel("规则决策树")
|
||||
public class RuleDecisionTreeVO implements Serializable {
|
||||
|
||||
@ApiModelProperty("与运行时 globalParams 一致的参数快照")
|
||||
private Map<String, Object> globalParamsPreview;
|
||||
|
||||
@ApiModelProperty("四大规则分块")
|
||||
private List<RuleDecisionBlockVO> blocks;
|
||||
|
||||
public Map<String, Object> safeGlobalParamsPreview() {
|
||||
if (globalParamsPreview == null) {
|
||||
globalParamsPreview = new LinkedHashMap<>();
|
||||
}
|
||||
return globalParamsPreview;
|
||||
}
|
||||
|
||||
public List<RuleDecisionBlockVO> safeBlocks() {
|
||||
if (blocks == null) {
|
||||
blocks = new ArrayList<>();
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.solution.rule.domain.config.vo;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@ApiModel("单个分块(环形参数 + If/Then 中枢)")
|
||||
public class RuleFourBlockClusterVO implements Serializable {
|
||||
|
||||
@ApiModelProperty("块标识:equipment/target/position/track")
|
||||
private String blockId;
|
||||
|
||||
@ApiModelProperty("模块编码,对应 rule_item.module_code")
|
||||
private String moduleCode;
|
||||
|
||||
@ApiModelProperty("界面标题(如 装备匹配)")
|
||||
private String title;
|
||||
|
||||
@ApiModelProperty("Drools 规则名(如 装备匹配)")
|
||||
private String droolsRuleName;
|
||||
|
||||
@ApiModelProperty("salience")
|
||||
private Integer salience;
|
||||
|
||||
@ApiModelProperty("Drools when 表达式摘要")
|
||||
private String whenExpr;
|
||||
|
||||
@ApiModelProperty("then 动作(含 mergeDefaultParams + Java 调用)")
|
||||
private String thenAction;
|
||||
|
||||
@ApiModelProperty("中枢 + 环形参数节点与边")
|
||||
private RuleGraphVO graph;
|
||||
|
||||
@ApiModelProperty("该块内每条规则的每个参数:When/Then/产出(表格)")
|
||||
private List<RuleFourBlockParamRowVO> paramRows;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.solution.rule.domain.config.vo;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@Data
|
||||
@ApiModel("四块分区内单条参数展示行")
|
||||
public class RuleFourBlockParamRowVO implements Serializable {
|
||||
|
||||
@ApiModelProperty("规则编码")
|
||||
private String ruleCode;
|
||||
|
||||
@ApiModelProperty("规则名称")
|
||||
private String ruleName;
|
||||
|
||||
@ApiModelProperty("参数键")
|
||||
private String paramKey;
|
||||
|
||||
@ApiModelProperty("参数业务名")
|
||||
private String paramName;
|
||||
|
||||
@ApiModelProperty("When(规则条件或块级回退)")
|
||||
private String whenText;
|
||||
|
||||
@ApiModelProperty("Then(规则动作或块级回退)")
|
||||
private String thenText;
|
||||
|
||||
@ApiModelProperty("产出说明(生效值 + 静态提示)")
|
||||
private String outputText;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.solution.rule.domain.config.vo;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
@ApiModel("四块规则知识图谱(装备/目标/阵位/航迹)")
|
||||
public class RuleFourBlocksGraphVO implements Serializable {
|
||||
|
||||
@ApiModelProperty("与运行时 KieSession globalParams 一致的参数快照(启用规则与参数合并后)")
|
||||
private Map<String, Object> globalParamsPreview;
|
||||
|
||||
@ApiModelProperty("四个分块,每块含中枢 If/Then 与子图节点边")
|
||||
private List<RuleFourBlockClusterVO> blocks;
|
||||
|
||||
public Map<String, Object> safeGlobalParamsPreview() {
|
||||
if (globalParamsPreview == null) {
|
||||
globalParamsPreview = new LinkedHashMap<>();
|
||||
}
|
||||
return globalParamsPreview;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.solution.rule.domain.config.vo;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@Data
|
||||
@ApiModel("规则知识图谱边")
|
||||
public class RuleGraphEdgeVO implements Serializable {
|
||||
|
||||
@ApiModelProperty("边 id")
|
||||
private String id;
|
||||
|
||||
@ApiModelProperty("起点节点 id")
|
||||
private String source;
|
||||
|
||||
@ApiModelProperty("终点节点 id")
|
||||
private String target;
|
||||
|
||||
@ApiModelProperty("边类型")
|
||||
private String edgeType;
|
||||
|
||||
@ApiModelProperty("边上展示文案")
|
||||
private String label;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.solution.rule.domain.config.vo;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
@ApiModel("规则知识图谱节点")
|
||||
public class RuleGraphNodeVO implements Serializable {
|
||||
|
||||
@ApiModelProperty("全局唯一节点 id")
|
||||
private String id;
|
||||
|
||||
@ApiModelProperty("展示标题")
|
||||
private String label;
|
||||
|
||||
@ApiModelProperty("节点类型:level/kind/module/rule/param/taskType")
|
||||
private String nodeType;
|
||||
|
||||
@ApiModelProperty("附加属性(如 ruleCode、paramKey、字典编码等)")
|
||||
private Map<String, Object> payload;
|
||||
|
||||
public Map<String, Object> safePayload() {
|
||||
if (payload == null) {
|
||||
payload = new HashMap<>();
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.solution.rule.domain.config.vo;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@ApiModel("规则知识图谱数据")
|
||||
public class RuleGraphVO implements Serializable {
|
||||
|
||||
@ApiModelProperty("节点列表")
|
||||
private List<RuleGraphNodeVO> nodes;
|
||||
|
||||
@ApiModelProperty("边列表")
|
||||
private List<RuleGraphEdgeVO> edges;
|
||||
|
||||
@ApiModelProperty("前端布局提示:如 radial_hub 使用径向圆心布局")
|
||||
private String layoutHint;
|
||||
|
||||
@ApiModelProperty("径向布局时的中心节点 id(通常为 drools_facade)")
|
||||
private String focusNodeId;
|
||||
|
||||
public List<RuleGraphNodeVO> safeNodes() {
|
||||
if (nodes == null) {
|
||||
nodes = new ArrayList<>();
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
public List<RuleGraphEdgeVO> safeEdges() {
|
||||
if (edges == null) {
|
||||
edges = new ArrayList<>();
|
||||
}
|
||||
return edges;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class AssignTargetItem {
|
||||
|
||||
private String task;
|
||||
|
||||
private String type;
|
||||
|
||||
private List<String> target = new ArrayList<>();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class DataOutput {
|
||||
|
||||
@JsonProperty("assign_target")
|
||||
private List<AssignTargetItem> assignTarget = new ArrayList<>();
|
||||
|
||||
private List<TaskItem> task = new ArrayList<>();
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Kj3ExecuteBlock {
|
||||
|
||||
private List<Kj3TargetItem> targetList;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Kj3ForceSide {
|
||||
|
||||
@JsonProperty("ObjectHandle")
|
||||
private String objectHandle;
|
||||
|
||||
@JsonProperty("ForceSideName")
|
||||
private String forceSideName;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Kj3MilitaryItem {
|
||||
|
||||
@JsonProperty("Name")
|
||||
private String name;
|
||||
|
||||
@JsonProperty("OwnerForceSide")
|
||||
private String ownerForceSide;
|
||||
|
||||
@JsonProperty("EquipmentID")
|
||||
private String equipmentId;
|
||||
|
||||
@JsonProperty("Platform_type")
|
||||
private String platformType;
|
||||
|
||||
@JsonProperty("SubComponents")
|
||||
private Kj3SubComponents subComponents;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Kj3MilitaryPlatformComponent {
|
||||
|
||||
@JsonProperty("TrackParamId")
|
||||
private String trackParamId;
|
||||
|
||||
private List<Double> positions;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Kj3MilitaryScenario {
|
||||
|
||||
@JsonProperty("Tasks")
|
||||
private List<Kj3TaskNode> tasks;
|
||||
|
||||
@JsonProperty("ForceSides")
|
||||
private List<Kj3ForceSide> forceSides;
|
||||
|
||||
@JsonProperty("Military")
|
||||
private List<Kj3MilitaryItem> military;
|
||||
|
||||
@JsonProperty("RefAttributeObject")
|
||||
private Kj3RefAttributeObject refAttributeObject;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class Kj3PostResult {
|
||||
|
||||
private boolean success;
|
||||
|
||||
private String statusMessage;
|
||||
|
||||
private String postUrl;
|
||||
|
||||
private int taskCount;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Kj3RefAttributeObject {
|
||||
|
||||
@JsonProperty("TrackParam")
|
||||
private Map<String, Kj3TrackParam> trackParam;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Kj3Root {
|
||||
|
||||
@JsonProperty("MilitaryScenario")
|
||||
private Kj3MilitaryScenario militaryScenario;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Kj3SubComponents {
|
||||
|
||||
private List<Kj3MilitaryPlatformComponent> platform;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Kj3TargetItem {
|
||||
|
||||
private String targetId;
|
||||
|
||||
@JsonProperty("cruiseRouteId")
|
||||
private String cruiseRouteId;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Kj3TaskNode {
|
||||
|
||||
private String name;
|
||||
|
||||
private String side;
|
||||
|
||||
private Kj3TaskPayload task;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Kj3TaskPayload {
|
||||
|
||||
private String name;
|
||||
|
||||
private String side;
|
||||
|
||||
private String type;
|
||||
|
||||
@JsonProperty("at_time")
|
||||
private String atTime;
|
||||
|
||||
private List<Kj3ExecuteBlock> execute;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Kj3TrackParam {
|
||||
|
||||
@JsonProperty("TrackPoints")
|
||||
private List<Kj3TrackPoint> trackPoints;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Kj3TrackPoint {
|
||||
|
||||
private String longitude;
|
||||
|
||||
private String latitude;
|
||||
|
||||
private String height;
|
||||
|
||||
private String speed;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class PlatformItem {
|
||||
|
||||
private String name;
|
||||
|
||||
@JsonProperty("platform_type")
|
||||
private String platformType;
|
||||
|
||||
private String longitude;
|
||||
|
||||
private String latitude;
|
||||
|
||||
private Integer altitude;
|
||||
|
||||
private List<RoutePoint> route = new ArrayList<>();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class RoutePoint {
|
||||
|
||||
private String longitude;
|
||||
|
||||
private String latitude;
|
||||
|
||||
private Integer altitude;
|
||||
|
||||
private Integer speed;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class TaskItem {
|
||||
|
||||
@JsonProperty("task_name")
|
||||
private String taskName;
|
||||
|
||||
private List<PlatformItem> platform = new ArrayList<>();
|
||||
|
||||
private TaskTime time;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.solution.rule.domain.tasks;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class TaskTime {
|
||||
|
||||
private Integer begin;
|
||||
|
||||
private Integer end;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.solution.rule.mapper;
|
||||
import com.solution.rule.domain.config.RuleConfig;
|
||||
import com.solution.rule.domain.config.RuleConfigParam;
|
||||
import com.solution.rule.domain.config.RuleConfigQuery;
|
||||
import com.solution.rule.domain.config.RuleConfigTaskTypeRow;
|
||||
import com.solution.rule.domain.config.RuleDictItem;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
@@ -24,12 +25,16 @@ public interface RuleConfigMapper {
|
||||
|
||||
List<RuleConfigParam> selectParamsByRuleCode(@Param("ruleCode") String ruleCode);
|
||||
|
||||
List<RuleConfigParam> selectParamsByRuleCodes(@Param("ruleCodes") List<String> ruleCodes);
|
||||
|
||||
int deleteParamsByRuleCodes(@Param("ruleCodes") String[] ruleCodes);
|
||||
|
||||
int insertParamsBatch(@Param("params") List<RuleConfigParam> params);
|
||||
|
||||
List<String> selectTaskTypesByRuleCode(@Param("ruleCode") String ruleCode);
|
||||
|
||||
List<RuleConfigTaskTypeRow> selectTaskTypesByRuleCodes(@Param("ruleCodes") List<String> ruleCodes);
|
||||
|
||||
int deleteTaskTypesByRuleCodes(@Param("ruleCodes") String[] ruleCodes);
|
||||
|
||||
int insertTaskTypesBatch(@Param("ruleCode") String ruleCode, @Param("taskTypes") List<String> taskTypes);
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package com.solution.rule.service;
|
||||
|
||||
import com.solution.rule.domain.config.RuleConfig;
|
||||
import com.solution.rule.domain.config.RuleConfigExcelRow;
|
||||
import com.solution.rule.domain.config.RuleConfigQuery;
|
||||
import com.solution.rule.domain.config.RuleDictItem;
|
||||
import com.solution.rule.domain.config.RuleParamMeta;
|
||||
import com.solution.rule.domain.config.vo.RuleDecisionTreeVO;
|
||||
import com.solution.rule.domain.config.vo.RuleFourBlocksGraphVO;
|
||||
import com.solution.rule.domain.config.vo.RuleGraphVO;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -25,4 +29,20 @@ public interface IRuleConfigService {
|
||||
Map<String, Object> loadEnabledGlobalParams();
|
||||
|
||||
List<RuleParamMeta> selectParamMetaList();
|
||||
|
||||
List<RuleConfigExcelRow> exportRuleConfigRows(RuleConfigQuery query);
|
||||
|
||||
String importRuleConfigRows(List<RuleConfigExcelRow> rows, boolean updateSupport);
|
||||
|
||||
/**
|
||||
* 根据当前页规则主数据构建知识图谱(节点与边),参数与任务类型从库批量加载。
|
||||
*/
|
||||
RuleGraphVO buildKnowledgeGraph(List<RuleConfig> ruleConfigs);
|
||||
|
||||
RuleDecisionTreeVO buildDecisionTree(List<RuleConfig> ruleConfigs);
|
||||
|
||||
/**
|
||||
* 四块规则知识图谱(装备/目标/阵位/航迹):中枢 If/Then + 环形参数,参数值与 {@link #loadEnabledGlobalParams()} 一致。
|
||||
*/
|
||||
RuleFourBlocksGraphVO buildFourBlocksKnowledgeGraph();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.solution.rule.service;
|
||||
|
||||
import com.solution.rule.domain.tasks.Kj3PostResult;
|
||||
import com.solution.rule.domain.tasks.Kj3Root;
|
||||
|
||||
public interface Kj3TaskDataService {
|
||||
|
||||
/**
|
||||
* 解析接口入参 JSON,仅提取红方任务,转换为 data 结构后发送 HTTP POST。
|
||||
*
|
||||
* @param kj3Json 传入的 kj-3 JSON 字符串
|
||||
* @return 发送结果
|
||||
*/
|
||||
Kj3PostResult parseAndPostRedTasks(String kj3Json);
|
||||
|
||||
/**
|
||||
* 解析接口入参对象,仅提取红方任务,转换为 data 结构后发送 HTTP POST。
|
||||
*
|
||||
* @param root 传入的 kj-3 对象
|
||||
* @return 发送结果
|
||||
*/
|
||||
Kj3PostResult parseAndPostRedTasks(Kj3Root root);
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
package com.solution.rule.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solution.rule.domain.tasks.AssignTargetItem;
|
||||
import com.solution.rule.domain.tasks.DataOutput;
|
||||
import com.solution.rule.domain.tasks.Kj3ExecuteBlock;
|
||||
import com.solution.rule.domain.tasks.Kj3ForceSide;
|
||||
import com.solution.rule.domain.tasks.Kj3MilitaryItem;
|
||||
import com.solution.rule.domain.tasks.Kj3MilitaryPlatformComponent;
|
||||
import com.solution.rule.domain.tasks.Kj3MilitaryScenario;
|
||||
import com.solution.rule.domain.tasks.Kj3PostResult;
|
||||
import com.solution.rule.domain.tasks.Kj3RefAttributeObject;
|
||||
import com.solution.rule.domain.tasks.Kj3Root;
|
||||
import com.solution.rule.domain.tasks.Kj3TaskNode;
|
||||
import com.solution.rule.domain.tasks.Kj3TaskPayload;
|
||||
import com.solution.rule.domain.tasks.Kj3TrackParam;
|
||||
import com.solution.rule.domain.tasks.Kj3TrackPoint;
|
||||
import com.solution.rule.domain.tasks.Kj3TargetItem;
|
||||
import com.solution.rule.domain.tasks.PlatformItem;
|
||||
import com.solution.rule.domain.tasks.RoutePoint;
|
||||
import com.solution.rule.domain.tasks.TaskItem;
|
||||
import com.solution.rule.domain.tasks.TaskTime;
|
||||
import com.solution.rule.service.Kj3TaskDataService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.UnknownHostException;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class Kj3TaskDataServiceImpl implements Kj3TaskDataService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(Kj3TaskDataServiceImpl.class);
|
||||
|
||||
private static final String DATA_POST_URL = "http://localhost:5000/bhtree/zhitangCompanyData";
|
||||
private static final String URL_PLACEHOLDER = "http://TODO-REPLACE";
|
||||
|
||||
private static final String RED_SIDE = "红方";
|
||||
|
||||
private static final String DEFAULT_ASSIGN_TYPE = "fire";
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public Kj3PostResult parseAndPostRedTasks(String kj3Json) {
|
||||
if (ObjectUtil.isEmpty(kj3Json)) {
|
||||
throw new IllegalArgumentException("kj3Json 不能为空");
|
||||
}
|
||||
Kj3Root root = parseKj3Json(kj3Json);
|
||||
return parseAndPostRedTasks(root);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Kj3PostResult parseAndPostRedTasks(Kj3Root root) {
|
||||
if (ObjectUtil.isEmpty(root)) {
|
||||
throw new IllegalArgumentException("kj3 入参对象不能为空");
|
||||
}
|
||||
DataOutput output = transformToDataOutput(root);
|
||||
String payload = writeJson(output);
|
||||
log.info("kj3 转换后的 data 输出: {}", payload);
|
||||
Kj3PostResult result = new Kj3PostResult();
|
||||
result.setPostUrl(DATA_POST_URL);
|
||||
result.setTaskCount(output.getTask().size());
|
||||
if (!isPostUrlConfigured()) {
|
||||
result.setSuccess(false);
|
||||
result.setStatusMessage("POST URL 未配置,请将 DATA_POST_URL 从占位值替换为真实地址");
|
||||
return result;
|
||||
}
|
||||
try {
|
||||
String response = postJson(payload);
|
||||
result.setSuccess(true);
|
||||
result.setStatusMessage(response);
|
||||
} catch (RuntimeException ex) {
|
||||
result.setSuccess(false);
|
||||
result.setStatusMessage(ex.getMessage());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private boolean isPostUrlConfigured() {
|
||||
return ObjectUtil.isNotEmpty(DATA_POST_URL) && !URL_PLACEHOLDER.equalsIgnoreCase(DATA_POST_URL);
|
||||
}
|
||||
|
||||
private Kj3Root parseKj3Json(String kj3Json) {
|
||||
try {
|
||||
return objectMapper.readValue(kj3Json, Kj3Root.class);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("解析接口入参 kj-3 JSON 失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
private DataOutput transformToDataOutput(Kj3Root root) {
|
||||
DataOutput output = new DataOutput();
|
||||
Kj3MilitaryScenario scenario = root == null ? null : root.getMilitaryScenario();
|
||||
List<Kj3TaskNode> tasks = scenario == null ? Collections.emptyList() : scenario.getTasks();
|
||||
if (CollUtil.isEmpty(tasks)) {
|
||||
return output;
|
||||
}
|
||||
String redForceSideId = getRedForceSideId(scenario);
|
||||
|
||||
List<Kj3TaskNode> redTasks = tasks.stream()
|
||||
.filter(this::isRedTask)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
for (Kj3TaskNode redTask : redTasks) {
|
||||
String taskName = resolveTaskName(redTask);
|
||||
Kj3TaskPayload payload = redTask.getTask();
|
||||
|
||||
TaskItem taskItem = new TaskItem();
|
||||
taskItem.setTaskName(taskName);
|
||||
taskItem.setTime(buildTaskTime(payload));
|
||||
taskItem.setPlatform(buildPlatformsForTask(scenario, redForceSideId, payload));
|
||||
output.getTask().add(taskItem);
|
||||
|
||||
AssignTargetItem assignTargetItem = new AssignTargetItem();
|
||||
assignTargetItem.setTask(taskName);
|
||||
assignTargetItem.setType(resolveTaskType(payload));
|
||||
assignTargetItem.setTarget(extractTargets(payload));
|
||||
output.getAssignTarget().add(assignTargetItem);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
private boolean isRedTask(Kj3TaskNode taskNode) {
|
||||
if (taskNode == null) {
|
||||
return false;
|
||||
}
|
||||
if (RED_SIDE.equals(taskNode.getSide())) {
|
||||
return true;
|
||||
}
|
||||
Kj3TaskPayload payload = taskNode.getTask();
|
||||
return payload != null && RED_SIDE.equals(payload.getSide());
|
||||
}
|
||||
|
||||
private String resolveTaskName(Kj3TaskNode taskNode) {
|
||||
Kj3TaskPayload payload = taskNode.getTask();
|
||||
if (payload != null && ObjectUtil.isNotEmpty(payload.getName())) {
|
||||
return payload.getName();
|
||||
}
|
||||
return taskNode.getName();
|
||||
}
|
||||
|
||||
private String resolveTaskType(Kj3TaskPayload payload) {
|
||||
if (payload != null && ObjectUtil.isNotEmpty(payload.getType())) {
|
||||
return payload.getType();
|
||||
}
|
||||
return DEFAULT_ASSIGN_TYPE;
|
||||
}
|
||||
|
||||
private String getRedForceSideId(Kj3MilitaryScenario scenario) {
|
||||
if (scenario == null || CollUtil.isEmpty(scenario.getForceSides())) {
|
||||
return "";
|
||||
}
|
||||
for (Kj3ForceSide forceSide : scenario.getForceSides()) {
|
||||
if (forceSide != null && RED_SIDE.equals(forceSide.getForceSideName())) {
|
||||
return forceSide.getObjectHandle();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private List<PlatformItem> buildRedPlatforms(Kj3MilitaryScenario scenario, String redForceSideId) {
|
||||
if (scenario == null || CollUtil.isEmpty(scenario.getMilitary()) || ObjectUtil.isEmpty(redForceSideId)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
Map<String, Kj3TrackParam> trackParamMap = getTrackParamMap(scenario);
|
||||
List<PlatformItem> platforms = new ArrayList<>();
|
||||
for (Kj3MilitaryItem militaryItem : scenario.getMilitary()) {
|
||||
if (militaryItem == null || !redForceSideId.equals(militaryItem.getOwnerForceSide())) {
|
||||
continue;
|
||||
}
|
||||
PlatformItem platformItem = mapMilitaryToPlatform(militaryItem, trackParamMap);
|
||||
platforms.add(platformItem);
|
||||
}
|
||||
return platforms;
|
||||
}
|
||||
|
||||
private List<PlatformItem> buildPlatformsForTask(Kj3MilitaryScenario scenario, String redForceSideId, Kj3TaskPayload payload) {
|
||||
List<PlatformItem> redPlatforms = buildRedPlatforms(scenario, redForceSideId);
|
||||
if (CollUtil.isEmpty(redPlatforms)) {
|
||||
return redPlatforms;
|
||||
}
|
||||
Map<String, Kj3TrackParam> trackParamMap = getTrackParamMap(scenario);
|
||||
String fallbackRouteId = resolveFallbackRouteId(payload);
|
||||
if (ObjectUtil.isEmpty(fallbackRouteId)) {
|
||||
return redPlatforms;
|
||||
}
|
||||
for (PlatformItem platform : redPlatforms) {
|
||||
if (CollUtil.isNotEmpty(platform.getRoute())) {
|
||||
continue;
|
||||
}
|
||||
platform.setRoute(buildRoute(fallbackRouteId, trackParamMap));
|
||||
}
|
||||
return redPlatforms;
|
||||
}
|
||||
|
||||
private Map<String, Kj3TrackParam> getTrackParamMap(Kj3MilitaryScenario scenario) {
|
||||
Kj3RefAttributeObject refAttributeObject = scenario.getRefAttributeObject();
|
||||
if (refAttributeObject == null || refAttributeObject.getTrackParam() == null) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return refAttributeObject.getTrackParam();
|
||||
}
|
||||
|
||||
private PlatformItem mapMilitaryToPlatform(Kj3MilitaryItem militaryItem, Map<String, Kj3TrackParam> trackParamMap) {
|
||||
PlatformItem platformItem = new PlatformItem();
|
||||
platformItem.setName(militaryItem.getName());
|
||||
platformItem.setPlatformType(militaryItem.getPlatformType());
|
||||
|
||||
Kj3MilitaryPlatformComponent positionSourceComponent = resolvePositionSourceComponent(militaryItem);
|
||||
fillPosition(platformItem, positionSourceComponent);
|
||||
String trackParamId = resolveTrackParamId(militaryItem);
|
||||
platformItem.setRoute(buildRoute(trackParamId, trackParamMap));
|
||||
return platformItem;
|
||||
}
|
||||
|
||||
private String resolveFallbackRouteId(Kj3TaskPayload payload) {
|
||||
if (payload == null || CollUtil.isEmpty(payload.getExecute())) {
|
||||
return "";
|
||||
}
|
||||
for (Kj3ExecuteBlock executeBlock : payload.getExecute()) {
|
||||
if (executeBlock == null || CollUtil.isEmpty(executeBlock.getTargetList())) {
|
||||
continue;
|
||||
}
|
||||
for (Kj3TargetItem targetItem : executeBlock.getTargetList()) {
|
||||
if (targetItem != null && ObjectUtil.isNotEmpty(targetItem.getCruiseRouteId())) {
|
||||
return targetItem.getCruiseRouteId();
|
||||
}
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private Kj3MilitaryPlatformComponent resolvePositionSourceComponent(Kj3MilitaryItem militaryItem) {
|
||||
if (militaryItem.getSubComponents() == null || CollUtil.isEmpty(militaryItem.getSubComponents().getPlatform())) {
|
||||
return null;
|
||||
}
|
||||
for (Kj3MilitaryPlatformComponent component : militaryItem.getSubComponents().getPlatform()) {
|
||||
if (component != null && CollUtil.isNotEmpty(component.getPositions())) {
|
||||
return component;
|
||||
}
|
||||
}
|
||||
return militaryItem.getSubComponents().getPlatform().get(0);
|
||||
}
|
||||
|
||||
private String resolveTrackParamId(Kj3MilitaryItem militaryItem) {
|
||||
if (militaryItem.getSubComponents() == null || CollUtil.isEmpty(militaryItem.getSubComponents().getPlatform())) {
|
||||
return "";
|
||||
}
|
||||
for (Kj3MilitaryPlatformComponent component : militaryItem.getSubComponents().getPlatform()) {
|
||||
if (component != null && ObjectUtil.isNotEmpty(component.getTrackParamId())) {
|
||||
return component.getTrackParamId();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private void fillPosition(PlatformItem platformItem, Kj3MilitaryPlatformComponent component) {
|
||||
if (component == null || CollUtil.isEmpty(component.getPositions())) {
|
||||
return;
|
||||
}
|
||||
List<Double> positions = component.getPositions();
|
||||
if (positions.size() > 0 && positions.get(0) != null) {
|
||||
platformItem.setLongitude(String.valueOf(positions.get(0)));
|
||||
}
|
||||
if (positions.size() > 1 && positions.get(1) != null) {
|
||||
platformItem.setLatitude(String.valueOf(positions.get(1)));
|
||||
}
|
||||
if (positions.size() > 2 && positions.get(2) != null) {
|
||||
platformItem.setAltitude((int) Math.round(positions.get(2)));
|
||||
}
|
||||
}
|
||||
|
||||
private List<RoutePoint> buildRoute(String trackParamId, Map<String, Kj3TrackParam> trackParamMap) {
|
||||
if (ObjectUtil.isEmpty(trackParamId)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
Kj3TrackParam trackParam = trackParamMap.get(trackParamId);
|
||||
if (trackParam == null || CollUtil.isEmpty(trackParam.getTrackPoints())) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
List<RoutePoint> routes = new ArrayList<>();
|
||||
for (Kj3TrackPoint trackPoint : trackParam.getTrackPoints()) {
|
||||
if (trackPoint == null) {
|
||||
continue;
|
||||
}
|
||||
RoutePoint routePoint = new RoutePoint();
|
||||
routePoint.setLongitude(trackPoint.getLongitude());
|
||||
routePoint.setLatitude(trackPoint.getLatitude());
|
||||
routePoint.setAltitude(parseInteger(trackPoint.getHeight()));
|
||||
routePoint.setSpeed(parseInteger(trackPoint.getSpeed()));
|
||||
routes.add(routePoint);
|
||||
}
|
||||
return routes;
|
||||
}
|
||||
|
||||
private TaskTime buildTaskTime(Kj3TaskPayload payload) {
|
||||
int begin = parseAtTime(payload);
|
||||
TaskTime taskTime = new TaskTime();
|
||||
taskTime.setBegin(begin);
|
||||
taskTime.setEnd(begin);
|
||||
return taskTime;
|
||||
}
|
||||
|
||||
private int parseAtTime(Kj3TaskPayload payload) {
|
||||
if (payload == null || ObjectUtil.isEmpty(payload.getAtTime())) {
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(payload.getAtTime().trim());
|
||||
} catch (NumberFormatException ex) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private Integer parseInteger(String value) {
|
||||
if (ObjectUtil.isEmpty(value)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return (int) Math.round(Double.parseDouble(value.trim()));
|
||||
} catch (NumberFormatException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> extractTargets(Kj3TaskPayload payload) {
|
||||
if (payload == null || CollUtil.isEmpty(payload.getExecute())) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
Set<String> uniqueTargets = new LinkedHashSet<>();
|
||||
for (Kj3ExecuteBlock executeBlock : payload.getExecute()) {
|
||||
if (executeBlock == null || CollUtil.isEmpty(executeBlock.getTargetList())) {
|
||||
continue;
|
||||
}
|
||||
for (Kj3TargetItem targetItem : executeBlock.getTargetList()) {
|
||||
if (targetItem == null || ObjectUtil.isEmpty(targetItem.getTargetId())) {
|
||||
continue;
|
||||
}
|
||||
uniqueTargets.add(targetItem.getTargetId());
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(uniqueTargets);
|
||||
}
|
||||
|
||||
private String writeJson(DataOutput output) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(output);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("序列化 data 输出失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String postJson(String payload) {
|
||||
HttpURLConnection connection = null;
|
||||
try {
|
||||
URL url = new URL(DATA_POST_URL);
|
||||
connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
|
||||
connection.setConnectTimeout(10000);
|
||||
connection.setReadTimeout(10000);
|
||||
connection.setDoOutput(true);
|
||||
|
||||
try (OutputStream outputStream = connection.getOutputStream()) {
|
||||
outputStream.write(payload.getBytes(StandardCharsets.UTF_8));
|
||||
outputStream.flush();
|
||||
}
|
||||
|
||||
int status = connection.getResponseCode();
|
||||
try (InputStream responseStream = status >= 400 ? connection.getErrorStream() : connection.getInputStream()) {
|
||||
String responseBody = readResponse(responseStream);
|
||||
return "HTTP " + status + " " + responseBody;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
if (e instanceof UnknownHostException) {
|
||||
throw new RuntimeException("POST data 输出失败: 无法解析主机,请检查 DATA_POST_URL=" + DATA_POST_URL, e);
|
||||
}
|
||||
throw new RuntimeException("POST data 输出失败: " + e.getMessage(), e);
|
||||
} finally {
|
||||
if (connection != null) {
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String readResponse(InputStream inputStream) throws IOException {
|
||||
if (inputStream == null) {
|
||||
return "";
|
||||
}
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
|
||||
StringBuilder response = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
response.append(line);
|
||||
}
|
||||
return response.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -88,6 +88,7 @@
|
||||
<resultMap id="VPBasicPlatformMap" type="com.solution.rule.domain.BasicPlatform">
|
||||
<result property="id" column="id"/>
|
||||
<result property="name" column="name"/>
|
||||
<result property="behaviortreeId" column="behaviortree_id"/>
|
||||
<result property="description" column="description"/>
|
||||
</resultMap>
|
||||
<select id="findAllBasicPlatformComponents" resultMap="VPBasicPlatformMap">
|
||||
|
||||
@@ -41,6 +41,11 @@
|
||||
<result property="remark" column="remark"/>
|
||||
</resultMap>
|
||||
|
||||
<resultMap id="RuleConfigTaskTypeRowMap" type="com.solution.rule.domain.config.RuleConfigTaskTypeRow">
|
||||
<result property="ruleCode" column="rule_code"/>
|
||||
<result property="taskTypeCode" column="task_type_code"/>
|
||||
</resultMap>
|
||||
|
||||
<select id="selectRuleConfigList" resultMap="RuleConfigMap">
|
||||
SELECT id, rule_code, rule_name, level_code, kind_code, module_code, priority_no,
|
||||
condition_expr, action_expr, version_no, enabled, remark, created_at, updated_at
|
||||
@@ -123,6 +128,23 @@
|
||||
ORDER BY sort_no ASC, id ASC
|
||||
</select>
|
||||
|
||||
<select id="selectParamsByRuleCodes" resultMap="RuleConfigParamMap">
|
||||
SELECT rule_code, param_key, param_val, val_type, param_name, sort_no, enabled, remark
|
||||
FROM rule_item_param
|
||||
<where>
|
||||
<if test="ruleCodes != null and ruleCodes.size() > 0">
|
||||
rule_code IN
|
||||
<foreach collection="ruleCodes" item="c" open="(" separator="," close=")">
|
||||
#{c}
|
||||
</foreach>
|
||||
</if>
|
||||
<if test="ruleCodes == null or ruleCodes.size() == 0">
|
||||
1 = 0
|
||||
</if>
|
||||
</where>
|
||||
ORDER BY rule_code ASC, sort_no ASC, id ASC
|
||||
</select>
|
||||
|
||||
<delete id="deleteParamsByRuleCodes">
|
||||
DELETE FROM rule_item_param
|
||||
WHERE rule_code IN
|
||||
@@ -148,6 +170,23 @@
|
||||
ORDER BY id ASC
|
||||
</select>
|
||||
|
||||
<select id="selectTaskTypesByRuleCodes" resultMap="RuleConfigTaskTypeRowMap">
|
||||
SELECT rule_code, task_type_code
|
||||
FROM rule_item_task_type
|
||||
<where>
|
||||
<if test="ruleCodes != null and ruleCodes.size() > 0">
|
||||
rule_code IN
|
||||
<foreach collection="ruleCodes" item="c" open="(" separator="," close=")">
|
||||
#{c}
|
||||
</foreach>
|
||||
</if>
|
||||
<if test="ruleCodes == null or ruleCodes.size() == 0">
|
||||
1 = 0
|
||||
</if>
|
||||
</where>
|
||||
ORDER BY rule_code ASC, id ASC
|
||||
</select>
|
||||
|
||||
<delete id="deleteTaskTypesByRuleCodes">
|
||||
DELETE FROM rule_item_task_type
|
||||
WHERE rule_code IN
|
||||
|
||||
204
auto-solution-rule/src/main/resources/task/data.json
Normal file
204
auto-solution-rule/src/main/resources/task/data.json
Normal file
@@ -0,0 +1,204 @@
|
||||
{
|
||||
"assign_target": [
|
||||
{
|
||||
"task": "task1",
|
||||
"type": "fire",
|
||||
"target": [
|
||||
"enemy_p1",
|
||||
"enemyp2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"task": "task2",
|
||||
"type": "fire",
|
||||
"target": [
|
||||
"enemy_p1333",
|
||||
"enemyp2333"
|
||||
]
|
||||
},
|
||||
{
|
||||
"task": "task3",
|
||||
"type": "radar",
|
||||
"target": [
|
||||
"enemy_p1444",
|
||||
"enemyp2444"
|
||||
]
|
||||
}
|
||||
],
|
||||
"task": [
|
||||
{
|
||||
"task_name": "task1",
|
||||
"platform": [
|
||||
{
|
||||
"name": "platform1",
|
||||
"platform_type": "WSF_PLATFORM",
|
||||
"longitude": "120:49:24.79e",
|
||||
"latitude": "23:47:26.60n",
|
||||
"altitude": 0,
|
||||
"route": [
|
||||
{
|
||||
"longitude": "120:49:24.79e",
|
||||
"latitude": "23:47:26.60n",
|
||||
"altitude": 0,
|
||||
"speed": 100
|
||||
},
|
||||
{
|
||||
"longitude": "120:49:42.46e",
|
||||
"latitude": "23:47:42.80n",
|
||||
"altitude": 0,
|
||||
"speed": 100
|
||||
},
|
||||
{
|
||||
"longitude": "120:50:19.01e",
|
||||
"latitude": "23:47:51.84n",
|
||||
"altitude": 0,
|
||||
"speed": 100
|
||||
},
|
||||
{
|
||||
"longitude": "120:50:42.73e",
|
||||
"latitude": "23:48:09.86n",
|
||||
"altitude": 0,
|
||||
"speed": 100
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "platform2",
|
||||
"platform_type": "WSF_PLATFORM",
|
||||
"longitude": "120:50:19.01e",
|
||||
"latitude": "23:47:51.84n",
|
||||
"altitude": 0,
|
||||
"route": [
|
||||
{
|
||||
"longitude": "120:50:19.01e",
|
||||
"latitude": "23:47:51.84n",
|
||||
"altitude": 0,
|
||||
"speed": 100
|
||||
},
|
||||
{
|
||||
"longitude": "120:50:42.73e",
|
||||
"latitude": "23:48:09.86n",
|
||||
"altitude": 0,
|
||||
"speed": 100
|
||||
},
|
||||
{
|
||||
"longitude": "120:50:42.73e",
|
||||
"latitude": "23:48:09.86n",
|
||||
"altitude": 0,
|
||||
"speed": 100
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"time": {
|
||||
"begin": 50,
|
||||
"end": 300
|
||||
}
|
||||
},
|
||||
{
|
||||
"task_name": "task2",
|
||||
"platform": [
|
||||
{
|
||||
"name": "platform3",
|
||||
"platform_type": "SENSOR_TYPE",
|
||||
"longitude": "120:50:19.01e",
|
||||
"latitude": "23:47:51.84n",
|
||||
"altitude": 0,
|
||||
"route": [
|
||||
{
|
||||
"longitude": "120:50:19.01e",
|
||||
"latitude": "23:47:51.84n",
|
||||
"altitude": 0,
|
||||
"speed": 100
|
||||
},
|
||||
{
|
||||
"longitude": "120:50:42.73e",
|
||||
"latitude": "23:48:09.86n",
|
||||
"altitude": 0,
|
||||
"speed": 100
|
||||
},
|
||||
{
|
||||
"longitude": "120:50:42.73e",
|
||||
"latitude": "23:48:09.86n",
|
||||
"altitude": 0,
|
||||
"speed": 100
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "platform5",
|
||||
"platform_type": "SENSOR_TYPE",
|
||||
"longitude": "120:50:42.73e",
|
||||
"latitude": "23:48:09.86n",
|
||||
"altitude": 0,
|
||||
"route": [
|
||||
{
|
||||
"longitude": "120:50:42.73e",
|
||||
"latitude": "23:48:09.86n",
|
||||
"altitude": 0,
|
||||
"speed": 100
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "platform4",
|
||||
"platform_type": "JAM_TYPE",
|
||||
"longitude": "120:49:55.28e",
|
||||
"latitude": "23:48:38.68n",
|
||||
"altitude": 0,
|
||||
"route": [
|
||||
{
|
||||
"longitude": "120:49:55.28e",
|
||||
"latitude": "23:48:38.68n",
|
||||
"altitude": 0,
|
||||
"speed": 100
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "platform9",
|
||||
"platform_type": "JAM_TYPE",
|
||||
"longitude": "120:49:55.28e",
|
||||
"latitude": "23:48:38.68n",
|
||||
"altitude": 0,
|
||||
"route": [
|
||||
{
|
||||
"longitude": "120:49:55.28e",
|
||||
"latitude": "23:48:38.68n",
|
||||
"altitude": 0,
|
||||
"speed": 100
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"time": {
|
||||
"begin": 110,
|
||||
"end": 300
|
||||
}
|
||||
},
|
||||
{
|
||||
"task_name": "task3",
|
||||
"platform": [
|
||||
{
|
||||
"name": "platform6",
|
||||
"platform_type": "WSF_PLATFORM",
|
||||
"longitude": "120:49:45.11e",
|
||||
"latitude": "23:48:53.09n",
|
||||
"altitude": 0,
|
||||
"route": [
|
||||
{
|
||||
"longitude": "120:49:45.11e",
|
||||
"latitude": "23:48:53.09n",
|
||||
"altitude": 0,
|
||||
"speed": 100
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"time": {
|
||||
"begin": 50,
|
||||
"end": 300
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
6485
auto-solution-rule/src/main/resources/task/kj-3.json
Normal file
6485
auto-solution-rule/src/main/resources/task/kj-3.json
Normal file
File diff suppressed because it is too large
Load Diff
880
modeler/package-lock.json
generated
880
modeler/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -9,6 +9,8 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@antv/g6": "^5.0.49",
|
||||
"@ant-design/icons-vue": "^7.0.1",
|
||||
"@antv/x6": "^3.1.2",
|
||||
"@antv/x6-vue-shape": "^3.0.2",
|
||||
"ant-design-vue": "^4.2.6",
|
||||
|
||||
@@ -853,6 +853,7 @@
|
||||
.ks-model-builder-content,
|
||||
.ks-model-builder-right {
|
||||
height: calc(100vh - 90px);
|
||||
overflow: auto;
|
||||
|
||||
.ant-card-body {
|
||||
padding: 6px;
|
||||
@@ -987,6 +988,7 @@
|
||||
|
||||
.ant-collapse-content-box {
|
||||
max-height: 37vh;
|
||||
height: fit-content;
|
||||
overflow: auto;
|
||||
}
|
||||
}
|
||||
@@ -1555,6 +1557,44 @@
|
||||
border: 1px solid #0f4a7c;
|
||||
color: #eee;
|
||||
}
|
||||
|
||||
// 修复 mini 模式分页滚动条问题
|
||||
&.ant-pagination-mini {
|
||||
height: 24px;
|
||||
line-height: 24px;
|
||||
|
||||
.ant-pagination-simple-pager {
|
||||
height: 24px;
|
||||
line-height: 24px;
|
||||
|
||||
input {
|
||||
height: 22px;
|
||||
line-height: 20px;
|
||||
padding: 0 4px;
|
||||
margin: 0 2px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-pagination-total-text {
|
||||
height: 24px;
|
||||
line-height: 24px;
|
||||
}
|
||||
|
||||
.ant-pagination-prev,
|
||||
.ant-pagination-next,
|
||||
.ant-pagination-jump-prev,
|
||||
.ant-pagination-jump-next {
|
||||
height: 24px;
|
||||
line-height: 22px;
|
||||
|
||||
.ant-pagination-item-link {
|
||||
height: 22px;
|
||||
line-height: 20px;
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1750,6 +1790,23 @@
|
||||
border: 1px solid #475f71;
|
||||
border-radius: 2px;
|
||||
|
||||
.ks-sidebar-list-param-head {
|
||||
margin-bottom: 12px;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 1px solid rgba(71, 95, 113, 0.65);
|
||||
}
|
||||
|
||||
.ks-sidebar-list-param-head-cell {
|
||||
font-size: 12px;
|
||||
color: #8fc7de;
|
||||
line-height: 22px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ks-sidebar-list-param-head-cell--actions {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.ks-sidebar-list-param-item {
|
||||
margin-bottom: 15px;
|
||||
|
||||
@@ -1877,3 +1934,231 @@
|
||||
padding-left: 5px;
|
||||
}
|
||||
}
|
||||
|
||||
/* rule-config 页:侧栏与主内容区视觉统一(仅带 .rule-config-sidebar 时生效) */
|
||||
.rule-config-sidebar.ks-layout-sidebar {
|
||||
background-color: #020a14;
|
||||
background-image:
|
||||
linear-gradient(180deg, rgba(2, 10, 20, 0.94) 0%, rgba(2, 12, 24, 0.9) 50%, rgba(1, 8, 18, 0.92) 100%),
|
||||
url('@/assets/icons/bg-fk.png');
|
||||
background-size: 100% 100%, 100% 100%;
|
||||
background-position: center, center;
|
||||
border-inline-end: 1px solid rgba(55, 126, 173, 0.35);
|
||||
|
||||
.ks-sidebar-header {
|
||||
background: url('@/assets/icons/bg-fk-title.png') center / 100% 100%;
|
||||
min-height: 104px;
|
||||
padding: 8px 10px 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: flex-start;
|
||||
gap: 10px;
|
||||
line-height: normal;
|
||||
}
|
||||
|
||||
.ant-tree {
|
||||
background: transparent;
|
||||
color: #eee;
|
||||
|
||||
.ant-tree-node-content-wrapper {
|
||||
color: #eee;
|
||||
|
||||
&:hover {
|
||||
background: rgba(9, 38, 75, 0.55);
|
||||
}
|
||||
}
|
||||
|
||||
.ant-tree-node-content-wrapper.ant-tree-node-selected {
|
||||
background: rgba(17, 55, 126, 0.65);
|
||||
}
|
||||
|
||||
.ant-tree-switcher {
|
||||
color: #a2b1ba;
|
||||
}
|
||||
|
||||
.ant-tree-title {
|
||||
color: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-pagination {
|
||||
color: #a2b1ba;
|
||||
|
||||
.ant-pagination-item-link,
|
||||
.ant-pagination-item a {
|
||||
color: #a2b1ba;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.rule-config-main-split {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: stretch;
|
||||
overflow: hidden;
|
||||
padding-right: 0;
|
||||
background:
|
||||
linear-gradient(180deg, rgba(1, 12, 28, 0.94) 0%, rgba(2, 16, 36, 0.92) 100%),
|
||||
url('@/assets/icons/page-card-body.png') center / 100% 100%;
|
||||
}
|
||||
|
||||
.rule-config-graph-placeholder {
|
||||
flex-shrink: 0;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1px dashed rgba(55, 126, 173, 0.45);
|
||||
margin: 8px 0 8px 8px;
|
||||
border-radius: 2px;
|
||||
color: #a2b1ba;
|
||||
background: rgba(8, 29, 54, 0.25);
|
||||
}
|
||||
|
||||
.rule-config-graph-placeholder--chart {
|
||||
align-items: stretch;
|
||||
justify-content: stretch;
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.rule-config-main-split-resizer {
|
||||
flex: 0 0 6px;
|
||||
width: 6px;
|
||||
margin: 8px 0;
|
||||
cursor: col-resize;
|
||||
flex-shrink: 0;
|
||||
border-radius: 2px;
|
||||
background: rgba(55, 126, 173, 0.25);
|
||||
|
||||
&:hover {
|
||||
background: rgba(55, 126, 173, 0.5);
|
||||
}
|
||||
}
|
||||
|
||||
.rule-config-sidebar .ks-sidebar-actions {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid rgba(71, 95, 113, 0.78);
|
||||
border-radius: 2px;
|
||||
background: linear-gradient(180deg, rgba(8, 29, 54, 0.88) 0%, rgba(6, 21, 40, 0.92) 100%);
|
||||
box-shadow: inset 0 0 0 1px rgba(18, 70, 120, 0.18);
|
||||
}
|
||||
|
||||
.rule-config-sidebar .ks-sidebar-add {
|
||||
position: static;
|
||||
right: auto;
|
||||
top: auto;
|
||||
font-size: 12px;
|
||||
|
||||
.anticon {
|
||||
display: block;
|
||||
float: left;
|
||||
line-height: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.rule-config-sidebar-action.ant-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-width: 62px;
|
||||
padding-inline: 10px;
|
||||
border-color: #1c468b;
|
||||
background: linear-gradient(0deg, #14223b 0, #1c468b 100%);
|
||||
color: #eee;
|
||||
|
||||
.anticon {
|
||||
margin: 0;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
&:not(:disabled):hover,
|
||||
&:hover,
|
||||
&:active {
|
||||
border-color: #166094;
|
||||
background: linear-gradient(90deg, #3687bc 0%, #074375 100%);
|
||||
color: #fff;
|
||||
}
|
||||
}
|
||||
|
||||
.rule-config-right-cluster {
|
||||
display: flex;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
align-items: stretch;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.rule-config-graph-placeholder__text {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.rule-config-panel-toggle {
|
||||
flex: 0 0 20px;
|
||||
width: 20px;
|
||||
margin: 8px 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 2px 0 0 2px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #eee;
|
||||
background: rgba(9, 38, 75, 0.75);
|
||||
|
||||
&:hover {
|
||||
background: rgba(17, 55, 126, 0.85);
|
||||
}
|
||||
}
|
||||
|
||||
.rule-config-right-panel {
|
||||
position: relative;
|
||||
flex: 0 0 min(480px, 42vw);
|
||||
width: min(480px, 42vw);
|
||||
min-width: 320px;
|
||||
max-width: 55%;
|
||||
transition: flex-basis 0.2s ease, width 0.2s ease, opacity 0.2s ease, min-width 0.2s ease;
|
||||
overflow: hidden;
|
||||
border-left: 1px solid rgba(71, 95, 113, 0.6);
|
||||
background:
|
||||
linear-gradient(180deg, rgba(4, 24, 50, 0.96) 0%, rgba(3, 17, 37, 0.94) 100%);
|
||||
box-shadow: inset 0 0 0 1px rgba(18, 70, 120, 0.18);
|
||||
}
|
||||
|
||||
.rule-config-right-panel--collapsed {
|
||||
flex: 0 0 0;
|
||||
width: 0;
|
||||
min-width: 0;
|
||||
max-width: 0;
|
||||
opacity: 0;
|
||||
border-left: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.rule-config-right-panel-edge {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 8px;
|
||||
bottom: 8px;
|
||||
width: 8px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
cursor: col-resize;
|
||||
background: linear-gradient(180deg, rgba(55, 126, 173, 0.15) 0%, rgba(55, 126, 173, 0.5) 50%, rgba(55, 126, 173, 0.15) 100%);
|
||||
z-index: 2;
|
||||
|
||||
&:hover {
|
||||
background: linear-gradient(180deg, rgba(55, 126, 173, 0.3) 0%, rgba(55, 126, 173, 0.72) 50%, rgba(55, 126, 173, 0.3) 100%);
|
||||
}
|
||||
}
|
||||
|
||||
.rule-config-right-panel__inner {
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
padding: 10px 10px 10px 12px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
@@ -51,7 +51,11 @@ export const getAllBehaviorTreesBySceneId = (sceneId: number): Promise<{ code: n
|
||||
return req.get<{ code: number; msg: string; data: BehaviorTree[] }>(`/system/scene/getAllTree/${sceneId}`);
|
||||
};
|
||||
|
||||
// 更新行为树(挂载到平台)
|
||||
// 更新平台的行为树id
|
||||
export const updateBehaviorTreeIdOfPlatform = (query: { id: number, behaviortreeId: number}): Promise<BasicResponse> => {
|
||||
return req.putJson<BasicResponse>(`/system/behaviortree/behaviortreeId`, query);
|
||||
};
|
||||
// 更新行为树的平台id
|
||||
export const updateBehaviorTree = (behaviorTree: BehaviorTree): Promise<BasicResponse> => {
|
||||
return req.putJson<BasicResponse>(`/system/behaviortree`, behaviorTree);
|
||||
};
|
||||
@@ -76,6 +76,8 @@ import { findOneScenarioById, saveScenario, findRelations, getAllBehaviorTreesBy
|
||||
import { resolveConnectionRelation } from './relation';
|
||||
import { generateRandomCommunicationData } from '../graph/random-data-generator';
|
||||
import { convertRecordsToGraphContainer, type CommunicationRecord } from '../graph/data-converter';
|
||||
import { log } from 'echarts/types/src/util/log.js';
|
||||
import { router } from '@/router';
|
||||
|
||||
const TeleportContainer = defineComponent(getTeleport());
|
||||
|
||||
@@ -104,7 +106,6 @@ export default defineComponent({
|
||||
const isDraggingOver = ref(false);
|
||||
const currentScenarioEditing = ref<boolean>(false);
|
||||
const currentScenario = ref<Scenario | null>(null);
|
||||
const currentGraph = ref<GraphContainer | null>(null);
|
||||
const selectedModelNode = ref<Node<NodeProperties> | null>(null);
|
||||
const selectedNodeTaskElement = ref<GraphTaskElement | null>(null);
|
||||
const changed = ref<boolean>(false);
|
||||
@@ -403,10 +404,6 @@ export default defineComponent({
|
||||
(graph.value as any).currentScenario = null;
|
||||
}
|
||||
|
||||
currentGraph.value = {
|
||||
edges: [],
|
||||
nodes: [],
|
||||
};
|
||||
selectedModelNode.value = null;
|
||||
selectedNodeTaskElement.value = null;
|
||||
|
||||
@@ -439,13 +436,19 @@ export default defineComponent({
|
||||
handleGraphEvent('node:dblclick', (args: any) => {
|
||||
const node = args.node as Node<NodeProperties>;
|
||||
const element = node.getData() as GraphTaskElement;
|
||||
console.error('element',element)
|
||||
window.location.href = `/app/decision/designer?scenario=${currentScenario.value?.id}&platform=${element?.platformId?? ''}`
|
||||
|
||||
window.location.href = `/app/decision/designer?scenarioId=${currentScenario.value?.id}&behaviortreeId=${element?.behaviortreeId ?? ''}`
|
||||
|
||||
// destroy()
|
||||
// window.location.href = '/app/decision/designer'
|
||||
|
||||
// 通过router跳转在初始化节点上存在渲染时机的问题,导致节点未渲染
|
||||
// router.push({
|
||||
// path: '/app/decision/designer'
|
||||
// path: '/app/decision/designer',
|
||||
// query: {
|
||||
// scenarioId: currentScenario.value?.id?.toString() ?? '',
|
||||
// behaviortreeId: element?.behaviortreeId?.toString() ?? '',
|
||||
// },
|
||||
// })
|
||||
});
|
||||
|
||||
@@ -743,7 +746,6 @@ export default defineComponent({
|
||||
handleCreate,
|
||||
currentScenarioEditing,
|
||||
currentScenario,
|
||||
currentGraph,
|
||||
selectedNodeTaskElement,
|
||||
selectedModelNode,
|
||||
graph,
|
||||
|
||||
@@ -1,94 +1,96 @@
|
||||
<template>
|
||||
<a-dropdown
|
||||
:trigger="['contextmenu']"
|
||||
:getPopupContainer="getPopupContainer"
|
||||
@openChange="handleVisibleChange"
|
||||
>
|
||||
<a-card
|
||||
:class="[
|
||||
'ks-scenario-node',
|
||||
`ks-scenario-${element?.category ?? 'model'}-node`
|
||||
]"
|
||||
hoverable
|
||||
<div>
|
||||
<a-dropdown
|
||||
:trigger="['contextmenu']"
|
||||
:getPopupContainer="getPopupContainer"
|
||||
@openChange="handleVisibleChange"
|
||||
>
|
||||
<template #title>
|
||||
<a-space>
|
||||
<span class="ks-scenario-node-title">{{ element?.description ?? element?.name ?? '-' }}</span>
|
||||
</a-space>
|
||||
</template>
|
||||
|
||||
<!-- 节点内容区域 -->
|
||||
<div class="w-full">
|
||||
<div class="ks-scenario-node-content">
|
||||
<div
|
||||
v-for="(item, index) in element?.components || []"
|
||||
:key="item.id || index"
|
||||
class="ks-scenario-node-row"
|
||||
>
|
||||
<a-card
|
||||
:class="[
|
||||
'ks-scenario-node',
|
||||
`ks-scenario-${element?.category ?? 'model'}-node`
|
||||
]"
|
||||
hoverable
|
||||
>
|
||||
<template #title>
|
||||
<a-space>
|
||||
<span class="ks-scenario-node-title">{{ element?.description ?? element?.name ?? '-' }}</span>
|
||||
</a-space>
|
||||
</template>
|
||||
|
||||
<!-- 节点内容区域 -->
|
||||
<div class="w-full">
|
||||
<div class="ks-scenario-node-content">
|
||||
<div
|
||||
:data-port="`in-${item.id || index}`"
|
||||
:port="`in-${item.id || index}`"
|
||||
:title="`入桩: ${item.name}`"
|
||||
class="port port-in"
|
||||
magnet="passive"
|
||||
:data-item="JSON.stringify(item)"
|
||||
v-for="(item, index) in element?.components || []"
|
||||
:key="item.id || index"
|
||||
class="ks-scenario-node-row"
|
||||
>
|
||||
<div class="triangle-left"></div>
|
||||
</div>
|
||||
|
||||
<!-- child名称 -->
|
||||
<div class="ks-scenario-node-name">
|
||||
{{ substring(item.description ?? item.name, 20) }}
|
||||
</div>
|
||||
|
||||
<!-- 右侧出桩:只能作为连线源 -->
|
||||
<div
|
||||
:data-port="`out-${item.id || index}`"
|
||||
:port="`out-${item.id || index}`"
|
||||
:title="`出桩: ${item.name}`"
|
||||
class="port port-out"
|
||||
magnet="active"
|
||||
:data-item="JSON.stringify(item)"
|
||||
>
|
||||
<div class="triangle-right" ></div>
|
||||
<div
|
||||
:data-port="`in-${item.id || index}`"
|
||||
:port="`in-${item.id || index}`"
|
||||
:title="`入桩: ${item.name}`"
|
||||
class="port port-in"
|
||||
magnet="passive"
|
||||
:data-item="JSON.stringify(item)"
|
||||
>
|
||||
<div class="triangle-left"></div>
|
||||
</div>
|
||||
|
||||
<!-- child名称 -->
|
||||
<div class="ks-scenario-node-name">
|
||||
{{ substring(item.description ?? item.name, 20) }}
|
||||
</div>
|
||||
|
||||
<!-- 右侧出桩:只能作为连线源 -->
|
||||
<div
|
||||
:data-port="`out-${item.id || index}`"
|
||||
:port="`out-${item.id || index}`"
|
||||
:title="`出桩: ${item.name}`"
|
||||
class="port port-out"
|
||||
magnet="active"
|
||||
:data-item="JSON.stringify(item)"
|
||||
>
|
||||
<div class="triangle-right" ></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</a-card>
|
||||
|
||||
<template #overlay>
|
||||
<a-menu @click="handleMenuClick">
|
||||
<a-sub-menu key="mount">
|
||||
<template #icon>
|
||||
<LinkOutlined />
|
||||
</template>
|
||||
<template #title>挂载</template>
|
||||
<a-menu-item
|
||||
v-for="tree in availableTrees"
|
||||
:key="`tree-${tree.id}`"
|
||||
:disabled="isTreeMounted(tree.id)"
|
||||
@click="() => handleMountTree(tree)"
|
||||
>
|
||||
</a-card>
|
||||
|
||||
<template #overlay>
|
||||
<a-menu @click="handleMenuClick">
|
||||
<a-sub-menu key="mount">
|
||||
<template #icon>
|
||||
<CheckOutlined v-if="isTreeMounted(tree.id)" />
|
||||
<LinkOutlined />
|
||||
</template>
|
||||
{{ tree.name }}
|
||||
<template #title>挂载</template>
|
||||
<a-menu-item
|
||||
v-for="tree in availableTrees"
|
||||
:key="`tree-${tree.id}`"
|
||||
:disabled="isTreeMounted(tree.id)"
|
||||
@click="() => handleMountTree(tree)"
|
||||
>
|
||||
<template #icon>
|
||||
<CheckOutlined v-if="isTreeMounted(tree.id)" />
|
||||
</template>
|
||||
{{ tree.name }}
|
||||
</a-menu-item>
|
||||
<a-menu-item v-if="availableTrees.length === 0" disabled>
|
||||
暂无可用行为树
|
||||
</a-menu-item>
|
||||
</a-sub-menu>
|
||||
<a-menu-divider />
|
||||
<a-menu-item key="delete">
|
||||
<template #icon>
|
||||
<DeleteOutlined />
|
||||
</template>
|
||||
删除
|
||||
</a-menu-item>
|
||||
<a-menu-item v-if="availableTrees.length === 0" disabled>
|
||||
暂无可用行为树
|
||||
</a-menu-item>
|
||||
</a-sub-menu>
|
||||
<a-menu-divider />
|
||||
<a-menu-item key="delete">
|
||||
<template #icon>
|
||||
<DeleteOutlined />
|
||||
</template>
|
||||
删除
|
||||
</a-menu-item>
|
||||
</a-menu>
|
||||
</template>
|
||||
</a-dropdown>
|
||||
</a-menu>
|
||||
</template>
|
||||
</a-dropdown>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
@@ -99,7 +101,7 @@ import { DeleteOutlined, LinkOutlined, CheckOutlined, SettingOutlined } from '@a
|
||||
import type { Graph } from '@antv/x6';
|
||||
import { message } from 'ant-design-vue';
|
||||
import { substring } from '@/utils/strings';
|
||||
import { getAllBehaviorTreesBySceneId, updateBehaviorTree } from './api';
|
||||
import { updateBehaviorTree, updateBehaviorTreeIdOfPlatform } from './api';
|
||||
import type { BehaviorTree } from '../designer/tree';
|
||||
|
||||
export default defineComponent({
|
||||
@@ -154,7 +156,7 @@ export default defineComponent({
|
||||
// 判断行为树是否已挂载到当前节点
|
||||
const isTreeMounted = (treeId: number): boolean => {
|
||||
if (!element.value) return false;
|
||||
const currentTreeId = (element.value as any).behaviorTreeId as number | undefined;
|
||||
const currentTreeId = (element.value as any).behaviortreeId as number | undefined;
|
||||
return currentTreeId === treeId;
|
||||
};
|
||||
|
||||
@@ -186,25 +188,23 @@ export default defineComponent({
|
||||
if (!element.value) return;
|
||||
|
||||
try {
|
||||
// 更新节点的behaviorTreeId属性
|
||||
const updatedElement = { ...(element.value as any), behaviorTreeId: tree.id };
|
||||
// 更新节点的behaviortreeId属性
|
||||
const updatedElement = { ...(element.value as any), behaviortreeId: tree.id };
|
||||
|
||||
// 调用后端API更新行为树(将platformId关联到该平台)
|
||||
const platformIdValue = (element.value as any).platformId as number | undefined;
|
||||
const treeToUpdate = {
|
||||
...tree,
|
||||
platformId: platformIdValue ?? null
|
||||
};
|
||||
|
||||
const updateResponse = await updateBehaviorTree(treeToUpdate);
|
||||
if (updateResponse.code === 200) {
|
||||
// 调用后端API:同时更新平台表的 behaviortreeId 和行为树表的 platformId
|
||||
const platformIdValue = (element.value as any).platformId as number;
|
||||
const [platformRes, treeRes] = await Promise.all([
|
||||
updateBehaviorTreeIdOfPlatform({ id: platformIdValue, behaviortreeId: tree.id }),
|
||||
updateBehaviorTree({ ...tree, platformId: platformIdValue }),
|
||||
]);
|
||||
if (platformRes.code === 200 && treeRes.code === 200) {
|
||||
// 更新本地节点数据
|
||||
if (_props.node) {
|
||||
_props.node.setData(updatedElement);
|
||||
}
|
||||
message.success(`已成功挂载行为树: ${tree.name}`);
|
||||
} else {
|
||||
message.error(updateResponse.msg || '挂载失败');
|
||||
message.error(platformRes.msg || treeRes.msg || '挂载失败');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('挂载行为树失败:', error);
|
||||
|
||||
@@ -26,7 +26,7 @@ export function resolveConnectionRelation(graph: Graph): PlatformRelation[] {
|
||||
// 过滤无效/临时边
|
||||
const validEdges = edges.filter(edge => {
|
||||
// 过滤临时边(X6 拖拽连线时生成的未完成边)
|
||||
const isTempEdge = edge?.attr('line/stroke') === 'transparent' || edge.id.includes('temp');
|
||||
const isTempEdge = edge?.attr('line/stroke') === 'transparent' || String(edge.id).includes('temp');
|
||||
if (isTempEdge) {
|
||||
tempEdgeIds.add(edge.id);
|
||||
return false;
|
||||
|
||||
@@ -10,9 +10,54 @@
|
||||
import { HttpRequestClient } from '@/utils/request';
|
||||
import type { NodeTemplatesResponse } from './template';
|
||||
import type { BehaviorTree, BehaviorTreeDetailsResponse, BehaviorTreePageResponse, BehaviorTreeRequest } from './tree';
|
||||
import type { BasicResponse } from '@/types';
|
||||
import type { BasicResponse, PageableResponse } from '@/types';
|
||||
import type { PlatformListableResponse } from '../types';
|
||||
|
||||
|
||||
|
||||
export interface TreeTemplateRow {
|
||||
id: number;
|
||||
type: string;
|
||||
name: string;
|
||||
multiable?: boolean;
|
||||
}
|
||||
|
||||
export interface TreeNodeInstanceRow {
|
||||
id: number;
|
||||
treeId: number;
|
||||
templateId: number;
|
||||
instanceName: string;
|
||||
isRoot: number;
|
||||
}
|
||||
|
||||
export interface TreeConnectionRow {
|
||||
id: number;
|
||||
treeId: number;
|
||||
parentNodeId: number;
|
||||
childNodeId: number;
|
||||
orderIndex: number;
|
||||
}
|
||||
|
||||
export interface TreeTemplateParameterDefRow {
|
||||
id: number;
|
||||
templateId: number;
|
||||
paramKey: string;
|
||||
dataType: string;
|
||||
defaultValue: string;
|
||||
description: string;
|
||||
templateType: string;
|
||||
}
|
||||
|
||||
export interface TreeNodeParameterRow {
|
||||
id: number;
|
||||
treeId: number;
|
||||
nodeInstanceId: number;
|
||||
paramDefId: number;
|
||||
value: string;
|
||||
groupIndex: number;
|
||||
}
|
||||
|
||||
|
||||
const req = HttpRequestClient.create<BasicResponse>({
|
||||
baseURL: '/api',
|
||||
});
|
||||
@@ -20,6 +65,20 @@ const req = HttpRequestClient.create<BasicResponse>({
|
||||
export const findNodeTemplates = (): Promise<NodeTemplatesResponse> => {
|
||||
return req.get('/system/nodetemplate/all');
|
||||
};
|
||||
export const findTemplateParameterDefs = (query={pageSize: 1000, pageNum: 1}): Promise<PageableResponse<TreeTemplateParameterDefRow>> => {
|
||||
return req.get('/system/templateparameterdef/list', query);
|
||||
}
|
||||
export const findNodeConnections = (query: {treeId: number}): Promise<PageableResponse<TreeConnectionRow>> => {
|
||||
return req.get('/system/nodeconnection/list', {pageSize: 1000, pageNum: 1, ...query});
|
||||
};
|
||||
export const findNodeParameters = (query: {treeId: number}): Promise<PageableResponse<TreeNodeParameterRow>> => {
|
||||
return req.get('/system/nodeparameter/list', {pageSize: 1000, pageNum: 1, ...query});
|
||||
}
|
||||
export const findTreeNodeInstances = (query: {treeId: number}): Promise<PageableResponse<TreeNodeInstanceRow>> => {
|
||||
return req.get('/system/treenodeinstance/list', {pageSize: 1000, pageNum: 1, ...query});
|
||||
}
|
||||
|
||||
|
||||
|
||||
export const findTreesByQuery = (query: Partial<BehaviorTreeRequest> = {}): Promise<BehaviorTreePageResponse> => {
|
||||
return req.get<BehaviorTreePageResponse>('/system/behaviortree/list', query);
|
||||
|
||||
@@ -5,8 +5,15 @@
|
||||
<a-layout class="ks-layout-body">
|
||||
<div class="ks-model-builder-body">
|
||||
<div class="ks-model-builder-left">
|
||||
<ScenariosCard
|
||||
ref="scenariosCardRef"
|
||||
:scenarioId="currentScenarioId"
|
||||
@select-scenario="handleSelectScenario"
|
||||
/>
|
||||
<TressCard
|
||||
ref="treesCardRef"
|
||||
:scenarioId="currentScenarioId"
|
||||
:treeId="currentTreeId"
|
||||
@create-tree="handleCreateTree"
|
||||
@select-tree="handleSelectTree"
|
||||
/>
|
||||
@@ -24,7 +31,7 @@
|
||||
<span>保存</span>
|
||||
</a-button>
|
||||
|
||||
<a-button v-if="currentScenarioId" class="ks-model-builder-save" size="small" @click="handleGoback">
|
||||
<a-button v-if="fromScenarioPage" class="ks-model-builder-save" size="small" @click="handleGoback">
|
||||
<BackwardFilled />
|
||||
<span>返回</span>
|
||||
</a-button>
|
||||
@@ -71,6 +78,7 @@ import Properties from './properties.vue';
|
||||
import type { NodeDragTemplate } from './template';
|
||||
import type { BehaviorTree } from './tree';
|
||||
import { createGraphTaskElementFromTemplate } from './utils';
|
||||
import { resolveBehaviorTreeGraph } from './reverse-tree/tree-graph-resolver';
|
||||
|
||||
import { createGraphTaskElement, createLineOptions, type GraphContainer, type GraphTaskElement, hasElements, hasRootElementNode, resolveGraph, useGraphCanvas } from '../graph';
|
||||
import { registerNodeElement } from './register';
|
||||
@@ -78,7 +86,9 @@ import { findAllBasicPlatforms, findAllNodeCommands } from '../api';
|
||||
import type { NodeCommand, Platform } from '../types';
|
||||
import { createTree, findOneTreeById, findOneTreeByPlatformId, updateTree, findSubPlatforms } from './api';
|
||||
import TressCard from './trees-card.vue';
|
||||
import ScenariosCard from './scenarios-card.vue';
|
||||
import NodesCard from './nodes-card.vue';
|
||||
import { generateKey } from '@/utils/strings';
|
||||
|
||||
const TeleportContainer = defineComponent(getTeleport());
|
||||
|
||||
@@ -86,6 +96,7 @@ registerNodeElement();
|
||||
|
||||
export default defineComponent({
|
||||
components: {
|
||||
ScenariosCard,
|
||||
TressCard,
|
||||
NodesCard,
|
||||
Wrapper,
|
||||
@@ -107,16 +118,18 @@ export default defineComponent({
|
||||
const isDraggingOver = ref(false);
|
||||
const currentTreeEditing = ref<boolean>(false);
|
||||
const currentBehaviorTree = ref<BehaviorTree | null>(null);
|
||||
const currentGraph = ref<GraphContainer | null>(null);
|
||||
const selectedModelNode = ref<Node<NodeProperties> | null>(null);
|
||||
const selectedNodeTaskElement = ref<GraphTaskElement | null>(null);
|
||||
const changed = ref<boolean>(false);
|
||||
const scenariosCardRef = ref<InstanceType<typeof ScenariosCard> | null>(null);
|
||||
const treesCardRef = ref<InstanceType<typeof TressCard> | null>(null);
|
||||
const platforms = ref<Platform[]>([]);
|
||||
const subPlatforms = ref<Platform[]>([]);
|
||||
const nodeCommands = ref<NodeCommand[]>([])
|
||||
const currentScenarioId = ref<number | null>(null);
|
||||
const currentScenarioId = ref<number | undefined>();
|
||||
const currentPlatformId = ref<number | null>(null);
|
||||
const currentTreeId = ref<number | null>(null);
|
||||
const fromScenarioPage = ref<boolean>(false);
|
||||
|
||||
const {
|
||||
handleGraphEvent,
|
||||
@@ -259,42 +272,24 @@ export default defineComponent({
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectTree = (tree: BehaviorTree) => {
|
||||
destroyGraph();
|
||||
currentPlatformId.value = null;
|
||||
currentScenarioId.value = null;
|
||||
const initGraphConfig = (_graph?: GraphContainer) => {
|
||||
const graph: GraphContainer = _graph ? _graph : {
|
||||
nodes: [],
|
||||
edges: [],
|
||||
};
|
||||
|
||||
console.info('handleSelectTree', tree);
|
||||
findOneTreeById(tree.id).then(r => {
|
||||
if (r.data) {
|
||||
let nodeGraph: GraphContainer | null = null;
|
||||
try {
|
||||
nodeGraph = JSON.parse(r.data?.xmlContent as unknown as string) as unknown as GraphContainer;
|
||||
} catch (e: any) {
|
||||
console.error('parse error,cause:', e);
|
||||
}
|
||||
if (!nodeGraph) {
|
||||
nodeGraph = {
|
||||
nodes: [],
|
||||
edges: [],
|
||||
};
|
||||
}
|
||||
currentBehaviorTree.value = {
|
||||
...r.data,
|
||||
graph: nodeGraph,
|
||||
};
|
||||
currentTreeEditing.value = true;
|
||||
|
||||
// 加载下属平台
|
||||
loadSubPlatforms(r.data.platformId);
|
||||
|
||||
nextTick(() => {
|
||||
initGraph();
|
||||
});
|
||||
} else {
|
||||
message.error(r.msg ?? '行为树不存在.');
|
||||
}
|
||||
});
|
||||
currentBehaviorTree.value = {
|
||||
id: 0,
|
||||
name: '行为树',
|
||||
description: null,
|
||||
englishName: generateKey('scenario'),
|
||||
xmlContent: null,
|
||||
createdAt: null,
|
||||
platformId: currentPlatformId.value,
|
||||
scenarioId: currentScenarioId.value,
|
||||
graph: { ...graph },
|
||||
updatedAt: null,
|
||||
};
|
||||
};
|
||||
|
||||
const createElements = () => {
|
||||
@@ -305,72 +300,107 @@ export default defineComponent({
|
||||
if (currentBehaviorTree.value?.graph.nodes) {
|
||||
currentBehaviorTree.value?.graph.nodes.forEach(ele => {
|
||||
const node = createGraphTaskElement(ele as GraphTaskElement);
|
||||
console.info('create node: ', ele);
|
||||
// 将节点添加到画布
|
||||
graph.value?.addNode(node as Node);
|
||||
});
|
||||
}
|
||||
if (currentBehaviorTree.value?.graph.edges) {
|
||||
setTimeout(() => {
|
||||
// 然后添加所有边,确保包含桩点信息
|
||||
setTimeout(() => {
|
||||
currentBehaviorTree.value?.graph.edges.forEach(edgeData => {
|
||||
graph.value?.addEdge({
|
||||
...edgeData,
|
||||
...createLineOptions(),
|
||||
});
|
||||
currentBehaviorTree.value?.graph.edges.forEach(edgeData => {
|
||||
graph.value?.addEdge({
|
||||
...edgeData,
|
||||
...createLineOptions(),
|
||||
});
|
||||
}, 100); // 延迟一会儿,免得连线错位
|
||||
}
|
||||
});
|
||||
});
|
||||
fitToScreen();
|
||||
|
||||
console.info('create elements: ', currentBehaviorTree.value?.graph);
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const resolveQuery = ()=> {
|
||||
let scenarioId = Number(currentRoute.query.scenario);
|
||||
if (!isNaN(scenarioId)) {
|
||||
currentScenarioId.value = scenarioId;
|
||||
} else {
|
||||
currentScenarioId.value = null;
|
||||
}
|
||||
let platformId = Number(currentRoute.query.platform);
|
||||
if (!isNaN(platformId)) {
|
||||
currentPlatformId.value = platformId;
|
||||
} else {
|
||||
currentPlatformId.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreateTree = () => {
|
||||
const applyBehaviorTree = (tree: BehaviorTree) => {
|
||||
destroyGraph();
|
||||
|
||||
currentBehaviorTree.value = {
|
||||
id: 0,
|
||||
name: '行为树',
|
||||
description: null,
|
||||
englishName: null,
|
||||
xmlContent: null,
|
||||
createdAt: null,
|
||||
platformId: currentPlatformId.value,
|
||||
graph: {
|
||||
edges: [],
|
||||
nodes: [],
|
||||
},
|
||||
updatedAt: null,
|
||||
};
|
||||
currentGraph.value = {
|
||||
edges: [],
|
||||
nodes: [],
|
||||
};
|
||||
currentPlatformId.value = tree.platformId ?? null;
|
||||
currentBehaviorTree.value = tree;
|
||||
currentTreeEditing.value = true;
|
||||
selectedModelNode.value = null;
|
||||
selectedNodeTaskElement.value = null;
|
||||
subPlatforms.value = []; // 重置下属平台
|
||||
|
||||
loadSubPlatforms(currentPlatformId.value);
|
||||
|
||||
nextTick(() => {
|
||||
initGraph();
|
||||
});
|
||||
};
|
||||
|
||||
const loadTargetTree = (tree: BehaviorTree) => {
|
||||
resolveBehaviorTreeGraph(tree.id, tree.xmlContent).then(nodeGraph => {
|
||||
applyBehaviorTree({
|
||||
...tree,
|
||||
graph: nodeGraph,
|
||||
});
|
||||
}).catch(error => {
|
||||
console.error('resolve tree graph error:', error);
|
||||
message.error('加载行为树图失败');
|
||||
});
|
||||
};
|
||||
|
||||
const handleCreateTree = () => {
|
||||
destroyGraph();
|
||||
|
||||
selectedModelNode.value = null;
|
||||
selectedNodeTaskElement.value = null;
|
||||
subPlatforms.value = []; // 重置下属平台
|
||||
|
||||
initGraphConfig();
|
||||
nextTick(() => {
|
||||
initGraph();
|
||||
});
|
||||
};
|
||||
|
||||
const handleSelectTree = (tree: BehaviorTree) => {
|
||||
console.info('handleSelectTree', tree);
|
||||
findOneTreeById(tree.id).then(r => {
|
||||
if (r.data) {
|
||||
currentTreeId.value = tree.id;
|
||||
loadTargetTree(r.data);
|
||||
} else {
|
||||
message.error(r.msg ?? '行为树不存在.');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const resolveQuery = ()=> {
|
||||
console.log(currentRoute);
|
||||
if (!currentRoute.query.scenarioId) {
|
||||
return
|
||||
}
|
||||
|
||||
let scenarioId = Number(currentRoute.query.scenarioId);
|
||||
if (!isNaN(scenarioId)) {
|
||||
currentScenarioId.value = scenarioId;
|
||||
fromScenarioPage.value = true;
|
||||
} else {
|
||||
fromScenarioPage.value = false;
|
||||
}
|
||||
|
||||
let behaviortreeId = Number(currentRoute.query.behaviortreeId);
|
||||
if (!isNaN(behaviortreeId)) {
|
||||
currentTreeId.value = behaviortreeId;
|
||||
} else {
|
||||
currentTreeId.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 处理选择场景
|
||||
const handleSelectScenario = (scenario: any) => {
|
||||
currentScenarioId.value = scenario.id;
|
||||
};
|
||||
|
||||
|
||||
|
||||
// 初始化X6画布
|
||||
const initGraph = () => {
|
||||
if (!canvas.value) {
|
||||
@@ -381,8 +411,15 @@ export default defineComponent({
|
||||
try {
|
||||
graph.value = createCanvas(canvas.value);
|
||||
console.log('画布初始化成功');
|
||||
|
||||
createElements();
|
||||
|
||||
graph.value?.on('edge:click', (args: any) => {
|
||||
const edge = args.edge;
|
||||
console.info('点击了连线:', args);
|
||||
// 这里可以添加选中连线的逻辑,比如显示属性面板等
|
||||
});
|
||||
|
||||
// 监听缩放变化
|
||||
handleGraphEvent('scale', ({ sx }: { sx: number }) => {
|
||||
currentZoom.value = sx;
|
||||
@@ -397,7 +434,6 @@ export default defineComponent({
|
||||
handleGraphEvent('node:click', (args: any) => {
|
||||
const node = args.node as Node<NodeProperties>;
|
||||
const newElement = node.getData() as GraphTaskElement;
|
||||
console.error('ddd', args);
|
||||
|
||||
selectedModelNode.value = node;
|
||||
selectedNodeTaskElement.value = JSON.parse(JSON.stringify(newElement || {})) as GraphTaskElement;
|
||||
@@ -423,23 +459,28 @@ export default defineComponent({
|
||||
|
||||
const init = () => {
|
||||
console.info('init');
|
||||
|
||||
resolveQuery();
|
||||
|
||||
nextTick(() => {
|
||||
initGraphConfig();
|
||||
initGraph();
|
||||
window.addEventListener('resize', handleResize);
|
||||
console.log('节点挂载完成');
|
||||
|
||||
resolveQuery();
|
||||
window.addEventListener('resize', handleResize);
|
||||
|
||||
if (currentPlatformId.value) {
|
||||
findOneTreeByPlatformId(currentPlatformId.value).then(r => {
|
||||
|
||||
|
||||
if (currentTreeId.value) {
|
||||
findOneTreeById(currentTreeId.value).then(r => {
|
||||
if (r.data) {
|
||||
handleSelectTree(r.data);
|
||||
currentPlatformId.value = r.data.platformId ?? null;
|
||||
loadTargetTree(r.data);
|
||||
} else {
|
||||
handleCreateTree();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
currentPlatformId.value = null;
|
||||
handleCreateTree();
|
||||
}
|
||||
});
|
||||
@@ -467,6 +508,7 @@ export default defineComponent({
|
||||
message.error('当前决策树不存在');
|
||||
return;
|
||||
}
|
||||
// return;
|
||||
const newTree: BehaviorTree = {
|
||||
...currentBehaviorTree.value,
|
||||
graph: graphData,
|
||||
@@ -509,13 +551,16 @@ export default defineComponent({
|
||||
return {
|
||||
nodeCommands,
|
||||
currentScenarioId,
|
||||
currentPlatformId,
|
||||
currentTreeId,
|
||||
platforms,
|
||||
subPlatforms,
|
||||
scenariosCardRef,
|
||||
treesCardRef,
|
||||
handleCreateTree,
|
||||
handleSelectScenario,
|
||||
currentTreeEditing,
|
||||
currentBehaviorTree,
|
||||
currentGraph,
|
||||
selectedNodeTaskElement,
|
||||
selectedModelNode,
|
||||
graph,
|
||||
@@ -534,6 +579,7 @@ export default defineComponent({
|
||||
handleUpdateElement,
|
||||
handleSelectTree,
|
||||
handleGoback,
|
||||
fromScenarioPage,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,49 +1,53 @@
|
||||
<template>
|
||||
<a-dropdown :trigger="['contextmenu']" @openChange="handleVisibleChange">
|
||||
<a-card
|
||||
:class="[
|
||||
'ks-designer-node',
|
||||
`ks-designer-${element?.category ?? 'model'}-node`,
|
||||
`ks-designer-group-${element?.group ?? 'general'}`
|
||||
]"
|
||||
hoverable
|
||||
>
|
||||
<template #title>
|
||||
<a-space>
|
||||
<!-- <span class="ks-designer-node-icon"></span>-->
|
||||
<span class="ks-designer-node-title">{{ element?.name ?? '-' }}</span>
|
||||
</a-space>
|
||||
<div>
|
||||
<a-dropdown :trigger="['contextmenu']" @openChange="handleVisibleChange">
|
||||
|
||||
|
||||
<a-card
|
||||
:class="[
|
||||
'ks-designer-node',
|
||||
`ks-designer-${element?.category ?? 'model'}-node`,
|
||||
`ks-designer-group-${element?.group ?? 'general'}`
|
||||
]"
|
||||
hoverable
|
||||
>
|
||||
<template #title>
|
||||
<a-space>
|
||||
<!-- <span class="ks-designer-node-icon"></span>-->
|
||||
<span class="ks-designer-node-title">{{ element?.name ?? '-' }}</span>
|
||||
</a-space>
|
||||
</template>
|
||||
|
||||
<div class="port port-in" data-port="in-0" port="in-0" magnet="passive">
|
||||
<div class="triangle-left"></div>
|
||||
</div>
|
||||
<div class="w-full ks-designer-node-text">
|
||||
<a-tooltip >
|
||||
<template #title>
|
||||
{{ element?.description ?? element?.name }}
|
||||
</template>
|
||||
<p class="ks-designer-node-label">
|
||||
{{ substring(element?.name ?? (element?.name ?? '-'), 40) }}
|
||||
</p>
|
||||
</a-tooltip>
|
||||
</div>
|
||||
<div class="port port-out" data-port="out-0" port="out-0" magnet="active">
|
||||
<div class="triangle-right" ></div>
|
||||
</div>
|
||||
</a-card>
|
||||
|
||||
<template #overlay>
|
||||
<a-menu @click="handleMenuClick">
|
||||
<a-menu-item key="delete">
|
||||
<template #icon>
|
||||
<DeleteOutlined />
|
||||
</template>
|
||||
删除
|
||||
</a-menu-item>
|
||||
</a-menu>
|
||||
</template>
|
||||
|
||||
<div class="port port-in" data-port="in-0" magnet="passive">
|
||||
<div class="triangle-left"></div>
|
||||
</div>
|
||||
<div class="w-full ks-designer-node-text">
|
||||
<a-tooltip >
|
||||
<template #title>
|
||||
{{ element?.description ?? element?.name }}
|
||||
</template>
|
||||
<p class="ks-designer-node-label">
|
||||
{{ substring(element?.name ?? (element?.name ?? '-'), 40) }}
|
||||
</p>
|
||||
</a-tooltip>
|
||||
</div>
|
||||
<div class="port port-out" data-port="out-0" magnet="active">
|
||||
<div class="triangle-right" ></div>
|
||||
</div>
|
||||
</a-card>
|
||||
|
||||
<template #overlay>
|
||||
<a-menu @click="handleMenuClick">
|
||||
<a-menu-item key="delete">
|
||||
<template #icon>
|
||||
<DeleteOutlined />
|
||||
</template>
|
||||
删除
|
||||
</a-menu-item>
|
||||
</a-menu>
|
||||
</template>
|
||||
</a-dropdown>
|
||||
</a-dropdown>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
|
||||
@@ -72,8 +72,8 @@
|
||||
<script lang="ts">
|
||||
import { defineComponent, onMounted, ref } from 'vue';
|
||||
import type { NodeDragTemplate, NodeTemplate } from './template';
|
||||
import { findNodeTemplates } from './api';
|
||||
import { safePreventDefault, safeStopPropagation } from '@/utils/event';
|
||||
import { loadNodeTemplatesOnce } from './template-metadata-loader';
|
||||
|
||||
export default defineComponent({
|
||||
emits: ['drag-item-start', 'drag-item-end'],
|
||||
@@ -95,7 +95,7 @@ export default defineComponent({
|
||||
conditionTemplates.value = [];
|
||||
actionsTemplates.value = [];
|
||||
|
||||
findNodeTemplates().then(r => {
|
||||
loadNodeTemplatesOnce().then(r => {
|
||||
templateData.value = r.data;
|
||||
if (r.data) {
|
||||
r.data.forEach(tpl => {
|
||||
|
||||
@@ -108,12 +108,13 @@
|
||||
:placeholder="setting.description" size="small" style="width:100%;" />
|
||||
<a-select :placeholder="`请选择${setting.description}`"
|
||||
allow-clear
|
||||
v-else-if="setting.paramKey === 'platforms'" v-model:value="setting.defaultValue">
|
||||
v-else-if="setting.paramKey === 'platforms'"
|
||||
v-model:value="setting.defaultValue">
|
||||
<a-select-option v-for="pl in getAvailablePlatforms()" :value="pl.name">{{pl.description}}</a-select-option>
|
||||
</a-select>
|
||||
<a-select :placeholder="`请选择${setting.description}`"
|
||||
allow-clear
|
||||
v-else-if="setting.paramKey === 'command'" v-model:value="setting.defaultValue">
|
||||
v-else-if="isNodeCommandParameter(setting.paramKey as string | null | undefined)" v-model:value="setting.defaultValue">
|
||||
<a-select-option v-for="pl in nodeCommands" :value="pl.command">{{pl.chineseName}}</a-select-option>
|
||||
</a-select>
|
||||
<a-input v-else v-model:value="setting.defaultValue"
|
||||
@@ -129,21 +130,31 @@
|
||||
</a-tabs>
|
||||
</template>
|
||||
<template v-else>
|
||||
<a-form-item v-for="setting in currentElement.parameters" :label="setting.description">
|
||||
<a-input-number v-if="setting.dataType === 'double'" v-model:value="setting.defaultValue"
|
||||
:placeholder="setting.description" size="small" style="width:100%;" />
|
||||
<a-select :placeholder="`请选择${setting.description}`"
|
||||
allow-clear
|
||||
v-else-if="setting.paramKey === 'platforms'" v-model:value="setting.defaultValue">
|
||||
<a-select-option v-for="pl in getAvailablePlatforms()" :value="pl.name">{{ pl.description }}</a-select-option>
|
||||
</a-select>
|
||||
<a-select :placeholder="`请选择${setting.description}`"
|
||||
allow-clear
|
||||
v-else-if="setting.paramKey === 'command'" v-model:value="setting.defaultValue">
|
||||
<a-select-option v-for="pl in nodeCommands" :value="pl.command">{{pl.chineseName}}</a-select-option>
|
||||
</a-select>
|
||||
<a-input v-else v-model:value="setting.defaultValue" :placeholder="setting.description" size="small" />
|
||||
</a-form-item>
|
||||
<template v-for="setting in currentElement.parameters">
|
||||
<div v-if="['lon','lat'].includes(setting.paramKey as string)">
|
||||
<div v-if="setting.paramKey==='lon'" class="ks-location-title">位置</div>
|
||||
<a-form-item class="ks-location-item" labelAlign="left" :label="setting.description">
|
||||
<a-input-number v-if="setting.dataType === 'double'" v-model:value="setting.defaultValue"
|
||||
:placeholder="setting.description" size="small" style="width:100%;" />
|
||||
<a-input v-else v-model:value="setting.defaultValue" :placeholder="setting.description" size="small" />
|
||||
</a-form-item>
|
||||
</div>
|
||||
<a-form-item v-else :label="setting.description">
|
||||
<a-input-number v-if="setting.dataType === 'double'" v-model:value="setting.defaultValue"
|
||||
:placeholder="setting.description" size="small" style="width:100%;" />
|
||||
<a-select :placeholder="`请选择${setting.description}`"
|
||||
allow-clear
|
||||
v-else-if="setting.paramKey === 'platforms'" v-model:value="setting.defaultValue">
|
||||
<a-select-option v-for="pl in getAvailablePlatforms()" :value="pl.name">{{ pl.description }}</a-select-option>
|
||||
</a-select>
|
||||
<a-select :placeholder="`请选择${setting.description}`"
|
||||
allow-clear
|
||||
v-else-if="isNodeCommandParameter(setting.paramKey as string | null | undefined)" v-model:value="setting.defaultValue">
|
||||
<a-select-option v-for="pl in nodeCommands" :value="pl.command">{{pl.chineseName}}</a-select-option>
|
||||
</a-select>
|
||||
<a-input v-else v-model:value="setting.defaultValue" :placeholder="setting.description" size="small" />
|
||||
</a-form-item>
|
||||
</template>
|
||||
</template>
|
||||
</a-form>
|
||||
</template>
|
||||
@@ -199,6 +210,10 @@ export default defineComponent({
|
||||
},
|
||||
emits: ['update-element', 'update-tree'],
|
||||
setup(props, { emit }) {
|
||||
const isNodeCommandParameter = (paramKey: string | null | undefined): boolean => {
|
||||
return ['command', 'should_task'].includes(paramKey ?? '');
|
||||
};
|
||||
|
||||
const platforms = ref<Platform[]>(props.platforms ?? []);
|
||||
const subPlatforms = ref<Platform[]>(props.subPlatforms ?? []);
|
||||
const nodeCommands = ref<NodeCommand[]>(props.nodeCommands ?? []);
|
||||
@@ -301,17 +316,46 @@ export default defineComponent({
|
||||
});
|
||||
|
||||
// 第二步:将 Map 转换为二维数组(按 groupIndex 升序排序)
|
||||
groupedParameters.value = Array.from(groupMap.entries())
|
||||
// 按分组索引从小到大排序(保证分组顺序正确)
|
||||
const rawGroups = Array.from(groupMap.entries())
|
||||
.sort((a, b) => a[0] - b[0])
|
||||
// 只保留分组后的参数数组,丢弃 key
|
||||
.map(item => item[1]);
|
||||
|
||||
// 第三步:展开逗号分隔的 platforms 值 —— 每个平台拆成独立分组
|
||||
const expandedGroups: Array<ElementParameter[]> = [];
|
||||
for (const group of rawGroups) {
|
||||
const platformParam = group.find(p => p.paramKey === 'platforms');
|
||||
if (platformParam) {
|
||||
const platformValues = String(platformParam.defaultValue ?? '')
|
||||
.split(',')
|
||||
.map(v => v.trim())
|
||||
.filter(Boolean);
|
||||
if (platformValues.length > 1) {
|
||||
// 每个平台值生成独立分组,其余参数保持一致
|
||||
for (const pv of platformValues) {
|
||||
const newGroup = JSON.parse(JSON.stringify(group)) as ElementParameter[];
|
||||
const pp = newGroup.find(p => p.paramKey === 'platforms');
|
||||
if (pp) pp.defaultValue = pv;
|
||||
expandedGroups.push(newGroup);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
expandedGroups.push(group);
|
||||
}
|
||||
|
||||
groupedParameters.value = expandedGroups;
|
||||
multiableParameters.value = multiable === true && groupedParameters.value.length > 0;
|
||||
};
|
||||
|
||||
// 获取平台Tab显示名称(优先使用下属平台名称)
|
||||
// 获取平台Tab显示名称(优先取该分组的 platforms 参数值,其次下属平台名称)
|
||||
const getPlatformTabName = (index: number): string => {
|
||||
const group = groupedParameters.value[index];
|
||||
if (group) {
|
||||
const platformParam = group.find(p => p.paramKey === 'platforms');
|
||||
if (platformParam?.defaultValue) {
|
||||
return String(platformParam.defaultValue);
|
||||
}
|
||||
}
|
||||
const sub = subPlatforms.value[index];
|
||||
if (sub) {
|
||||
return sub.name || sub.description || `平台 ${index + 1}`;
|
||||
@@ -438,6 +482,7 @@ export default defineComponent({
|
||||
groupedParameters,
|
||||
getPlatformTabName,
|
||||
getAvailablePlatforms,
|
||||
isNodeCommandParameter,
|
||||
actionSpaceColumns,
|
||||
activeTopTabsKey,
|
||||
activeBottomTabsKey,
|
||||
@@ -454,6 +499,33 @@ export default defineComponent({
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.ks-location-title {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: rgba(255, 255, 255, 0.65);
|
||||
margin-top: 6px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
:deep(.ks-location-item) {
|
||||
.ant-form-item-row {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.ant-form-item-label {
|
||||
width: 48px;
|
||||
flex-shrink: 0;
|
||||
padding-bottom: 0;
|
||||
> label {
|
||||
height: 24px;
|
||||
}
|
||||
}
|
||||
.ant-form-item-control {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.ks-parameter-setting-tabs {
|
||||
:deep(.ant-tabs-tab) {
|
||||
width: 120px;
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { GraphContainer } from '../../graph';
|
||||
import { findNodeConnections, findNodeParameters, findTreeNodeInstances } from '../api';
|
||||
import type { TreeTemplateRow } from '../api';
|
||||
import { buildGraphFromReverseTreeRows } from './reverse-tree';
|
||||
import type { ReverseTreeRows } from './reverse-tree';
|
||||
import { loadNodeTemplatesOnce, loadTemplateParameterDefsOnce } from '../template-metadata-loader';
|
||||
|
||||
// 已反演过的树直接返回缓存图,无需重复请求
|
||||
const graphCache = new Map<number, GraphContainer>();
|
||||
|
||||
export const loadReverseTreeGraph = async (treeId: number): Promise<GraphContainer | null> => {
|
||||
const cached = graphCache.get(treeId);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
// 模板类接口只请求一次,树级接口每次切树请求
|
||||
const [nodeTemplatesResponse, templateParameterDefs, instancesResponse, connectionsResponse] =
|
||||
await Promise.all([
|
||||
loadNodeTemplatesOnce(),
|
||||
loadTemplateParameterDefsOnce(),
|
||||
findTreeNodeInstances({ treeId }),
|
||||
findNodeConnections({ treeId }),
|
||||
]);
|
||||
const parametersResponse = await findNodeParameters({ treeId });
|
||||
|
||||
const rows: ReverseTreeRows = {
|
||||
templates: (nodeTemplatesResponse.data ?? []).map(t => ({
|
||||
id: t.id,
|
||||
type: t.type ?? 'action',
|
||||
name: t.name ?? '',
|
||||
multiable: t.multiable,
|
||||
})) as TreeTemplateRow[],
|
||||
templateParameterDefs: templateParameterDefs,
|
||||
nodeInstances: instancesResponse.rows ?? [],
|
||||
connections: connectionsResponse.rows ?? [],
|
||||
nodeParameters: parametersResponse.rows ?? [],
|
||||
};
|
||||
|
||||
const graph = buildGraphFromReverseTreeRows(treeId, rows);
|
||||
if (graph) {
|
||||
graphCache.set(treeId, graph);
|
||||
}
|
||||
return graph;
|
||||
};
|
||||
|
||||
export const invalidateReverseTreeCache = (treeId: number): void => {
|
||||
graphCache.delete(treeId);
|
||||
};
|
||||
267
modeler/src/views/decision/designer/reverse-tree/reverse-tree.ts
Normal file
267
modeler/src/views/decision/designer/reverse-tree/reverse-tree.ts
Normal file
@@ -0,0 +1,267 @@
|
||||
import type { ElementParameter, GraphContainer, GraphEdgeElement, GraphTaskElement } from '../../graph';
|
||||
import type {
|
||||
TreeConnectionRow as ReverseTreeConnectionRow,
|
||||
TreeNodeInstanceRow as ReverseTreeNodeInstanceRow,
|
||||
TreeNodeParameterRow as ReverseTreeNodeParameterRow,
|
||||
TreeTemplateParameterDefRow as ReverseTreeTemplateParameterDefRow,
|
||||
TreeTemplateRow as ReverseTreeTemplateRow,
|
||||
} from '../api';
|
||||
|
||||
export interface ReverseTreeRows {
|
||||
templates: ReverseTreeTemplateRow[];
|
||||
nodeInstances: ReverseTreeNodeInstanceRow[];
|
||||
connections: ReverseTreeConnectionRow[];
|
||||
templateParameterDefs: ReverseTreeTemplateParameterDefRow[];
|
||||
nodeParameters: ReverseTreeNodeParameterRow[];
|
||||
}
|
||||
|
||||
const NODE_WIDTH = 250;
|
||||
const CONTROL_HEIGHT = 60;
|
||||
const ACTION_HEIGHT = 120;
|
||||
const ROOT_X = 80;
|
||||
const ROOT_Y = 50;
|
||||
const LEVEL_Y_SPACING = 120;
|
||||
const SIBLING_X_SPACING = 280;
|
||||
|
||||
const createNodeKey = (treeId: number, nodeId: number): string => {
|
||||
return `reverse-tree-${treeId}-node-${nodeId}`;
|
||||
};
|
||||
|
||||
const createEdgeKey = (treeId: number, edgeId: number): string => {
|
||||
return `reverse-tree-${treeId}-edge-${edgeId}`;
|
||||
};
|
||||
|
||||
const createBehaviorTreeEdgeEndpoints = (sourceCell: string, targetCell: string) => {
|
||||
return {
|
||||
source: {
|
||||
cell: sourceCell,
|
||||
port: 'out-0',
|
||||
},
|
||||
target: {
|
||||
cell: targetCell,
|
||||
port: 'in-0',
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const resolveGroup = (type: string): 'control' | 'condition' | 'action' => {
|
||||
if (type === 'root' || type === 'parallel' || type === 'select' || type === 'sequence') {
|
||||
return 'control';
|
||||
}
|
||||
if (type === 'condition') {
|
||||
return 'condition';
|
||||
}
|
||||
return 'action';
|
||||
};
|
||||
|
||||
const resolveTemplateType = (type: string): string => {
|
||||
if (type === 'select') {
|
||||
return 'selector';
|
||||
}
|
||||
return type;
|
||||
};
|
||||
|
||||
const resolveNodeHeight = (group: 'control' | 'condition' | 'action'): number => {
|
||||
return group === 'action' ? ACTION_HEIGHT : CONTROL_HEIGHT;
|
||||
};
|
||||
|
||||
const findRootNodeId = (
|
||||
instances: ReverseTreeNodeInstanceRow[],
|
||||
connections: ReverseTreeConnectionRow[],
|
||||
): number | null => {
|
||||
const rootNode = instances.find(item => item.isRoot === 1);
|
||||
if (rootNode) {
|
||||
return rootNode.id;
|
||||
}
|
||||
|
||||
const childIds = new Set(connections.map(item => item.childNodeId));
|
||||
const topNode = instances.find(item => !childIds.has(item.id));
|
||||
return topNode?.id ?? null;
|
||||
};
|
||||
|
||||
export const buildGraphFromReverseTreeRows = (
|
||||
treeId: number,
|
||||
rows: ReverseTreeRows,
|
||||
): GraphContainer | null => {
|
||||
const templates = rows.templates;
|
||||
const templateParameterDefs = rows.templateParameterDefs;
|
||||
const nodeParameters = rows.nodeParameters;
|
||||
const instances = rows.nodeInstances.filter(item => item.treeId === treeId);
|
||||
const connections = rows.connections
|
||||
.filter(item => item.treeId === treeId)
|
||||
.sort((left, right) => left.orderIndex - right.orderIndex);
|
||||
const treeNodeParameters = nodeParameters.filter(item => item.treeId === treeId);
|
||||
|
||||
if (instances.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const templateMap = new Map(templates.map(item => [item.id, item]));
|
||||
const templateParameterDefsMap = new Map<number, ReverseTreeTemplateParameterDefRow[]>();
|
||||
const instanceMap = new Map(instances.map(item => [item.id, item]));
|
||||
const childrenMap = new Map<number, ReverseTreeConnectionRow[]>();
|
||||
const nodeParametersMap = new Map<number, ReverseTreeNodeParameterRow[]>();
|
||||
|
||||
templateParameterDefs.forEach(definition => {
|
||||
const currentDefinitions = templateParameterDefsMap.get(definition.templateId) ?? [];
|
||||
currentDefinitions.push(definition);
|
||||
currentDefinitions.sort((left, right) => left.id - right.id);
|
||||
templateParameterDefsMap.set(definition.templateId, currentDefinitions);
|
||||
});
|
||||
|
||||
treeNodeParameters.forEach(parameter => {
|
||||
const currentParameters = nodeParametersMap.get(parameter.nodeInstanceId) ?? [];
|
||||
currentParameters.push(parameter);
|
||||
currentParameters.sort((left, right) => {
|
||||
if (left.groupIndex !== right.groupIndex) {
|
||||
return left.groupIndex - right.groupIndex;
|
||||
}
|
||||
return left.id - right.id;
|
||||
});
|
||||
nodeParametersMap.set(parameter.nodeInstanceId, currentParameters);
|
||||
});
|
||||
|
||||
connections.forEach(connection => {
|
||||
const siblingConnections = childrenMap.get(connection.parentNodeId) ?? [];
|
||||
siblingConnections.push(connection);
|
||||
siblingConnections.sort((left, right) => left.orderIndex - right.orderIndex);
|
||||
childrenMap.set(connection.parentNodeId, siblingConnections);
|
||||
});
|
||||
|
||||
const rootNodeId = findRootNodeId(instances, connections);
|
||||
if (!rootNodeId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const leafCountCache = new Map<number, number>();
|
||||
const countLeaves = (nodeId: number): number => {
|
||||
const cachedCount = leafCountCache.get(nodeId);
|
||||
if (cachedCount) {
|
||||
return cachedCount;
|
||||
}
|
||||
|
||||
const children = childrenMap.get(nodeId) ?? [];
|
||||
if (children.length === 0) {
|
||||
leafCountCache.set(nodeId, 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const totalLeaves = children.reduce((total, connection) => {
|
||||
return total + countLeaves(connection.childNodeId);
|
||||
}, 0);
|
||||
leafCountCache.set(nodeId, totalLeaves);
|
||||
return totalLeaves;
|
||||
};
|
||||
|
||||
const nodes: GraphTaskElement[] = [];
|
||||
const edges: GraphEdgeElement[] = [];
|
||||
|
||||
const buildNodeParameters = (instance: ReverseTreeNodeInstanceRow): ElementParameter[] => {
|
||||
const parameterDefinitions = templateParameterDefsMap.get(instance.templateId) ?? [];
|
||||
if (parameterDefinitions.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const parameterRows = nodeParametersMap.get(instance.id) ?? [];
|
||||
const groupIndexes = parameterRows.length > 0
|
||||
? Array.from(new Set(parameterRows.map(item => item.groupIndex))).sort((left, right) => left - right)
|
||||
: [0];
|
||||
|
||||
return groupIndexes.flatMap(groupIndex => {
|
||||
return parameterDefinitions.map(definition => {
|
||||
const parameterRow = parameterRows.find(item => item.paramDefId === definition.id && item.groupIndex === groupIndex);
|
||||
return {
|
||||
id: definition.id,
|
||||
templateId: definition.templateId,
|
||||
paramKey: definition.paramKey,
|
||||
dataType: definition.dataType,
|
||||
defaultValue: parameterRow?.value ?? definition.defaultValue,
|
||||
description: definition.description,
|
||||
templateType: definition.templateType,
|
||||
groupIndex,
|
||||
} as ElementParameter;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const walk = (nodeId: number, startX: number, y: number): number => {
|
||||
const instance = instanceMap.get(nodeId);
|
||||
if (!instance) {
|
||||
return startX;
|
||||
}
|
||||
|
||||
const template = templateMap.get(instance.templateId);
|
||||
const templateType = template?.type ?? 'action';
|
||||
const group = resolveGroup(templateType);
|
||||
const parameters = buildNodeParameters(instance);
|
||||
const leafCount = countLeaves(nodeId);
|
||||
const totalWidth = leafCount * SIBLING_X_SPACING;
|
||||
const centerX = startX + totalWidth / 2 - SIBLING_X_SPACING / 2;
|
||||
const currentNode: GraphTaskElement = {
|
||||
id: instance.id,
|
||||
key: createNodeKey(treeId, instance.id),
|
||||
type: 'task',
|
||||
template: instance.templateId,
|
||||
templateType: resolveTemplateType(templateType),
|
||||
name: instance.instanceName || template?.name || `节点 ${instance.id}`,
|
||||
category: group,
|
||||
group,
|
||||
description: instance.instanceName || template?.name || `节点 ${instance.id}`,
|
||||
multiable: template?.multiable === true,
|
||||
order: 0,
|
||||
position: {
|
||||
x: Math.round(centerX),
|
||||
y: Math.round(y),
|
||||
},
|
||||
width: NODE_WIDTH,
|
||||
height: resolveNodeHeight(group),
|
||||
inputs: null,
|
||||
outputs: null,
|
||||
parameters,
|
||||
variables: [],
|
||||
};
|
||||
|
||||
nodes.push(currentNode);
|
||||
|
||||
const children = childrenMap.get(nodeId) ?? [];
|
||||
let childStartX = startX;
|
||||
children.forEach(connection => {
|
||||
const childLeafCount = countLeaves(connection.childNodeId);
|
||||
walk(connection.childNodeId, childStartX, y + LEVEL_Y_SPACING + currentNode.height);
|
||||
|
||||
const childInstance = instanceMap.get(connection.childNodeId);
|
||||
const edge: GraphEdgeElement = {
|
||||
id: connection.id,
|
||||
key: createEdgeKey(treeId, connection.id),
|
||||
...createBehaviorTreeEdgeEndpoints(
|
||||
currentNode.key as string,
|
||||
createNodeKey(treeId, connection.childNodeId),
|
||||
),
|
||||
attrs: {},
|
||||
router: {},
|
||||
connector: null,
|
||||
};
|
||||
|
||||
edges.push(edge);
|
||||
|
||||
const currentEdges = ((currentNode as GraphTaskElement & { edges?: GraphEdgeElement[] }).edges ?? []).slice();
|
||||
currentEdges.push({
|
||||
...edge,
|
||||
sourceName: currentNode.name,
|
||||
targetName: childInstance?.instanceName ?? childInstance?.id ?? connection.childNodeId,
|
||||
});
|
||||
(currentNode as GraphTaskElement & { edges?: GraphEdgeElement[] }).edges = currentEdges;
|
||||
|
||||
childStartX += childLeafCount * SIBLING_X_SPACING;
|
||||
});
|
||||
|
||||
return centerX;
|
||||
};
|
||||
|
||||
walk(rootNodeId, ROOT_X, ROOT_Y);
|
||||
|
||||
return {
|
||||
nodes,
|
||||
edges,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { GraphContainer } from '../../graph';
|
||||
import { loadReverseTreeGraph } from './reverse-tree-loader';
|
||||
|
||||
const EMPTY_GRAPH: GraphContainer = {
|
||||
nodes: [],
|
||||
edges: [],
|
||||
};
|
||||
|
||||
export const parseBehaviorTreeGraph = (xmlContent: string | null | undefined): GraphContainer | null => {
|
||||
if (!xmlContent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(xmlContent) as GraphContainer;
|
||||
} catch (error) {
|
||||
console.error('parse behavior tree graph error:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const hasBehaviorTreeNodes = (graph: GraphContainer | null | undefined): boolean => {
|
||||
return Boolean(graph?.nodes && graph.nodes.length > 0);
|
||||
};
|
||||
|
||||
export const loadBehaviorTreeGraphById = async (treeId: number): Promise<GraphContainer> => {
|
||||
return (await loadReverseTreeGraph(treeId)) ?? { ...EMPTY_GRAPH };
|
||||
};
|
||||
|
||||
export const resolveBehaviorTreeGraph = async (
|
||||
treeId: number,
|
||||
xmlContent: string | null | undefined,
|
||||
): Promise<GraphContainer> => {
|
||||
// void xmlContent;
|
||||
|
||||
// 如需恢复动态选择逻辑,可切回下面这段:
|
||||
const savedGraph = parseBehaviorTreeGraph(xmlContent);
|
||||
if (hasBehaviorTreeNodes(savedGraph)) {
|
||||
return savedGraph as GraphContainer;
|
||||
}
|
||||
|
||||
return loadBehaviorTreeGraphById(treeId);
|
||||
};
|
||||
138
modeler/src/views/decision/designer/scenarios-card.vue
Normal file
138
modeler/src/views/decision/designer/scenarios-card.vue
Normal file
@@ -0,0 +1,138 @@
|
||||
<template>
|
||||
<a-collapse v-model:activeKey="activeKey" :accordion="false" class="ks-trees-collapse">
|
||||
<a-collapse-panel key="1" style="position: relative">
|
||||
<template #header>
|
||||
<a-flex>
|
||||
<span class="ks-model-builder-title-icon icon-model"></span>
|
||||
<span style="color: #82c4e9;font-size: 16px;">我的场景</span>
|
||||
</a-flex>
|
||||
</template>
|
||||
<div class="w-full" style="padding: 5px;">
|
||||
<a-flex>
|
||||
<a-input-search v-model:value="scenarioQuery.name" allowClear placeholder="场景名称" size="small" @search="loadScenarios()" />
|
||||
</a-flex>
|
||||
</div>
|
||||
<a-list :data-source="scenarios || []" size="small" style="min-height: 25vh">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item :class="{ 'ks-item-selected': scenarioId === item.id }" @click="()=> handleSelect(item)">
|
||||
<a-flex>
|
||||
<a-tooltip placement="bottom">
|
||||
<template #title>
|
||||
<p>名称: {{ item.name }}</p>
|
||||
<p>说明: {{ item.description }}</p>
|
||||
</template>
|
||||
<span>{{ substring(item.name, 15) }}</span>
|
||||
</a-tooltip>
|
||||
</a-flex>
|
||||
</a-list-item>
|
||||
</template>
|
||||
</a-list>
|
||||
<a-pagination
|
||||
v-model:current="scenarioQuery.pageNum"
|
||||
:page-size="scenarioQuery.pageSize"
|
||||
:total="totalScenarios"
|
||||
style="position: unset; margin: 5px 0;"
|
||||
simple size="small" @change="handleChange" />
|
||||
</a-collapse-panel>
|
||||
</a-collapse>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, onMounted, ref, watch, type PropType } from 'vue';
|
||||
import { CopyOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
|
||||
import type { Scenario, ScenarioRequest } from '../communication/types';
|
||||
import { findScenarioByQuery } from '../communication/api';
|
||||
import { substring } from '@/utils/strings';
|
||||
|
||||
export default defineComponent({
|
||||
props: {
|
||||
scenarioId: Number as PropType<number>,
|
||||
},
|
||||
emits: ['select-scenario'],
|
||||
components: {
|
||||
CopyOutlined,
|
||||
PlusOutlined,
|
||||
DeleteOutlined,
|
||||
},
|
||||
setup(_props, { emit }) {
|
||||
const scenarios = ref<Scenario[]>([]);
|
||||
const scenarioQuery = ref<Partial<ScenarioRequest>>({
|
||||
name: null,
|
||||
pageNum: 1,
|
||||
pageSize: 8,
|
||||
});
|
||||
const activeKey = ref<number>(0);
|
||||
const totalScenarios = ref<number>(0);
|
||||
|
||||
const loadScenarios = (cb?: () => void) => {
|
||||
findScenarioByQuery(scenarioQuery.value).then(r => {
|
||||
scenarios.value = r.rows;
|
||||
totalScenarios.value = r.total ?? 0;
|
||||
if(cb) cb();
|
||||
});
|
||||
};
|
||||
|
||||
const handleChange = (page: number, pageSize: number) => {
|
||||
scenarioQuery.value.pageNum = page;
|
||||
scenarioQuery.value.pageSize = pageSize;
|
||||
loadScenarios();
|
||||
};
|
||||
|
||||
const handleSelect = (record: Scenario) => {
|
||||
emit('select-scenario', record);
|
||||
};
|
||||
|
||||
const refresh = () => loadScenarios();
|
||||
|
||||
onMounted(() => {
|
||||
loadScenarios(() => {
|
||||
if (_props.scenarioId) {
|
||||
return;
|
||||
}
|
||||
// 默认选中第一个场景
|
||||
const selectedScenario = scenarios.value[0];
|
||||
if (selectedScenario) {
|
||||
emit('select-scenario', selectedScenario);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
refresh,
|
||||
totalScenarios,
|
||||
substring,
|
||||
activeKey,
|
||||
scenarios,
|
||||
scenarioQuery,
|
||||
loadScenarios,
|
||||
handleSelect,
|
||||
handleChange,
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.a-list-item {
|
||||
cursor: pointer;
|
||||
padding: 8px 12px;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.a-list-item:hover {
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.icon-scenario::before {
|
||||
content: '\e6b8';
|
||||
font-family: 'iconfont';
|
||||
margin-right: 8px;
|
||||
color: #82c4e9;
|
||||
}
|
||||
|
||||
:deep(.ant-list-item.ks-item-selected) {
|
||||
background-color: rgba(130, 196, 233, 0.15);
|
||||
border-left: 3px solid #82c4e9;
|
||||
padding-left: 9px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,32 @@
|
||||
import { findNodeTemplates, findTemplateParameterDefs } from './api';
|
||||
import type { TreeTemplateParameterDefRow } from './api';
|
||||
import type { NodeTemplatesResponse } from './template';
|
||||
|
||||
// 模板列表:全局只请求一次
|
||||
let nodeTemplatesPromise: Promise<NodeTemplatesResponse> | null = null;
|
||||
|
||||
// 模板参数定义:全局只请求一次
|
||||
let templateParameterDefsPromise: Promise<TreeTemplateParameterDefRow[]> | null = null;
|
||||
|
||||
export const loadNodeTemplatesOnce = (): Promise<NodeTemplatesResponse> => {
|
||||
if (!nodeTemplatesPromise) {
|
||||
nodeTemplatesPromise = findNodeTemplates().catch(err => {
|
||||
// 请求失败时清除缓存,下次可以重试
|
||||
nodeTemplatesPromise = null;
|
||||
return Promise.reject(err);
|
||||
});
|
||||
}
|
||||
return nodeTemplatesPromise;
|
||||
};
|
||||
|
||||
export const loadTemplateParameterDefsOnce = (): Promise<TreeTemplateParameterDefRow[]> => {
|
||||
if (!templateParameterDefsPromise) {
|
||||
templateParameterDefsPromise = findTemplateParameterDefs()
|
||||
.then(r => r.rows ?? [])
|
||||
.catch(err => {
|
||||
templateParameterDefsPromise = null;
|
||||
return Promise.reject(err);
|
||||
});
|
||||
}
|
||||
return templateParameterDefsPromise;
|
||||
};
|
||||
@@ -20,11 +20,13 @@ export interface BehaviorTree {
|
||||
xmlContent: NullableString,
|
||||
graph: GraphContainer
|
||||
platformId: null | number
|
||||
scenarioId?: number,
|
||||
}
|
||||
|
||||
export interface BehaviorTreeRequest extends BehaviorTree {
|
||||
pageNum: number,
|
||||
pageSize: number,
|
||||
scenarioId?: number,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
</div>
|
||||
<a-list :data-source="behaviorTrees || []" size="small" style="min-height: 25vh">
|
||||
<template #renderItem="{ item }">
|
||||
<a-list-item @click="()=> handleSelect(item)">
|
||||
<a-list-item :class="{ 'ks-item-selected': treeId === item.id }" @click="()=> handleSelect(item)">
|
||||
<a-flex>
|
||||
<a-tooltip placement="bottom">
|
||||
<template #title>
|
||||
@@ -50,19 +50,25 @@
|
||||
v-model:current="behaviorTreeQuery.pageNum"
|
||||
:page-size="behaviorTreeQuery.pageSize"
|
||||
:total="totalTress"
|
||||
style="position: unset; margin: 5px 0;"
|
||||
simple size="small" @change="handleChange" />
|
||||
</a-collapse-panel>
|
||||
</a-collapse>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, onMounted, ref } from 'vue';
|
||||
import type { PropType } from 'vue';
|
||||
import { defineComponent, onMounted, ref, watch } from 'vue';
|
||||
import { CheckOutlined, CopyOutlined, DeleteOutlined, EditFilled, PlusOutlined } from '@ant-design/icons-vue';
|
||||
import type { BehaviorTree, BehaviorTreeRequest } from './tree';
|
||||
import { copyTree, deleteOneTreeById, findTreesByQuery } from './api';
|
||||
import { substring } from '@/utils/strings';
|
||||
|
||||
export default defineComponent({
|
||||
props: {
|
||||
scenarioId: Number as PropType<number | undefined>,
|
||||
treeId: Number as PropType<number | null>,
|
||||
},
|
||||
emits: ['select-tree', 'create-tree'],
|
||||
components: {
|
||||
CheckOutlined,
|
||||
@@ -71,20 +77,37 @@ export default defineComponent({
|
||||
DeleteOutlined,
|
||||
EditFilled,
|
||||
},
|
||||
setup(_props, { emit }) {
|
||||
setup(props, { emit }) {
|
||||
const behaviorTrees = ref<BehaviorTree[]>([]);
|
||||
const behaviorTreeQuery = ref<Partial<BehaviorTreeRequest>>({
|
||||
name: null,
|
||||
pageNum: 1,
|
||||
pageSize: 8,
|
||||
scenarioId: props.scenarioId,
|
||||
});
|
||||
const activeKey = ref<number>(1);
|
||||
const totalTress = ref<number>(0);
|
||||
|
||||
const loadTress = () => {
|
||||
watch(
|
||||
() => props.scenarioId,
|
||||
() => {
|
||||
if (!props.scenarioId) {
|
||||
behaviorTrees.value = [];
|
||||
totalTress.value = 0;
|
||||
return;
|
||||
}
|
||||
behaviorTreeQuery.value.pageNum = 1;
|
||||
behaviorTreeQuery.value.scenarioId = props.scenarioId;
|
||||
loadTress();
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
function loadTress(cb?: () => void) {
|
||||
findTreesByQuery(behaviorTreeQuery.value).then(r => {
|
||||
behaviorTrees.value = r.rows;
|
||||
totalTress.value = r.total ?? 0;
|
||||
if (cb) cb();
|
||||
});
|
||||
};
|
||||
|
||||
@@ -131,10 +154,6 @@ export default defineComponent({
|
||||
|
||||
const refresh = () => loadTress();
|
||||
|
||||
onMounted(() => {
|
||||
loadTress();
|
||||
});
|
||||
|
||||
return {
|
||||
refresh,
|
||||
totalTress,
|
||||
@@ -155,3 +174,11 @@ export default defineComponent({
|
||||
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
:deep(.ant-list-item.ks-item-selected) {
|
||||
background-color: rgba(130, 196, 233, 0.15);
|
||||
border-left: 3px solid #82c4e9;
|
||||
padding-left: 9px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -11,21 +11,136 @@ import { Edge, Graph, Path, Selection } from '@antv/x6';
|
||||
import { createLineOptions, type ModelElement } from '../graph';
|
||||
import type { Connecting } from '@antv/x6/lib/graph/options';
|
||||
|
||||
|
||||
Graph.registerConnector(
|
||||
'sequenceFlowConnector',
|
||||
(s, e) => {
|
||||
const offset = 4;
|
||||
const deltaY = Math.abs(e.y - s.y);
|
||||
const control = Math.floor((deltaY / 3) * 2);
|
||||
(s, e, _r, args) => {
|
||||
const stub = 16;
|
||||
|
||||
const v1 = { x: s.x, y: s.y + offset + control };
|
||||
const v2 = { x: e.x, y: e.y - offset - control };
|
||||
// 根据端点相对于节点 bbox 的位置判断端口朝向:1=向右出/入,-1=向左出/入
|
||||
const sBBox = (args as any)?.sourceBBox;
|
||||
const tBBox = (args as any)?.targetBBox;
|
||||
const sSide: 1 | -1 = sBBox
|
||||
? (s.x >= sBBox.x + sBBox.width / 2 ? 1 : -1)
|
||||
: 1;
|
||||
const tSide: 1 | -1 = tBBox
|
||||
? (e.x >= tBBox.x + tBBox.width / 2 ? 1 : -1)
|
||||
: -1;
|
||||
|
||||
// 端口外侧 stub 后的延伸点
|
||||
const sx2 = s.x + stub * sSide;
|
||||
const ex2 = e.x + stub * tSide;
|
||||
|
||||
const dy = e.y - s.y;
|
||||
const absDy = Math.abs(dy);
|
||||
const dir = dy >= 0 ? 1 : -1;
|
||||
|
||||
// 沿出口方向是否有足够空间走贝塞尔(端口相对 + dx 充足)
|
||||
const dxAligned = (ex2 - sx2) * sSide; // 出口方向上的有效距离
|
||||
const control = Math.max(Math.abs(ex2 - sx2) * 0.5, absDy * 0.35, 36);
|
||||
const canDirectBezier = sSide !== tSide && dxAligned > control;
|
||||
|
||||
if (canDirectBezier) {
|
||||
const v1 = { x: sx2 + control * sSide, y: s.y };
|
||||
const v2 = { x: ex2 + control * tSide, y: e.y };
|
||||
return Path.parse(
|
||||
`
|
||||
M ${s.x} ${s.y}
|
||||
L ${sx2} ${s.y}
|
||||
C ${v1.x} ${v1.y} ${v2.x} ${v2.y} ${ex2} ${e.y}
|
||||
L ${e.x} ${e.y}
|
||||
`,
|
||||
).serialize();
|
||||
}
|
||||
|
||||
// 两端朝向相同:单侧 U 形绕行
|
||||
if (sSide === tSide) {
|
||||
const offset = Math.max(absDy * 0.2, 50);
|
||||
const bypassX = sSide === 1
|
||||
? Math.max(sx2, ex2) + offset
|
||||
: Math.min(sx2, ex2) - offset;
|
||||
const r = Math.min(20, absDy / 2);
|
||||
return Path.parse(
|
||||
`
|
||||
M ${s.x} ${s.y}
|
||||
L ${bypassX - r * sSide} ${s.y}
|
||||
Q ${bypassX} ${s.y} ${bypassX} ${s.y + r * dir}
|
||||
L ${bypassX} ${e.y - r * dir}
|
||||
Q ${bypassX} ${e.y} ${bypassX - r * tSide} ${e.y}
|
||||
L ${e.x} ${e.y}
|
||||
`,
|
||||
).serialize();
|
||||
}
|
||||
|
||||
// 端口相对但水平距离不足(反向交叉):Z 形 —— 两段竖直 + 中间水平
|
||||
const offset = Math.max(absDy * 0.15, 40);
|
||||
const sBypassX = sx2 + offset * sSide;
|
||||
const tBypassX = ex2 + offset * tSide;
|
||||
const midY = s.y + dy / 2;
|
||||
const r = Math.min(
|
||||
16,
|
||||
absDy / 4,
|
||||
Math.abs(sBypassX - tBypassX) / 2,
|
||||
);
|
||||
return Path.parse(
|
||||
`
|
||||
M ${s.x} ${s.y}
|
||||
L ${sBypassX - r * sSide} ${s.y}
|
||||
Q ${sBypassX} ${s.y} ${sBypassX} ${s.y + r * dir}
|
||||
L ${sBypassX} ${midY - r * dir}
|
||||
Q ${sBypassX} ${midY} ${sBypassX - r * sSide} ${midY}
|
||||
L ${tBypassX - r * tSide} ${midY}
|
||||
Q ${tBypassX} ${midY} ${tBypassX} ${midY + r * dir}
|
||||
L ${tBypassX} ${e.y - r * dir}
|
||||
Q ${tBypassX} ${e.y} ${tBypassX - r * tSide} ${e.y}
|
||||
L ${e.x} ${e.y}
|
||||
`,
|
||||
).serialize();
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
Graph.registerConnector(
|
||||
'quadraticBezierCurveConnector',
|
||||
(s, e) => {
|
||||
const stub = 16;
|
||||
const dx = e.x - s.x;
|
||||
const dy = e.y - s.y;
|
||||
const absDy = Math.abs(dy);
|
||||
const dir = dy >= 0 ? 1 : -1; // 1=向下,-1=向上
|
||||
|
||||
// 预先计算贝塞尔控制点距离
|
||||
const control = Math.max(Math.abs(dx) * 0.5, absDy * 0.35, 36);
|
||||
|
||||
// 当水平距离不足以容纳两侧控制点时(v1/v2 会超出节点范围),改用 U 形绕行
|
||||
// 条件:dx < stub + control 意味着 v2.x = e.x - stub - control < s.x,会穿越节点
|
||||
if (dx < stub + control) {
|
||||
// bypassX:取两端口最大 x 再向右延伸,垂直距离越大延伸越宽
|
||||
const bypassX = Math.max(s.x, e.x) + Math.max(absDy * 0.2, 50);
|
||||
// 圆角半径:不超过 20px,也不超过竖直段长度一半
|
||||
const r = Math.min(20, absDy / 2);
|
||||
|
||||
return Path.parse(
|
||||
`
|
||||
M ${s.x} ${s.y}
|
||||
L ${bypassX - r} ${s.y}
|
||||
Q ${bypassX} ${s.y} ${bypassX} ${s.y + r * dir}
|
||||
L ${bypassX} ${e.y - r * dir}
|
||||
Q ${bypassX} ${e.y} ${bypassX - r} ${e.y}
|
||||
L ${e.x} ${e.y}
|
||||
`,
|
||||
).serialize();
|
||||
}
|
||||
|
||||
// 正向连接:水平贝塞尔 S 曲线,控制点始终沿水平方向延伸
|
||||
const v1 = { x: s.x + stub + control, y: s.y };
|
||||
const v2 = { x: e.x - stub - control, y: e.y };
|
||||
|
||||
return Path.parse(
|
||||
`
|
||||
M ${s.x} ${s.y}
|
||||
L ${s.x} ${s.y + offset}
|
||||
C ${v1.x} ${v1.y} ${v2.x} ${v2.y} ${e.x} ${e.y - offset}
|
||||
L ${s.x + stub} ${s.y}
|
||||
C ${v1.x} ${v1.y} ${v2.x} ${v2.y} ${e.x - stub} ${e.y}
|
||||
L ${e.x} ${e.y}
|
||||
`,
|
||||
).serialize();
|
||||
@@ -40,7 +155,7 @@ export const createGraphConnectingAttributes = (): Partial<Connecting> => {
|
||||
allowBlank: false, // 是否允许连接到画布空白位置的点,默认为 true
|
||||
allowLoop: false, // 是否允许创建循环连线,即边的起始节点和终止节点为同一节点,默认为 true
|
||||
highlight: true, // 当连接到节点时,通过 sourceAnchor 来指定源节点的锚点。
|
||||
connector: 'smooth',
|
||||
connector: 'sequenceFlowConnector',
|
||||
connectionPoint: 'anchor', // 指定连接点,默认值为 boundary。
|
||||
anchor: 'center',
|
||||
// validateMagnet({ magnet }) {
|
||||
|
||||
@@ -735,6 +735,7 @@ const createNodeObjects = (
|
||||
type: 'scenario',
|
||||
name: platform,
|
||||
platformId: platformId,
|
||||
behaviortreeId: platformData?.behaviortreeId ?? null,
|
||||
scenarioId: nodeScenarioId, // 修复:优先使用platformData.scenarioId
|
||||
components: components,
|
||||
template: 0,
|
||||
@@ -829,6 +830,7 @@ const createRootNode = (
|
||||
type: 'scenario',
|
||||
name: rootPlatformName,
|
||||
platformId: platformId,
|
||||
behaviortreeId: platformData?.behaviortreeId ?? null,
|
||||
scenarioId: rootNodeScenarioId, // 修复:优先使用platformData.scenarioId
|
||||
components: components,
|
||||
template: 0,
|
||||
|
||||
@@ -100,8 +100,8 @@ export interface ModelElement extends GraphBaseElement {
|
||||
export interface GraphEdgeElement {
|
||||
id: number;
|
||||
key: NullableString;
|
||||
source: NullableString;
|
||||
target: NullableString;
|
||||
source: NullableString | Record<string, any>;
|
||||
target: NullableString | Record<string, any>;
|
||||
attrs: Record<any, any>;
|
||||
router: Record<any, any>;
|
||||
connector: any;
|
||||
|
||||
@@ -58,14 +58,12 @@ export const useGraphCanvas = (readonly: boolean = false): UseGraphCanvas => {
|
||||
if (graph.value) {
|
||||
clearGraph();
|
||||
|
||||
// 等待 Vue 完成卸载
|
||||
nextTick(() => {
|
||||
graph.value?.dispose(); // 销毁 Graph 实例
|
||||
graph.value = null;
|
||||
if (container.value) {
|
||||
container.value.innerHTML = ''; // 清空容器内容
|
||||
}
|
||||
});
|
||||
// 同步销毁 Graph 实例,避免异步导致的竞态条件
|
||||
graph.value.dispose();
|
||||
graph.value = null;
|
||||
if (container.value) {
|
||||
container.value.innerHTML = ''; // 清空容器内容
|
||||
}
|
||||
} else if (container.value) {
|
||||
container.value.innerHTML = '';
|
||||
}
|
||||
@@ -222,7 +220,8 @@ export const useGraphCanvas = (readonly: boolean = false): UseGraphCanvas => {
|
||||
|
||||
// 监听节点选中事件
|
||||
graph.value.on('node:selected', ({ node }) => {
|
||||
console.info('node select', node);
|
||||
console.info('node select', node,node.getData());
|
||||
|
||||
emitGraphEvent('node:selected', node);
|
||||
});
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<Header />
|
||||
<a-layout class="ks-layout-body">
|
||||
<slot name="body">
|
||||
<a-layout-sider class="ks-layout-sidebar" width="300">
|
||||
<a-layout-sider class="ks-layout-sidebar" :class="sidebarClass" width="300">
|
||||
<slot name="sidebar" />
|
||||
</a-layout-sider>
|
||||
<a-layout-content class="ks-layout-main">
|
||||
@@ -21,4 +21,9 @@
|
||||
<script lang="ts" setup>
|
||||
import { Wrapper } from '@/components/wrapper';
|
||||
import Header from './header.vue';
|
||||
|
||||
defineProps<{
|
||||
/** 追加在 ks-layout-sidebar 上的类名,用于单页侧栏皮肤 */
|
||||
sidebarClass?: string;
|
||||
}>();
|
||||
</script>
|
||||
309
modeler/src/views/decision/rule-config/RuleBlockNeoGraph.vue
Normal file
309
modeler/src/views/decision/rule-config/RuleBlockNeoGraph.vue
Normal file
@@ -0,0 +1,309 @@
|
||||
<!--
|
||||
- This file is part of the kernelstudio package.
|
||||
-
|
||||
- (c) 2014-2026 zlin <admin@kernelstudio.com>
|
||||
-
|
||||
- For the full copyright and license information, please view the LICENSE file
|
||||
- that was distributed with this source code.
|
||||
-->
|
||||
<template>
|
||||
<div class="rule-block-neo-graph">
|
||||
<div v-if="emptyHint" class="rule-block-neo-graph__empty">{{ emptyHint }}</div>
|
||||
<div v-show="!emptyHint" ref="hostRef" class="rule-block-neo-graph__host" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Graph } from '@antv/g6';
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import type { RuleGraphEdge, RuleGraphNode, RuleGraphPayload } from './types';
|
||||
|
||||
const props = defineProps<{
|
||||
payload: RuleGraphPayload,
|
||||
accent?: string,
|
||||
}>();
|
||||
|
||||
const hostRef = ref<HTMLDivElement | null>(null);
|
||||
const emptyHint = ref<string | null>(null);
|
||||
|
||||
let graph: Graph | null = null;
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
|
||||
const toGraphData = (payload: RuleGraphPayload) => ({
|
||||
nodes: (payload.nodes ?? []).map((n: RuleGraphNode) => ({
|
||||
id: n.id,
|
||||
data: {
|
||||
label: n.label,
|
||||
nodeType: n.nodeType,
|
||||
payload: n.payload ?? {},
|
||||
},
|
||||
})),
|
||||
edges: (payload.edges ?? []).map((e: RuleGraphEdge) => ({
|
||||
id: e.id,
|
||||
source: e.source,
|
||||
target: e.target,
|
||||
data: {
|
||||
edgeType: e.edgeType ?? '',
|
||||
label: e.label ?? '',
|
||||
},
|
||||
})),
|
||||
});
|
||||
|
||||
const disposeGraph = async () => {
|
||||
resizeObserver?.disconnect();
|
||||
resizeObserver = null;
|
||||
if (graph) {
|
||||
try {
|
||||
graph.destroy();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
graph = null;
|
||||
}
|
||||
};
|
||||
|
||||
const nodeSize = (nodeType?: string) => {
|
||||
if (nodeType === 'drools_facade' || nodeType === 'logicCore') {
|
||||
return 36;
|
||||
}
|
||||
if (nodeType === 'compute_step') {
|
||||
return 30;
|
||||
}
|
||||
if (nodeType === 'rule_row') {
|
||||
return 26;
|
||||
}
|
||||
if (nodeType === 'param') {
|
||||
return 20;
|
||||
}
|
||||
if (nodeType === 'param_condition') {
|
||||
return 15;
|
||||
}
|
||||
if (nodeType === 'rule_output') {
|
||||
return 19;
|
||||
}
|
||||
return 22;
|
||||
};
|
||||
|
||||
const buildGraph = async () => {
|
||||
await disposeGraph();
|
||||
await nextTick();
|
||||
const el = hostRef.value;
|
||||
const raw = props.payload;
|
||||
if (!el || !raw?.nodes?.length) {
|
||||
emptyHint.value = raw && raw.nodes?.length === 0 ? '暂无图谱节点' : null;
|
||||
return;
|
||||
}
|
||||
emptyHint.value = null;
|
||||
|
||||
const accent = props.accent ?? '#5B8FF9';
|
||||
const fillFor = (nodeType?: string) => {
|
||||
if (nodeType === 'drools_facade' || nodeType === 'logicCore') {
|
||||
return accent;
|
||||
}
|
||||
if (nodeType === 'compute_step') {
|
||||
return '#ffe58f';
|
||||
}
|
||||
if (nodeType === 'rule_row') {
|
||||
return '#36cfc9';
|
||||
}
|
||||
if (nodeType === 'param') {
|
||||
return '#b37feb';
|
||||
}
|
||||
if (nodeType === 'param_condition') {
|
||||
return '#5cdbd3';
|
||||
}
|
||||
if (nodeType === 'rule_output') {
|
||||
return '#fa8c16';
|
||||
}
|
||||
return '#8c8c8c';
|
||||
};
|
||||
|
||||
const labelMaxFor = (nodeType?: string) => {
|
||||
if (nodeType === 'compute_step') {
|
||||
return 200;
|
||||
}
|
||||
if (nodeType === 'rule_output') {
|
||||
return 190;
|
||||
}
|
||||
if (nodeType === 'param_condition') {
|
||||
return 120;
|
||||
}
|
||||
return 140;
|
||||
};
|
||||
|
||||
const labelSizeFor = (nodeType?: string) => {
|
||||
if (nodeType === 'compute_step') {
|
||||
return 8;
|
||||
}
|
||||
if (nodeType === 'rule_output') {
|
||||
return 8;
|
||||
}
|
||||
if (nodeType === 'param_condition') {
|
||||
return 7;
|
||||
}
|
||||
if (nodeType === 'drools_facade' || nodeType === 'logicCore') {
|
||||
return 11;
|
||||
}
|
||||
return 9;
|
||||
};
|
||||
|
||||
const width = Math.max(el.clientWidth, 160);
|
||||
const height = Math.max(el.clientHeight, 260);
|
||||
|
||||
const data = toGraphData(raw);
|
||||
|
||||
const useRadial = raw.layoutHint === 'radial_hub' && !!raw.focusNodeId;
|
||||
const layoutOpts = useRadial
|
||||
? {
|
||||
type: 'radial' as const,
|
||||
focusNode: raw.focusNodeId,
|
||||
unitRadius: 88,
|
||||
preventOverlap: true,
|
||||
}
|
||||
: {
|
||||
type: 'd3-force' as const,
|
||||
};
|
||||
|
||||
graph = new Graph({
|
||||
container: el,
|
||||
width,
|
||||
height,
|
||||
data,
|
||||
layout: layoutOpts,
|
||||
node: {
|
||||
style: {
|
||||
size: (d: { data?: { nodeType?: string } }) => nodeSize(d.data?.nodeType),
|
||||
fill: (d: { data?: { nodeType?: string } }) => fillFor(d.data?.nodeType),
|
||||
labelText: (d: { data?: { label?: string }; id: string }) => d.data?.label ?? String(d.id),
|
||||
labelFill: (d: { data?: { nodeType?: string } }) => {
|
||||
const t = d.data?.nodeType;
|
||||
if (t === 'compute_step') {
|
||||
return '#3d2f00';
|
||||
}
|
||||
if (t === 'rule_output') {
|
||||
return '#2b1604';
|
||||
}
|
||||
if (t === 'param_condition') {
|
||||
return '#06302b';
|
||||
}
|
||||
return '#e8f4f8';
|
||||
},
|
||||
labelFontSize: (d: { data?: { nodeType?: string } }) => labelSizeFor(d.data?.nodeType),
|
||||
labelMaxWidth: (d: { data?: { nodeType?: string } }) => labelMaxFor(d.data?.nodeType),
|
||||
labelWordWrap: true,
|
||||
lineWidth: 1.2,
|
||||
stroke: '#050d14',
|
||||
},
|
||||
},
|
||||
edge: {
|
||||
style: {
|
||||
stroke: (d: { data?: { edgeType?: string } }) => {
|
||||
const t = d.data?.edgeType;
|
||||
if (t === 'compute_flow') {
|
||||
return 'rgba(149, 222, 100, 0.85)';
|
||||
}
|
||||
if (t === 'rule_priority_next') {
|
||||
return '#faad14';
|
||||
}
|
||||
if (t === 'drools_contains') {
|
||||
return 'rgba(91, 143, 249, 0.75)';
|
||||
}
|
||||
if (t === 'rule_has_param') {
|
||||
return 'rgba(179, 127, 235, 0.55)';
|
||||
}
|
||||
if (t === 'rule_produces') {
|
||||
return 'rgba(250, 173, 20, 0.75)';
|
||||
}
|
||||
if (t === 'condition_applies') {
|
||||
return 'rgba(92, 219, 211, 0.65)';
|
||||
}
|
||||
return 'rgba(150, 175, 190, 0.45)';
|
||||
},
|
||||
lineWidth: (d: { data?: { edgeType?: string } }) => {
|
||||
const t = d.data?.edgeType;
|
||||
if (t === 'rule_priority_next' || t === 'compute_flow') {
|
||||
return 2;
|
||||
}
|
||||
if (t === 'rule_produces') {
|
||||
return 1.5;
|
||||
}
|
||||
if (t === 'condition_applies') {
|
||||
return 1.2;
|
||||
}
|
||||
return 1;
|
||||
},
|
||||
endArrow: true,
|
||||
labelText: (d: { data?: { label?: string } }) => {
|
||||
const s = d.data?.label;
|
||||
return s && String(s).length > 0 ? String(s) : '';
|
||||
},
|
||||
labelFill: '#9fb8c4',
|
||||
labelFontSize: 9,
|
||||
},
|
||||
},
|
||||
behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'],
|
||||
});
|
||||
|
||||
await graph.render();
|
||||
await graph.fitView();
|
||||
|
||||
resizeObserver = new ResizeObserver(() => {
|
||||
if (!graph || !hostRef.value) {
|
||||
return;
|
||||
}
|
||||
const w = Math.max(hostRef.value.clientWidth, 160);
|
||||
const h = Math.max(hostRef.value.clientHeight, 260);
|
||||
graph.setSize(w, h);
|
||||
void graph.fitView();
|
||||
});
|
||||
resizeObserver.observe(el);
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [props.payload, props.accent],
|
||||
() => {
|
||||
void buildGraph();
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
|
||||
onMounted(() => {
|
||||
void buildGraph();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
void disposeGraph();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.rule-block-neo-graph {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.rule-block-neo-graph__host {
|
||||
flex: 1;
|
||||
min-height: 260px;
|
||||
width: 100%;
|
||||
border-radius: 8px;
|
||||
background: #0a1620;
|
||||
border: 1px solid rgba(80, 120, 150, 0.35);
|
||||
}
|
||||
|
||||
.rule-block-neo-graph__empty {
|
||||
flex: 1;
|
||||
min-height: 260px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
color: #7a8d96;
|
||||
border-radius: 8px;
|
||||
background: #0a1620;
|
||||
border: 1px dashed rgba(80, 120, 150, 0.35);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,502 @@
|
||||
<template>
|
||||
<div class="rule-decision-binary-tree">
|
||||
<div class="rule-decision-binary-tree__toolbar">
|
||||
<a-popover placement="bottomLeft" trigger="click" overlay-class-name="rule-decision-binary-tree-snapshot-popover">
|
||||
<template #content>
|
||||
<pre class="rule-decision-binary-tree__popover-json">{{ previewJson }}</pre>
|
||||
</template>
|
||||
<a-button type="link" size="small" class="rule-decision-binary-tree__snapshot-btn">
|
||||
全局参数快照({{ previewEntryCount }})
|
||||
</a-button>
|
||||
</a-popover>
|
||||
</div>
|
||||
|
||||
<div v-if="errorMsg" class="rule-decision-binary-tree__banner rule-decision-binary-tree__banner--error">
|
||||
{{ errorMsg }}
|
||||
</div>
|
||||
<div v-else-if="emptyHint" class="rule-decision-binary-tree__banner">
|
||||
{{ emptyHint }}
|
||||
</div>
|
||||
<div v-else ref="hostRef" class="rule-decision-binary-tree__canvas" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Graph } from '@antv/g6';
|
||||
import { message } from 'ant-design-vue';
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { findRuleDecisionTree } from './api';
|
||||
import type { RuleConfigRequest, RuleDecisionBlock, RuleDecisionNode, RuleDecisionTreePayload } from './types';
|
||||
|
||||
const props = defineProps<{
|
||||
query: RuleConfigRequest,
|
||||
refreshKey: number,
|
||||
}>();
|
||||
|
||||
type BinaryGraphNode = {
|
||||
id: string,
|
||||
label: string,
|
||||
nodeType: string,
|
||||
description?: string,
|
||||
fullText?: string,
|
||||
};
|
||||
|
||||
const hostRef = ref<HTMLDivElement | null>(null);
|
||||
const errorMsg = ref<string | null>(null);
|
||||
const emptyHint = ref<string | null>(null);
|
||||
const payload = ref<RuleDecisionTreePayload | null>(null);
|
||||
const renderVersion = ref(0);
|
||||
|
||||
let graph: Graph | null = null;
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
|
||||
const previewEntryCount = computed(() => {
|
||||
const p = payload.value?.globalParamsPreview;
|
||||
return p ? Object.keys(p).length : 0;
|
||||
});
|
||||
|
||||
const previewJson = computed(() => {
|
||||
const p = payload.value?.globalParamsPreview;
|
||||
if (!p) {
|
||||
return '';
|
||||
}
|
||||
try {
|
||||
return JSON.stringify(p, null, 2);
|
||||
} catch {
|
||||
return String(p);
|
||||
}
|
||||
});
|
||||
|
||||
const NODE_COLORS: Record<string, string> = {
|
||||
start: '#4fb3ff',
|
||||
decision: '#ffd166',
|
||||
if: '#49c59c',
|
||||
else: '#ff9c4a',
|
||||
output: '#9270CA',
|
||||
end: '#e8684a',
|
||||
};
|
||||
|
||||
const BLOCK_TITLE: Record<string, string> = {
|
||||
equipment: '装备规则',
|
||||
target: '目标规则',
|
||||
position: '阵位规则',
|
||||
track: '航迹规则',
|
||||
};
|
||||
|
||||
const flatten = (nodes: RuleDecisionNode[] | null | undefined): RuleDecisionNode[] => {
|
||||
const out: RuleDecisionNode[] = [];
|
||||
const visit = (list: RuleDecisionNode[] | null | undefined) => {
|
||||
(list ?? []).forEach((node) => {
|
||||
out.push(node);
|
||||
visit(node.children ?? []);
|
||||
});
|
||||
};
|
||||
visit(nodes);
|
||||
return out;
|
||||
};
|
||||
|
||||
const pickImportantParams = (flatNodes: RuleDecisionNode[]) =>
|
||||
flatNodes.filter((node) => node.nodeType === 'input_param' || node.nodeType === 'param').slice(0, 2);
|
||||
|
||||
const pickConditions = (flatNodes: RuleDecisionNode[]) =>
|
||||
flatNodes.filter((node) => node.nodeType === 'condition').slice(0, 1);
|
||||
|
||||
const pickOutputs = (flatNodes: RuleDecisionNode[]) =>
|
||||
flatNodes.filter((node) => node.nodeType === 'output' || node.nodeType === 'outcome').slice(0, 2);
|
||||
|
||||
const shortText = (text: string | null | undefined, max = 44) => {
|
||||
const value = String(text ?? '').replace(/\s+/g, ' ').trim();
|
||||
if (!value) {
|
||||
return '';
|
||||
}
|
||||
return value.length > max ? `${value.slice(0, max)}...` : value;
|
||||
};
|
||||
|
||||
const buildConditionText = (block: RuleDecisionBlock) => {
|
||||
const flatNodes = flatten(block.nodes);
|
||||
const condition = pickConditions(flatNodes)[0];
|
||||
if (condition?.description) {
|
||||
return shortText(condition.description, 52);
|
||||
}
|
||||
const param = pickImportantParams(flatNodes)[0];
|
||||
if (param) {
|
||||
return `${param.title} 是否满足当前规则条件`;
|
||||
}
|
||||
return `${BLOCK_TITLE[block.blockId] ?? block.title ?? block.blockId} 是否命中`;
|
||||
};
|
||||
|
||||
const buildIfText = (block: RuleDecisionBlock) => {
|
||||
const flatNodes = flatten(block.nodes);
|
||||
const outputs = pickOutputs(flatNodes);
|
||||
if (outputs.length > 0) {
|
||||
return outputs.map((item) => shortText(item.title || item.description, 30)).join(';');
|
||||
}
|
||||
return `进入${BLOCK_TITLE[block.blockId] ?? block.title ?? block.blockId}处理`;
|
||||
};
|
||||
|
||||
const buildElseText = (block: RuleDecisionBlock) =>
|
||||
`不满足当前条件,跳过${BLOCK_TITLE[block.blockId] ?? block.title ?? block.blockId},继续后续判断`;
|
||||
|
||||
const buildBinaryGraph = (tree: RuleDecisionTreePayload) => {
|
||||
const nodes: BinaryGraphNode[] = [];
|
||||
const edges: Array<{ source: string; target: string; label?: string }> = [];
|
||||
|
||||
const startId = 'binary:start';
|
||||
nodes.push({
|
||||
id: startId,
|
||||
label: '开始',
|
||||
nodeType: 'start',
|
||||
description: '载入关键参数,进入规则判断',
|
||||
fullText: '开始:载入关键参数,进入规则判断',
|
||||
});
|
||||
|
||||
const blocks = [...(tree.blocks ?? [])];
|
||||
|
||||
const attachSubtree = (parentId: string, branchLabel: string, branchType: 'if' | 'else', description: string, blockIndex: number) => {
|
||||
const branchId = `${parentId}:${branchType}:${blockIndex}`;
|
||||
nodes.push({
|
||||
id: branchId,
|
||||
label: branchType === 'if' ? 'If' : 'Else',
|
||||
nodeType: branchType,
|
||||
description,
|
||||
fullText: `${branchType === 'if' ? 'If' : 'Else'}:${description}`,
|
||||
});
|
||||
edges.push({ source: parentId, target: branchId, label: branchLabel });
|
||||
|
||||
if (blockIndex >= blocks.length) {
|
||||
const endId = `${branchId}:end`;
|
||||
nodes.push({
|
||||
id: endId,
|
||||
label: '输出 / 结束',
|
||||
nodeType: 'end',
|
||||
description: '输出最终规则结果',
|
||||
});
|
||||
edges.push({ source: branchId, target: endId });
|
||||
return;
|
||||
}
|
||||
|
||||
const block = blocks[blockIndex];
|
||||
if (!block) {
|
||||
const endId = `${branchId}:end:fallback`;
|
||||
nodes.push({
|
||||
id: endId,
|
||||
label: '输出 / 结束',
|
||||
nodeType: 'end',
|
||||
description: '输出最终规则结果',
|
||||
});
|
||||
edges.push({ source: branchId, target: endId });
|
||||
return;
|
||||
}
|
||||
const decisionId = `${branchId}:decision:${block.blockId}:${blockIndex}`;
|
||||
nodes.push({
|
||||
id: decisionId,
|
||||
label: `${BLOCK_TITLE[block.blockId] ?? block.title ?? block.blockId}判断`,
|
||||
nodeType: 'decision',
|
||||
description: buildConditionText(block),
|
||||
fullText: `${BLOCK_TITLE[block.blockId] ?? block.title ?? block.blockId}判断:${buildConditionText(block)}`,
|
||||
});
|
||||
edges.push({ source: branchId, target: decisionId });
|
||||
|
||||
attachSubtree(decisionId, '满足', 'if', buildIfText(block), blockIndex + 1);
|
||||
attachSubtree(decisionId, '不满足', 'else', buildElseText(block), blockIndex + 1);
|
||||
};
|
||||
|
||||
if (!blocks.length) {
|
||||
const endId = 'binary:end:empty';
|
||||
nodes.push({
|
||||
id: endId,
|
||||
label: '输出 / 结束',
|
||||
nodeType: 'end',
|
||||
description: '当前没有可用规则',
|
||||
fullText: '输出 / 结束:当前没有可用规则',
|
||||
});
|
||||
edges.push({ source: startId, target: endId });
|
||||
return { nodes, edges };
|
||||
}
|
||||
|
||||
const first = blocks[0];
|
||||
if (!first) {
|
||||
const endId = 'binary:end:fallback';
|
||||
nodes.push({
|
||||
id: endId,
|
||||
label: '输出 / 结束',
|
||||
nodeType: 'end',
|
||||
description: '当前没有可用规则',
|
||||
});
|
||||
edges.push({ source: startId, target: endId });
|
||||
return { nodes, edges };
|
||||
}
|
||||
const firstDecisionId = `binary:decision:${first.blockId}:0`;
|
||||
nodes.push({
|
||||
id: firstDecisionId,
|
||||
label: `${BLOCK_TITLE[first.blockId] ?? first.title ?? first.blockId}判断`,
|
||||
nodeType: 'decision',
|
||||
description: buildConditionText(first),
|
||||
fullText: `${BLOCK_TITLE[first.blockId] ?? first.title ?? first.blockId}判断:${buildConditionText(first)}`,
|
||||
});
|
||||
edges.push({ source: startId, target: firstDecisionId });
|
||||
|
||||
attachSubtree(firstDecisionId, '满足', 'if', buildIfText(first), 1);
|
||||
attachSubtree(firstDecisionId, '不满足', 'else', buildElseText(first), 1);
|
||||
|
||||
return { nodes, edges };
|
||||
};
|
||||
|
||||
const disposeGraph = () => {
|
||||
resizeObserver?.disconnect();
|
||||
resizeObserver = null;
|
||||
if (graph) {
|
||||
try {
|
||||
graph.destroy();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
graph = null;
|
||||
}
|
||||
hostRef.value?.replaceChildren();
|
||||
};
|
||||
|
||||
const renderGraph = async (tree: RuleDecisionTreePayload, version: number) => {
|
||||
const host = hostRef.value;
|
||||
if (!host) {
|
||||
return;
|
||||
}
|
||||
disposeGraph();
|
||||
if (version !== renderVersion.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
const data = buildBinaryGraph(tree);
|
||||
graph = new Graph({
|
||||
container: host,
|
||||
width: Math.max(host.clientWidth, 320),
|
||||
height: Math.max(host.clientHeight, 260),
|
||||
data: {
|
||||
nodes: data.nodes.map((node) => ({
|
||||
id: node.id,
|
||||
data: node,
|
||||
})),
|
||||
edges: data.edges.map((edge, index) => ({
|
||||
id: `edge:${index}:${edge.source}:${edge.target}`,
|
||||
source: edge.source,
|
||||
target: edge.target,
|
||||
data: { label: edge.label ?? '' },
|
||||
})),
|
||||
},
|
||||
layout: {
|
||||
type: 'antv-dagre',
|
||||
rankdir: 'TB',
|
||||
nodesep: 28,
|
||||
ranksep: 42,
|
||||
},
|
||||
node: {
|
||||
type: (model: { data?: { nodeType?: string } }) => {
|
||||
const t = model.data?.nodeType;
|
||||
if (t === 'start') return 'rect';
|
||||
if (t === 'end' || t === 'decision') return 'diamond';
|
||||
return 'circle';
|
||||
},
|
||||
style: {
|
||||
size: (model: { data?: { nodeType?: string } }) => {
|
||||
const t = model.data?.nodeType;
|
||||
if (t === 'start') return 24;
|
||||
if (t === 'end') return 22;
|
||||
if (t === 'decision') return 26;
|
||||
return 18;
|
||||
},
|
||||
fill: (model: { data?: { nodeType?: string } }) => NODE_COLORS[model.data?.nodeType ?? 'decision'] ?? '#5B8FF9',
|
||||
stroke: '#0d1f2c',
|
||||
lineWidth: 1.5,
|
||||
labelText: (model: { data?: { label?: string; description?: string; fullText?: string; nodeType?: string } }) => {
|
||||
const fullText = model.data?.fullText;
|
||||
if (fullText) {
|
||||
return fullText;
|
||||
}
|
||||
const label = model.data?.label ?? '';
|
||||
const description = model.data?.description;
|
||||
return description ? `${label}\n${description}` : label;
|
||||
},
|
||||
labelFill: '#e8f4f8',
|
||||
labelFontSize: 11,
|
||||
labelLineHeight: 15,
|
||||
labelWordWrap: true,
|
||||
labelMaxWidth: 320,
|
||||
labelPlacement: (model: { data?: { nodeType?: string } }) => {
|
||||
const t = model.data?.nodeType;
|
||||
if (t === 'decision' || t === 'if' || t === 'else' || t === 'output' || t === 'end') {
|
||||
return 'right';
|
||||
}
|
||||
return 'bottom';
|
||||
},
|
||||
labelOffsetX: (model: { data?: { nodeType?: string } }) => {
|
||||
const t = model.data?.nodeType;
|
||||
if (t === 'decision' || t === 'if' || t === 'else' || t === 'output' || t === 'end') {
|
||||
return 14;
|
||||
}
|
||||
return 0;
|
||||
},
|
||||
labelTextAlign: (model: { data?: { nodeType?: string } }) => {
|
||||
const t = model.data?.nodeType;
|
||||
if (t === 'decision' || t === 'if' || t === 'else' || t === 'output' || t === 'end') {
|
||||
return 'left';
|
||||
}
|
||||
return 'center';
|
||||
},
|
||||
labelBackground: true,
|
||||
labelBackgroundFill: 'rgba(6, 21, 40, 0.88)',
|
||||
labelBackgroundRadius: 4,
|
||||
labelPadding: [6, 8],
|
||||
},
|
||||
},
|
||||
edge: {
|
||||
style: {
|
||||
stroke: 'rgba(120, 170, 200, 0.52)',
|
||||
lineWidth: 1.2,
|
||||
endArrow: true,
|
||||
labelText: (edge: { data?: { label?: string } }) => edge.data?.label ?? '',
|
||||
labelFill: '#9ad0f5',
|
||||
labelFontSize: 11,
|
||||
labelBackground: true,
|
||||
labelBackgroundFill: 'rgba(6, 21, 40, 0.85)',
|
||||
labelBackgroundRadius: 3,
|
||||
labelPadding: [2, 6],
|
||||
},
|
||||
},
|
||||
behaviors: ['drag-canvas', 'zoom-canvas'],
|
||||
});
|
||||
|
||||
await graph.render();
|
||||
if (version !== renderVersion.value) {
|
||||
disposeGraph();
|
||||
return;
|
||||
}
|
||||
await graph.fitView({ when: 'always' });
|
||||
|
||||
resizeObserver = new ResizeObserver(() => {
|
||||
if (!graph || !hostRef.value) {
|
||||
return;
|
||||
}
|
||||
graph.setSize(Math.max(hostRef.value.clientWidth, 320), Math.max(hostRef.value.clientHeight, 260));
|
||||
void graph.fitView({ when: 'overflow' });
|
||||
});
|
||||
resizeObserver.observe(host);
|
||||
};
|
||||
|
||||
const load = async () => {
|
||||
errorMsg.value = null;
|
||||
emptyHint.value = null;
|
||||
payload.value = null;
|
||||
renderVersion.value += 1;
|
||||
disposeGraph();
|
||||
try {
|
||||
const r = await findRuleDecisionTree({
|
||||
pageNum: props.query.pageNum,
|
||||
pageSize: props.query.pageSize,
|
||||
ruleCode: props.query.ruleCode ?? undefined,
|
||||
ruleName: props.query.ruleName ?? undefined,
|
||||
levelCode: props.query.levelCode ?? undefined,
|
||||
kindCode: props.query.kindCode ?? undefined,
|
||||
moduleCode: props.query.moduleCode ?? undefined,
|
||||
enabled: props.query.enabled ?? undefined,
|
||||
});
|
||||
if (r.code !== 200 || !r.data) {
|
||||
errorMsg.value = r.msg ?? '加载二叉决策树失败';
|
||||
return;
|
||||
}
|
||||
if (!r.data.blocks?.length) {
|
||||
emptyHint.value = '当前没有可展示的二叉决策树数据';
|
||||
return;
|
||||
}
|
||||
payload.value = r.data;
|
||||
await nextTick();
|
||||
await renderGraph(r.data, renderVersion.value);
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
errorMsg.value = `二叉决策树请求失败:${msg}`;
|
||||
message.error(errorMsg.value);
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [props.query.pageNum, props.query.pageSize, props.refreshKey],
|
||||
() => {
|
||||
void load();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
renderVersion.value += 1;
|
||||
disposeGraph();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.rule-decision-binary-tree {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.rule-decision-binary-tree__toolbar {
|
||||
flex: 0 0 auto;
|
||||
padding: 0 2px;
|
||||
}
|
||||
|
||||
.rule-decision-binary-tree__snapshot-btn {
|
||||
padding-left: 0;
|
||||
font-size: 11px;
|
||||
color: #8fafbd;
|
||||
}
|
||||
|
||||
.rule-decision-binary-tree__banner {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 12px;
|
||||
font-size: 13px;
|
||||
color: #a2b1ba;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.rule-decision-binary-tree__banner--error {
|
||||
color: #ff9c9c;
|
||||
}
|
||||
|
||||
.rule-decision-binary-tree__canvas {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
border: 1px solid rgba(80, 120, 150, 0.22);
|
||||
border-radius: 4px;
|
||||
background: rgba(4, 18, 28, 0.35);
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
.rule-decision-binary-tree-snapshot-popover {
|
||||
.ant-popover-inner-content {
|
||||
max-width: min(520px, 90vw);
|
||||
max-height: 70vh;
|
||||
overflow: auto;
|
||||
background: #081e3b;
|
||||
}
|
||||
|
||||
.ant-popover-inner {
|
||||
background: #081e3b;
|
||||
}
|
||||
}
|
||||
|
||||
.rule-decision-binary-tree__popover-json {
|
||||
margin: 0;
|
||||
font-size: 10px;
|
||||
line-height: 1.35;
|
||||
color: #c9dfe8;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
</style>
|
||||
415
modeler/src/views/decision/rule-config/RuleDecisionTreePanel.vue
Normal file
415
modeler/src/views/decision/rule-config/RuleDecisionTreePanel.vue
Normal file
@@ -0,0 +1,415 @@
|
||||
<template>
|
||||
<div class="rule-decision-tree">
|
||||
<div class="rule-decision-tree__toolbar">
|
||||
<a-popover placement="bottomLeft" trigger="click" overlay-class-name="rule-decision-tree-snapshot-popover">
|
||||
<template #content>
|
||||
<pre class="rule-decision-tree__popover-json">{{ previewJson }}</pre>
|
||||
</template>
|
||||
<a-button type="link" size="small" class="rule-decision-tree__snapshot-btn">
|
||||
全局参数快照({{ previewEntryCount }})
|
||||
</a-button>
|
||||
</a-popover>
|
||||
</div>
|
||||
|
||||
<div v-if="errorMsg" class="rule-decision-tree__banner rule-decision-tree__banner--error">
|
||||
{{ errorMsg }}
|
||||
</div>
|
||||
<div v-else-if="emptyHint" class="rule-decision-tree__banner">
|
||||
{{ emptyHint }}
|
||||
</div>
|
||||
<div v-else-if="payload" class="rule-decision-tree__grid">
|
||||
<section
|
||||
v-for="block in payload.blocks"
|
||||
:key="block.blockId"
|
||||
class="rule-decision-tree__pane"
|
||||
>
|
||||
<header class="rule-decision-tree__pane-header">
|
||||
<div class="rule-decision-tree__pane-title">{{ block.title || block.blockId }}</div>
|
||||
<div class="rule-decision-tree__pane-meta">
|
||||
模块:{{ block.moduleCode || '-' }} / salience:{{ block.salience ?? '-' }}
|
||||
</div>
|
||||
</header>
|
||||
<div
|
||||
:ref="(el) => registerHost(block.blockId, el)"
|
||||
class="rule-decision-tree__canvas"
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Graph } from '@antv/g6';
|
||||
import { message } from 'ant-design-vue';
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { findRuleDecisionTree } from './api';
|
||||
import type { RuleConfigRequest, RuleDecisionBlock, RuleDecisionNode, RuleDecisionTreePayload } from './types';
|
||||
|
||||
const props = defineProps<{
|
||||
query: RuleConfigRequest,
|
||||
refreshKey: number,
|
||||
}>();
|
||||
|
||||
const payload = ref<RuleDecisionTreePayload | null>(null);
|
||||
const errorMsg = ref<string | null>(null);
|
||||
const emptyHint = ref<string | null>(null);
|
||||
|
||||
const hostMap = new Map<string, HTMLDivElement>();
|
||||
const graphMap = new Map<string, Graph>();
|
||||
const resizeMap = new Map<string, ResizeObserver>();
|
||||
const renderVersion = ref(0);
|
||||
|
||||
const previewEntryCount = computed(() => {
|
||||
const p = payload.value?.globalParamsPreview;
|
||||
return p ? Object.keys(p).length : 0;
|
||||
});
|
||||
|
||||
const previewJson = computed(() => {
|
||||
const p = payload.value?.globalParamsPreview;
|
||||
if (!p) {
|
||||
return '';
|
||||
}
|
||||
try {
|
||||
return JSON.stringify(p, null, 2);
|
||||
} catch {
|
||||
return String(p);
|
||||
}
|
||||
});
|
||||
|
||||
const BLOCK_COLORS: Record<string, string> = {
|
||||
equipment: '#5B8FF9',
|
||||
target: '#F6903D',
|
||||
position: '#61DDAA',
|
||||
track: '#9270CA',
|
||||
};
|
||||
|
||||
const NODE_COLORS: Record<string, string> = {
|
||||
root: '#5B8FF9',
|
||||
input_group: '#5B8FF9',
|
||||
input_param: '#4fb3ff',
|
||||
step_group: '#61DDAA',
|
||||
step: '#49c59c',
|
||||
rule_group: '#F6903D',
|
||||
rule: '#ff9c4a',
|
||||
condition: '#ffd166',
|
||||
task_types: '#9ad0f5',
|
||||
param_group: '#3db2ff',
|
||||
param: '#5ab9ff',
|
||||
output_group: '#f08c6c',
|
||||
output: '#ffb366',
|
||||
outcome_group: '#9270CA',
|
||||
outcome: '#a98cf0',
|
||||
end: '#e8684a',
|
||||
empty: '#6f8194',
|
||||
};
|
||||
|
||||
const registerHost = (blockId: string, el: unknown) => {
|
||||
if (!(el instanceof HTMLDivElement)) {
|
||||
disposeBlock(blockId);
|
||||
hostMap.delete(blockId);
|
||||
return;
|
||||
}
|
||||
hostMap.set(blockId, el);
|
||||
};
|
||||
|
||||
const flattenTree = (block: RuleDecisionBlock) => {
|
||||
const nodes: Array<{ id: string; label: string; nodeType: string; valueText?: string | null; description?: string | null }> = [];
|
||||
const edges: Array<{ source: string; target: string }> = [];
|
||||
const rootId = `block:${block.blockId}:root`;
|
||||
|
||||
nodes.push({
|
||||
id: rootId,
|
||||
label: block.title || block.blockId,
|
||||
nodeType: 'root',
|
||||
valueText: block.salience != null ? `salience=${block.salience}` : undefined,
|
||||
description: block.droolsRuleName || undefined,
|
||||
});
|
||||
|
||||
const visit = (node: RuleDecisionNode, parentId: string) => {
|
||||
const desc = node.description ? (node.valueText ? `${node.description} | ${node.valueText}` : node.description) : (node.valueText ?? '');
|
||||
nodes.push({
|
||||
id: node.key,
|
||||
label: node.title,
|
||||
nodeType: node.nodeType,
|
||||
description: desc || undefined,
|
||||
});
|
||||
edges.push({ source: parentId, target: node.key });
|
||||
(node.children ?? []).forEach((child) => visit(child, node.key));
|
||||
};
|
||||
|
||||
(block.nodes ?? []).forEach((node) => visit(node, rootId));
|
||||
return { nodes, edges };
|
||||
};
|
||||
|
||||
const disposeBlock = (blockId: string) => {
|
||||
resizeMap.get(blockId)?.disconnect();
|
||||
resizeMap.delete(blockId);
|
||||
const graph = graphMap.get(blockId);
|
||||
if (graph) {
|
||||
try {
|
||||
graph.destroy();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
graphMap.delete(blockId);
|
||||
}
|
||||
const host = hostMap.get(blockId);
|
||||
if (host) {
|
||||
host.replaceChildren();
|
||||
}
|
||||
};
|
||||
|
||||
const renderBlock = async (block: RuleDecisionBlock, version: number) => {
|
||||
const host = hostMap.get(block.blockId);
|
||||
if (!host) {
|
||||
return;
|
||||
}
|
||||
disposeBlock(block.blockId);
|
||||
if (version !== renderVersion.value) {
|
||||
return;
|
||||
}
|
||||
const width = Math.max(host.clientWidth, 320);
|
||||
const height = Math.max(host.clientHeight, 240);
|
||||
const accent = BLOCK_COLORS[block.blockId] ?? '#5B8FF9';
|
||||
const data = flattenTree(block);
|
||||
|
||||
const graph = new Graph({
|
||||
container: host,
|
||||
width,
|
||||
height,
|
||||
data: {
|
||||
nodes: data.nodes.map((node) => ({
|
||||
id: node.id,
|
||||
data: node,
|
||||
})),
|
||||
edges: data.edges,
|
||||
},
|
||||
layout: {
|
||||
type: 'antv-dagre',
|
||||
rankdir: 'TB',
|
||||
nodesep: 20,
|
||||
ranksep: 42,
|
||||
},
|
||||
node: {
|
||||
type: (model: { data?: { nodeType?: string } }) => {
|
||||
const t = model.data?.nodeType;
|
||||
if (t === 'input_group') return 'rect';
|
||||
if (t === 'end') return 'diamond';
|
||||
return 'circle';
|
||||
},
|
||||
style: {
|
||||
size: (model: { data?: { nodeType?: string } }) => {
|
||||
const t = model.data?.nodeType;
|
||||
if (t === 'root') return 18;
|
||||
if (t === 'input_group' || t === 'end') return 20;
|
||||
return 14;
|
||||
},
|
||||
fill: (model: { data?: { nodeType?: string } }) => NODE_COLORS[model.data?.nodeType ?? ''] ?? accent,
|
||||
stroke: '#0d1f2c',
|
||||
lineWidth: 1.5,
|
||||
labelText: (model: { data?: { label?: string; description?: string } }) => {
|
||||
const label = model.data?.label ?? '';
|
||||
const description = model.data?.description;
|
||||
return description ? `${label}\n${description}` : label;
|
||||
},
|
||||
labelFill: '#e8f4f8',
|
||||
labelFontSize: 11,
|
||||
labelLineHeight: 15,
|
||||
labelWordWrap: true,
|
||||
labelMaxWidth: 160,
|
||||
},
|
||||
},
|
||||
edge: {
|
||||
style: {
|
||||
stroke: 'rgba(120, 170, 200, 0.52)',
|
||||
lineWidth: 1.2,
|
||||
endArrow: true,
|
||||
},
|
||||
},
|
||||
behaviors: ['drag-canvas', 'zoom-canvas'],
|
||||
});
|
||||
|
||||
await graph.render();
|
||||
if (version !== renderVersion.value) {
|
||||
try {
|
||||
graph.destroy();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return;
|
||||
}
|
||||
await graph.fitView({ when: 'always' });
|
||||
graphMap.set(block.blockId, graph);
|
||||
|
||||
const observer = new ResizeObserver(() => {
|
||||
const nextWidth = Math.max(host.clientWidth, 320);
|
||||
const nextHeight = Math.max(host.clientHeight, 240);
|
||||
graph.setSize(nextWidth, nextHeight);
|
||||
void graph.fitView({ when: 'overflow' });
|
||||
});
|
||||
observer.observe(host);
|
||||
resizeMap.set(block.blockId, observer);
|
||||
};
|
||||
|
||||
const renderAll = async () => {
|
||||
if (!payload.value?.blocks?.length) {
|
||||
return;
|
||||
}
|
||||
await nextTick();
|
||||
const version = renderVersion.value;
|
||||
for (const block of payload.value.blocks) {
|
||||
await renderBlock(block, version);
|
||||
}
|
||||
};
|
||||
|
||||
const load = async () => {
|
||||
errorMsg.value = null;
|
||||
emptyHint.value = null;
|
||||
payload.value = null;
|
||||
renderVersion.value += 1;
|
||||
Array.from(graphMap.keys()).forEach(disposeBlock);
|
||||
try {
|
||||
const r = await findRuleDecisionTree({
|
||||
pageNum: props.query.pageNum,
|
||||
pageSize: props.query.pageSize,
|
||||
ruleCode: props.query.ruleCode ?? undefined,
|
||||
ruleName: props.query.ruleName ?? undefined,
|
||||
levelCode: props.query.levelCode ?? undefined,
|
||||
kindCode: props.query.kindCode ?? undefined,
|
||||
moduleCode: props.query.moduleCode ?? undefined,
|
||||
enabled: props.query.enabled ?? undefined,
|
||||
});
|
||||
if (r.code !== 200 || !r.data) {
|
||||
errorMsg.value = r.msg ?? '加载决策树失败';
|
||||
return;
|
||||
}
|
||||
if (!r.data.blocks?.length) {
|
||||
emptyHint.value = '当前没有可展示的规则决策树数据';
|
||||
return;
|
||||
}
|
||||
payload.value = r.data;
|
||||
await renderAll();
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
errorMsg.value = `决策树请求失败:${msg}`;
|
||||
message.error(errorMsg.value);
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [props.query.pageNum, props.query.pageSize, props.refreshKey],
|
||||
() => {
|
||||
void load();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
renderVersion.value += 1;
|
||||
Array.from(graphMap.keys()).forEach(disposeBlock);
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.rule-decision-tree {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.rule-decision-tree__toolbar {
|
||||
flex: 0 0 auto;
|
||||
padding: 0 2px;
|
||||
}
|
||||
|
||||
.rule-decision-tree__snapshot-btn {
|
||||
padding-left: 0;
|
||||
font-size: 11px;
|
||||
color: #8fafbd;
|
||||
}
|
||||
|
||||
.rule-decision-tree__banner {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 12px;
|
||||
font-size: 13px;
|
||||
color: #a2b1ba;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.rule-decision-tree__banner--error {
|
||||
color: #ff9c9c;
|
||||
}
|
||||
|
||||
.rule-decision-tree__grid {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
grid-template-rows: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.rule-decision-tree__pane {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
border: 1px solid rgba(80, 120, 150, 0.25);
|
||||
background: linear-gradient(180deg, rgba(8, 20, 30, 0.78) 0%, rgba(5, 16, 29, 0.9) 100%);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.rule-decision-tree__pane-header {
|
||||
flex: 0 0 auto;
|
||||
padding: 8px 10px 6px;
|
||||
border-bottom: 1px solid rgba(80, 120, 150, 0.2);
|
||||
background: rgba(10, 28, 40, 0.78);
|
||||
}
|
||||
|
||||
.rule-decision-tree__pane-title {
|
||||
font-size: 14px;
|
||||
color: #d8edf6;
|
||||
}
|
||||
|
||||
.rule-decision-tree__pane-meta {
|
||||
margin-top: 2px;
|
||||
font-size: 11px;
|
||||
color: #7f9aaa;
|
||||
}
|
||||
|
||||
.rule-decision-tree__canvas {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
background: transparent;
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
.rule-decision-tree-snapshot-popover {
|
||||
.ant-popover-inner-content {
|
||||
max-width: min(520px, 90vw);
|
||||
max-height: 70vh;
|
||||
overflow: auto;
|
||||
background: #081e3b;
|
||||
}
|
||||
|
||||
.ant-popover-inner {
|
||||
background: #081e3b;
|
||||
}
|
||||
}
|
||||
|
||||
.rule-decision-tree__popover-json {
|
||||
margin: 0;
|
||||
font-size: 10px;
|
||||
line-height: 1.35;
|
||||
color: #c9dfe8;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,466 @@
|
||||
<template>
|
||||
<div class="rule-decision-tree-simple">
|
||||
<div class="rule-decision-tree-simple__toolbar">
|
||||
<a-popover placement="bottomLeft" trigger="click" overlay-class-name="rule-decision-tree-simple-snapshot-popover">
|
||||
<template #content>
|
||||
<pre class="rule-decision-tree-simple__popover-json">{{ previewJson }}</pre>
|
||||
</template>
|
||||
<a-button type="link" size="small" class="rule-decision-tree-simple__snapshot-btn">
|
||||
全局参数快照({{ previewEntryCount }})
|
||||
</a-button>
|
||||
</a-popover>
|
||||
</div>
|
||||
|
||||
<div v-if="errorMsg" class="rule-decision-tree-simple__banner rule-decision-tree-simple__banner--error">
|
||||
{{ errorMsg }}
|
||||
</div>
|
||||
<div v-else-if="emptyHint" class="rule-decision-tree-simple__banner">
|
||||
{{ emptyHint }}
|
||||
</div>
|
||||
<div v-else ref="hostRef" class="rule-decision-tree-simple__canvas" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Graph } from '@antv/g6';
|
||||
import { message } from 'ant-design-vue';
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { findRuleDecisionTree } from './api';
|
||||
import type { RuleConfigRequest, RuleDecisionBlock, RuleDecisionNode, RuleDecisionTreePayload } from './types';
|
||||
|
||||
const props = defineProps<{
|
||||
query: RuleConfigRequest,
|
||||
refreshKey: number,
|
||||
}>();
|
||||
|
||||
type GraphNode = {
|
||||
id: string,
|
||||
label: string,
|
||||
nodeType: string,
|
||||
description?: string,
|
||||
fullText?: string,
|
||||
};
|
||||
|
||||
const hostRef = ref<HTMLDivElement | null>(null);
|
||||
const errorMsg = ref<string | null>(null);
|
||||
const emptyHint = ref<string | null>(null);
|
||||
const payload = ref<RuleDecisionTreePayload | null>(null);
|
||||
const renderVersion = ref(0);
|
||||
|
||||
let graph: Graph | null = null;
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
|
||||
const previewEntryCount = computed(() => {
|
||||
const p = payload.value?.globalParamsPreview;
|
||||
return p ? Object.keys(p).length : 0;
|
||||
});
|
||||
|
||||
const previewJson = computed(() => {
|
||||
const p = payload.value?.globalParamsPreview;
|
||||
if (!p) {
|
||||
return '';
|
||||
}
|
||||
try {
|
||||
return JSON.stringify(p, null, 2);
|
||||
} catch {
|
||||
return String(p);
|
||||
}
|
||||
});
|
||||
|
||||
const NODE_COLORS: Record<string, string> = {
|
||||
start: '#4fb3ff',
|
||||
block: '#5B8FF9',
|
||||
params: '#49c59c',
|
||||
rules: '#ff9c4a',
|
||||
outputs: '#a98cf0',
|
||||
end: '#e8684a',
|
||||
};
|
||||
|
||||
const BLOCK_TITLE: Record<string, string> = {
|
||||
equipment: '装备规则',
|
||||
target: '目标规则',
|
||||
position: '阵位规则',
|
||||
track: '航迹规则',
|
||||
};
|
||||
|
||||
const flatten = (nodes: RuleDecisionNode[] | null | undefined): RuleDecisionNode[] => {
|
||||
const out: RuleDecisionNode[] = [];
|
||||
const visit = (items: RuleDecisionNode[] | null | undefined) => {
|
||||
(items ?? []).forEach((item) => {
|
||||
out.push(item);
|
||||
visit(item.children ?? []);
|
||||
});
|
||||
};
|
||||
visit(nodes);
|
||||
return out;
|
||||
};
|
||||
|
||||
const scoreParamNode = (node: RuleDecisionNode) => {
|
||||
const text = `${node.title ?? ''} ${node.description ?? ''} ${node.valueText ?? ''}`.toLowerCase();
|
||||
let score = 0;
|
||||
const keywords = [
|
||||
'模式', '类型', '目标', '装备', '阵位', '航迹', '选择', '分配', '距离', '阈值', '权重',
|
||||
'比例', '数量', '规则', 'mode', 'type', 'target', 'equipment', 'position', 'track',
|
||||
'select', 'assign', 'distance', 'threshold', 'weight', 'ratio', 'count', 'limit', 'min', 'max',
|
||||
];
|
||||
keywords.forEach((keyword) => {
|
||||
if (text.includes(keyword)) {
|
||||
score += 2;
|
||||
}
|
||||
});
|
||||
if (text.includes('生效值')) {
|
||||
score += 1;
|
||||
}
|
||||
return score;
|
||||
};
|
||||
|
||||
const pickImportantParams = (flatNodes: RuleDecisionNode[]) => {
|
||||
return flatNodes
|
||||
.filter((node) => node.nodeType === 'input_param' || node.nodeType === 'param')
|
||||
.sort((a, b) => scoreParamNode(b) - scoreParamNode(a))
|
||||
.slice(0, 4);
|
||||
};
|
||||
|
||||
const pickCoreRules = (flatNodes: RuleDecisionNode[]) => {
|
||||
return flatNodes
|
||||
.filter((node) => node.nodeType === 'rule')
|
||||
.slice(0, 2);
|
||||
};
|
||||
|
||||
const pickOutputs = (flatNodes: RuleDecisionNode[]) => {
|
||||
const list = flatNodes.filter((node) => node.nodeType === 'output' || node.nodeType === 'outcome');
|
||||
return list.slice(0, 3);
|
||||
};
|
||||
|
||||
const buildMergedTree = (tree: RuleDecisionTreePayload) => {
|
||||
const nodes: GraphNode[] = [];
|
||||
const edges: Array<{ source: string; target: string }> = [];
|
||||
|
||||
const startId = 'simple:start';
|
||||
nodes.push({
|
||||
id: startId,
|
||||
label: '输入参数',
|
||||
nodeType: 'start',
|
||||
description: `汇总四类规则块共享的运行时参数(${Object.keys(tree.globalParamsPreview ?? {}).length}项)`,
|
||||
});
|
||||
|
||||
let previousMainId = startId;
|
||||
const blocks = [...(tree.blocks ?? [])];
|
||||
for (const block of blocks) {
|
||||
const mainId = `simple:block:${block.blockId}`;
|
||||
nodes.push({
|
||||
id: mainId,
|
||||
label: BLOCK_TITLE[block.blockId] ?? (block.title || block.blockId),
|
||||
nodeType: 'block',
|
||||
description: `salience=${block.salience ?? '-'};保留核心规则与关键参数`,
|
||||
});
|
||||
edges.push({ source: previousMainId, target: mainId });
|
||||
|
||||
const flatNodes = flatten(block.nodes);
|
||||
const importantParams = pickImportantParams(flatNodes);
|
||||
const coreRules = pickCoreRules(flatNodes);
|
||||
const outputs = pickOutputs(flatNodes);
|
||||
|
||||
const paramId = `simple:block:${block.blockId}:params`;
|
||||
nodes.push({
|
||||
id: paramId,
|
||||
label: '关键参数',
|
||||
nodeType: 'params',
|
||||
description: importantParams.length > 0
|
||||
? importantParams.map((item) => `${item.title}${item.valueText ? `:${item.valueText}` : ''}`).join(';')
|
||||
: '无关键参数',
|
||||
fullText: importantParams.length > 0
|
||||
? `关键参数:${importantParams.map((item) => `${item.title}${item.valueText ? `=${item.valueText}` : ''}`).join(';')}`
|
||||
: '关键参数:无',
|
||||
});
|
||||
edges.push({ source: mainId, target: paramId });
|
||||
|
||||
const ruleId = `simple:block:${block.blockId}:rules`;
|
||||
nodes.push({
|
||||
id: ruleId,
|
||||
label: '核心规则',
|
||||
nodeType: 'rules',
|
||||
description: coreRules.length > 0
|
||||
? coreRules.map((item) => item.title).join(';')
|
||||
: '无核心规则',
|
||||
fullText: coreRules.length > 0
|
||||
? `核心规则:${coreRules.map((item) => item.title).join(';')}`
|
||||
: '核心规则:无',
|
||||
});
|
||||
edges.push({ source: mainId, target: ruleId });
|
||||
|
||||
const outputId = `simple:block:${block.blockId}:outputs`;
|
||||
nodes.push({
|
||||
id: outputId,
|
||||
label: '阶段输出',
|
||||
nodeType: 'outputs',
|
||||
description: outputs.length > 0
|
||||
? outputs.map((item) => String(item.title || item.description || '')).join(';')
|
||||
: '无阶段输出',
|
||||
fullText: outputs.length > 0
|
||||
? `阶段输出:${outputs.map((item) => String(item.title || item.description || '')).join(';')}`
|
||||
: '阶段输出:无',
|
||||
});
|
||||
edges.push({ source: mainId, target: outputId });
|
||||
|
||||
previousMainId = mainId;
|
||||
}
|
||||
|
||||
nodes.push({
|
||||
id: 'simple:end',
|
||||
label: '输出 / 结束',
|
||||
nodeType: 'end',
|
||||
description: '四类规则块汇总后输出最终结果',
|
||||
fullText: '输出 / 结束:四类规则块汇总后输出最终结果',
|
||||
});
|
||||
edges.push({ source: previousMainId, target: 'simple:end' });
|
||||
|
||||
return { nodes, edges };
|
||||
};
|
||||
|
||||
const disposeGraph = () => {
|
||||
resizeObserver?.disconnect();
|
||||
resizeObserver = null;
|
||||
if (graph) {
|
||||
try {
|
||||
graph.destroy();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
graph = null;
|
||||
}
|
||||
hostRef.value?.replaceChildren();
|
||||
};
|
||||
|
||||
const renderGraph = async (tree: RuleDecisionTreePayload, version: number) => {
|
||||
const host = hostRef.value;
|
||||
if (!host) {
|
||||
return;
|
||||
}
|
||||
disposeGraph();
|
||||
if (version !== renderVersion.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
const data = buildMergedTree(tree);
|
||||
graph = new Graph({
|
||||
container: host,
|
||||
width: Math.max(host.clientWidth, 320),
|
||||
height: Math.max(host.clientHeight, 240),
|
||||
data: {
|
||||
nodes: data.nodes.map((node) => ({
|
||||
id: node.id,
|
||||
data: node,
|
||||
})),
|
||||
edges: data.edges,
|
||||
},
|
||||
layout: {
|
||||
type: 'antv-dagre',
|
||||
rankdir: 'LR',
|
||||
nodesep: 28,
|
||||
ranksep: 56,
|
||||
},
|
||||
node: {
|
||||
type: (model: { data?: { nodeType?: string } }) => {
|
||||
const t = model.data?.nodeType;
|
||||
if (t === 'start') return 'rect';
|
||||
if (t === 'end') return 'diamond';
|
||||
return 'circle';
|
||||
},
|
||||
style: {
|
||||
size: (model: { data?: { nodeType?: string } }) => {
|
||||
const t = model.data?.nodeType;
|
||||
if (t === 'start' || t === 'end') return 26;
|
||||
if (t === 'block') return 20;
|
||||
if (t === 'params' || t === 'rules' || t === 'outputs') return 16;
|
||||
return 16;
|
||||
},
|
||||
fill: (model: { data?: { nodeType?: string } }) => NODE_COLORS[model.data?.nodeType ?? 'block'] ?? '#5B8FF9',
|
||||
stroke: '#0d1f2c',
|
||||
lineWidth: 1.5,
|
||||
labelText: (model: { data?: { label?: string; description?: string; fullText?: string; nodeType?: string } }) => {
|
||||
const text = model.data?.fullText;
|
||||
if (text) {
|
||||
return text;
|
||||
}
|
||||
const label = model.data?.label ?? '';
|
||||
const description = model.data?.description;
|
||||
return description ? `${label}:${description}` : label;
|
||||
},
|
||||
labelFill: '#e8f4f8',
|
||||
labelFontSize: 11,
|
||||
labelLineHeight: 15,
|
||||
labelWordWrap: true,
|
||||
labelMaxWidth: 360,
|
||||
labelPlacement: (model: { data?: { nodeType?: string } }) => {
|
||||
const t = model.data?.nodeType;
|
||||
if (t === 'params' || t === 'rules' || t === 'outputs') {
|
||||
return 'right';
|
||||
}
|
||||
return 'bottom';
|
||||
},
|
||||
labelOffsetX: (model: { data?: { nodeType?: string } }) => {
|
||||
const t = model.data?.nodeType;
|
||||
if (t === 'params' || t === 'rules' || t === 'outputs') {
|
||||
return 14;
|
||||
}
|
||||
return 0;
|
||||
},
|
||||
labelTextAlign: (model: { data?: { nodeType?: string } }) => {
|
||||
const t = model.data?.nodeType;
|
||||
if (t === 'params' || t === 'rules' || t === 'outputs') {
|
||||
return 'left';
|
||||
}
|
||||
return 'center';
|
||||
},
|
||||
labelBackground: true,
|
||||
labelBackgroundFill: 'rgba(6, 21, 40, 0.88)',
|
||||
labelBackgroundRadius: 4,
|
||||
labelPadding: [6, 8],
|
||||
},
|
||||
},
|
||||
edge: {
|
||||
style: {
|
||||
stroke: 'rgba(120, 170, 200, 0.52)',
|
||||
lineWidth: 1.2,
|
||||
endArrow: true,
|
||||
},
|
||||
},
|
||||
behaviors: ['drag-canvas', 'zoom-canvas'],
|
||||
});
|
||||
|
||||
await graph.render();
|
||||
if (version !== renderVersion.value) {
|
||||
disposeGraph();
|
||||
return;
|
||||
}
|
||||
await graph.fitView({ when: 'always' });
|
||||
|
||||
resizeObserver = new ResizeObserver(() => {
|
||||
if (!graph || !hostRef.value) {
|
||||
return;
|
||||
}
|
||||
graph.setSize(Math.max(hostRef.value.clientWidth, 320), Math.max(hostRef.value.clientHeight, 240));
|
||||
void graph.fitView({ when: 'overflow' });
|
||||
});
|
||||
resizeObserver.observe(host);
|
||||
};
|
||||
|
||||
const load = async () => {
|
||||
errorMsg.value = null;
|
||||
emptyHint.value = null;
|
||||
payload.value = null;
|
||||
renderVersion.value += 1;
|
||||
disposeGraph();
|
||||
try {
|
||||
const r = await findRuleDecisionTree({
|
||||
pageNum: props.query.pageNum,
|
||||
pageSize: props.query.pageSize,
|
||||
ruleCode: props.query.ruleCode ?? undefined,
|
||||
ruleName: props.query.ruleName ?? undefined,
|
||||
levelCode: props.query.levelCode ?? undefined,
|
||||
kindCode: props.query.kindCode ?? undefined,
|
||||
moduleCode: props.query.moduleCode ?? undefined,
|
||||
enabled: props.query.enabled ?? undefined,
|
||||
});
|
||||
if (r.code !== 200 || !r.data) {
|
||||
errorMsg.value = r.msg ?? '加载简化决策树失败';
|
||||
return;
|
||||
}
|
||||
if (!r.data.blocks?.length) {
|
||||
emptyHint.value = '当前没有可展示的简化决策树数据';
|
||||
return;
|
||||
}
|
||||
payload.value = r.data;
|
||||
await nextTick();
|
||||
await renderGraph(r.data, renderVersion.value);
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
errorMsg.value = `简化决策树请求失败:${msg}`;
|
||||
message.error(errorMsg.value);
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [props.query.pageNum, props.query.pageSize, props.refreshKey],
|
||||
() => {
|
||||
void load();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
renderVersion.value += 1;
|
||||
disposeGraph();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.rule-decision-tree-simple {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.rule-decision-tree-simple__toolbar {
|
||||
flex: 0 0 auto;
|
||||
padding: 0 2px;
|
||||
}
|
||||
|
||||
.rule-decision-tree-simple__snapshot-btn {
|
||||
padding-left: 0;
|
||||
font-size: 11px;
|
||||
color: #8fafbd;
|
||||
}
|
||||
|
||||
.rule-decision-tree-simple__banner {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 12px;
|
||||
font-size: 13px;
|
||||
color: #a2b1ba;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.rule-decision-tree-simple__banner--error {
|
||||
color: #ff9c9c;
|
||||
}
|
||||
|
||||
.rule-decision-tree-simple__canvas {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
border: 1px solid rgba(80, 120, 150, 0.22);
|
||||
border-radius: 4px;
|
||||
background: rgba(4, 18, 28, 0.35);
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
.rule-decision-tree-simple-snapshot-popover {
|
||||
.ant-popover-inner-content {
|
||||
max-width: min(520px, 90vw);
|
||||
max-height: 70vh;
|
||||
overflow: auto;
|
||||
background: #081e3b;
|
||||
}
|
||||
|
||||
.ant-popover-inner {
|
||||
background: #081e3b;
|
||||
}
|
||||
}
|
||||
|
||||
.rule-decision-tree-simple__popover-json {
|
||||
margin: 0;
|
||||
font-size: 10px;
|
||||
line-height: 1.35;
|
||||
color: #c9dfe8;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
</style>
|
||||
294
modeler/src/views/decision/rule-config/RuleFourBlocksPanel.vue
Normal file
294
modeler/src/views/decision/rule-config/RuleFourBlocksPanel.vue
Normal file
@@ -0,0 +1,294 @@
|
||||
<!--
|
||||
- This file is part of the kernelstudio package.
|
||||
-
|
||||
- (c) 2014-2026 zlin <admin@kernelstudio.com>
|
||||
-
|
||||
- For the full copyright and license information, please view the LICENSE file
|
||||
- that was distributed with this source code.
|
||||
-->
|
||||
<template>
|
||||
<div class="rule-four-blocks">
|
||||
<div class="rule-four-blocks__toolbar">
|
||||
<a-popover placement="bottomLeft" trigger="click" overlay-class-name="rule-four-blocks-snapshot-popover">
|
||||
<template #content>
|
||||
<pre class="rule-four-blocks__popover-json">{{ previewJson }}</pre>
|
||||
</template>
|
||||
<a-button type="link" size="small" class="rule-four-blocks__snapshot-btn">
|
||||
全局参数快照({{ previewEntryCount }})
|
||||
</a-button>
|
||||
</a-popover>
|
||||
</div>
|
||||
<div v-if="errorMsg" class="rule-four-blocks__banner rule-four-blocks__banner--error">
|
||||
{{ errorMsg }}
|
||||
</div>
|
||||
<div v-else-if="emptyHint" class="rule-four-blocks__banner">
|
||||
{{ emptyHint }}
|
||||
</div>
|
||||
<div v-else-if="payload" class="rule-four-blocks__grid">
|
||||
<div
|
||||
v-for="block in payload.blocks"
|
||||
:key="block.blockId"
|
||||
class="rule-four-blocks__pane"
|
||||
:class="{ 'rule-four-blocks__pane--fullscreen': isPaneFullscreen(block.blockId) }"
|
||||
:ref="(el) => registerPaneRef(block.blockId, el)"
|
||||
>
|
||||
<div class="rule-four-blocks__pane-bar">
|
||||
<a-button
|
||||
type="link"
|
||||
size="small"
|
||||
class="rule-four-blocks__pane-fs-btn"
|
||||
:title="isPaneFullscreen(block.blockId) ? '退出本格全屏' : '本格全屏'"
|
||||
@click="togglePaneFullscreen(block.blockId)"
|
||||
>
|
||||
<template #icon>
|
||||
<FullscreenExitOutlined v-if="isPaneFullscreen(block.blockId)" />
|
||||
<FullscreenOutlined v-else />
|
||||
</template>
|
||||
</a-button>
|
||||
</div>
|
||||
<div class="rule-four-blocks__pane-body">
|
||||
<RuleBlockNeoGraph
|
||||
class="rule-four-blocks__cell"
|
||||
:payload="block.graph"
|
||||
:accent="blockColor(block.blockId)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons-vue';
|
||||
import { message } from 'ant-design-vue';
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { findRuleFourBlocksGraph } from './api';
|
||||
import RuleBlockNeoGraph from './RuleBlockNeoGraph.vue';
|
||||
import type { RuleFourBlocksPayload } from './types';
|
||||
|
||||
const props = defineProps<{
|
||||
refreshKey: number,
|
||||
}>();
|
||||
|
||||
const payload = ref<RuleFourBlocksPayload | null>(null);
|
||||
const errorMsg = ref<string | null>(null);
|
||||
const emptyHint = ref<string | null>(null);
|
||||
|
||||
const paneRefs = new Map<string, HTMLElement>();
|
||||
const paneFsTick = ref(0);
|
||||
|
||||
const BLOCK_COLORS: Record<string, string> = {
|
||||
equipment: '#5B8FF9',
|
||||
target: '#F6903D',
|
||||
position: '#61DDAA',
|
||||
track: '#9270CA',
|
||||
};
|
||||
|
||||
const blockColor = (blockId: string) => BLOCK_COLORS[blockId] ?? '#65789B';
|
||||
|
||||
const previewEntryCount = computed(() => {
|
||||
const p = payload.value?.globalParamsPreview;
|
||||
return p ? Object.keys(p).length : 0;
|
||||
});
|
||||
|
||||
const previewJson = computed(() => {
|
||||
const p = payload.value?.globalParamsPreview;
|
||||
if (!p) {
|
||||
return '';
|
||||
}
|
||||
try {
|
||||
return JSON.stringify(p, null, 2);
|
||||
} catch {
|
||||
return String(p);
|
||||
}
|
||||
});
|
||||
|
||||
const registerPaneRef = (blockId: string, el: unknown) => {
|
||||
if (el == null) {
|
||||
paneRefs.delete(blockId);
|
||||
return;
|
||||
}
|
||||
if (el instanceof HTMLElement) {
|
||||
paneRefs.set(blockId, el);
|
||||
}
|
||||
};
|
||||
|
||||
const isPaneFullscreen = (blockId: string) => {
|
||||
void paneFsTick.value;
|
||||
const node = paneRefs.get(blockId);
|
||||
return Boolean(node && document.fullscreenElement === node);
|
||||
};
|
||||
|
||||
const onDocumentFullscreenChange = () => {
|
||||
paneFsTick.value += 1;
|
||||
void nextTick(() => {
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
window.setTimeout(() => {
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
}, 120);
|
||||
});
|
||||
};
|
||||
|
||||
const togglePaneFullscreen = async (blockId: string) => {
|
||||
const el = paneRefs.get(blockId);
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (document.fullscreenElement === el) {
|
||||
await document.exitFullscreen();
|
||||
} else {
|
||||
await el.requestFullscreen();
|
||||
}
|
||||
} catch {
|
||||
message.warning('无法切换本格全屏,请重试或使用 Chrome / Edge');
|
||||
}
|
||||
};
|
||||
|
||||
const load = async () => {
|
||||
errorMsg.value = null;
|
||||
emptyHint.value = null;
|
||||
payload.value = null;
|
||||
try {
|
||||
const r = await findRuleFourBlocksGraph();
|
||||
if (r.code !== 200 || !r.data) {
|
||||
errorMsg.value = r.msg ?? '加载四块图谱失败';
|
||||
return;
|
||||
}
|
||||
const data = r.data;
|
||||
if (!data.blocks?.length) {
|
||||
emptyHint.value = '暂无四块图谱数据';
|
||||
return;
|
||||
}
|
||||
payload.value = data;
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
errorMsg.value = `四块图谱请求失败:${msg}`;
|
||||
message.error(errorMsg.value);
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.refreshKey,
|
||||
() => {
|
||||
void load();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('fullscreenchange', onDocumentFullscreenChange);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('fullscreenchange', onDocumentFullscreenChange);
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.rule-four-blocks {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.rule-four-blocks__toolbar {
|
||||
flex: 0 0 auto;
|
||||
padding: 0 2px;
|
||||
}
|
||||
|
||||
.rule-four-blocks__snapshot-btn {
|
||||
padding-left: 0;
|
||||
font-size: 11px;
|
||||
color: #8fafbd;
|
||||
}
|
||||
|
||||
.rule-four-blocks__banner {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 12px;
|
||||
font-size: 13px;
|
||||
color: #a2b1ba;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.rule-four-blocks__banner--error {
|
||||
color: #ff9c9c;
|
||||
}
|
||||
|
||||
.rule-four-blocks__grid {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
grid-template-rows: minmax(0, 1fr) minmax(0, 1fr);
|
||||
gap: 6px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.rule-four-blocks__pane {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: max(0px, calc(50vh - 56px));
|
||||
border-radius: 6px;
|
||||
border: 1px solid rgba(80, 120, 150, 0.25);
|
||||
background: rgba(8, 20, 30, 0.5);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.rule-four-blocks__pane--fullscreen {
|
||||
border-color: transparent;
|
||||
background: #0d1f2c;
|
||||
}
|
||||
|
||||
.rule-four-blocks__pane-bar {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
padding: 2px 4px 0;
|
||||
}
|
||||
|
||||
.rule-four-blocks__pane-fs-btn {
|
||||
color: #8fafbd;
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.rule-four-blocks__pane-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0 6px 6px;
|
||||
}
|
||||
|
||||
.rule-four-blocks__cell {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
.rule-four-blocks-snapshot-popover {
|
||||
.ant-popover-inner-content {
|
||||
max-width: min(520px, 90vw);
|
||||
max-height: 70vh;
|
||||
overflow: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.rule-four-blocks__popover-json {
|
||||
margin: 0;
|
||||
font-size: 10px;
|
||||
line-height: 1.35;
|
||||
color: #c9dfe8;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
</style>
|
||||
387
modeler/src/views/decision/rule-config/RuleKnowledgeGraph.vue
Normal file
387
modeler/src/views/decision/rule-config/RuleKnowledgeGraph.vue
Normal file
@@ -0,0 +1,387 @@
|
||||
<!--
|
||||
- This file is part of the kernelstudio package.
|
||||
-
|
||||
- (c) 2014-2026 zlin <admin@kernelstudio.com>
|
||||
-
|
||||
- For the full copyright and license information, please view the LICENSE file
|
||||
- that was distributed with this source code.
|
||||
-->
|
||||
<template>
|
||||
<div
|
||||
ref="graphShellRef"
|
||||
class="rule-knowledge-graph"
|
||||
:class="{
|
||||
'rule-knowledge-graph--four-blocks': density === 'four-blocks',
|
||||
'rule-knowledge-graph--decision-tree': density === 'decision-tree',
|
||||
'rule-knowledge-graph--fullscreen': isFullscreen,
|
||||
}"
|
||||
>
|
||||
<div class="rule-knowledge-graph__toolbar">
|
||||
<a-radio-group v-model:value="density" size="small" button-style="solid">
|
||||
<a-radio-button value="decision-tree-simple">决策树(简化)</a-radio-button>
|
||||
<a-radio-button value="decision-tree-binary">决策树(二叉树)</a-radio-button>
|
||||
<a-radio-button value="decision-tree">决策树</a-radio-button>
|
||||
<a-radio-button value="full">完整图谱</a-radio-button>
|
||||
<a-radio-button value="four-blocks">四块分区</a-radio-button>
|
||||
</a-radio-group>
|
||||
<span v-if="density === 'decision-tree-simple'" class="rule-knowledge-graph__hint">
|
||||
决策树(简化):把装备、目标、阵位、航迹四个规则块合并成一棵总树,只保留关键参数、核心规则和阶段输出
|
||||
</span>
|
||||
<span v-else-if="density === 'decision-tree-binary'" class="rule-knowledge-graph__hint">
|
||||
决策树(二叉树):按 if / else 方式展示关键参数条件判断、分支去向与最终输出
|
||||
</span>
|
||||
<span v-else-if="density === 'decision-tree'" class="rule-knowledge-graph__hint">
|
||||
决策树:按装备、目标、阵位、航迹四个规则块展示输入参数、运算步骤、命中规则与结果产出
|
||||
</span>
|
||||
<span v-else-if="density === 'full'" class="rule-knowledge-graph__hint">
|
||||
完整图谱包含参数、任务类型与执行顺序
|
||||
</span>
|
||||
<span v-else class="rule-knowledge-graph__hint rule-knowledge-graph__hint--compact">
|
||||
四块分区:可拖动画布,滚轮缩放
|
||||
</span>
|
||||
<a-button type="default" size="small" class="rule-knowledge-graph__fullscreen-btn" @click="toggleFullscreen">
|
||||
<template #icon>
|
||||
<FullscreenExitOutlined v-if="isFullscreen" />
|
||||
<FullscreenOutlined v-else />
|
||||
</template>
|
||||
{{ isFullscreen ? '退出全屏' : '全屏' }}
|
||||
</a-button>
|
||||
</div>
|
||||
<RuleDecisionTreeSimplePanel v-if="density === 'decision-tree-simple'" :query="query" :refresh-key="refreshKey" />
|
||||
<RuleDecisionBinaryTreePanel v-else-if="density === 'decision-tree-binary'" :query="query" :refresh-key="refreshKey" />
|
||||
<RuleDecisionTreePanel v-else-if="density === 'decision-tree'" :query="query" :refresh-key="refreshKey" />
|
||||
<RuleFourBlocksPanel v-else-if="density === 'four-blocks'" :refresh-key="refreshKey" />
|
||||
<template v-else>
|
||||
<div v-if="errorMsg" class="rule-knowledge-graph__banner rule-knowledge-graph__banner--error">
|
||||
{{ errorMsg }}
|
||||
</div>
|
||||
<div v-else-if="emptyHint" class="rule-knowledge-graph__banner">
|
||||
{{ emptyHint }}
|
||||
</div>
|
||||
<div v-show="!errorMsg && !emptyHint" ref="hostRef" class="rule-knowledge-graph__host" />
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons-vue';
|
||||
import { Graph } from '@antv/g6';
|
||||
import { message } from 'ant-design-vue';
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { findRuleConfigGraph } from './api';
|
||||
import RuleDecisionBinaryTreePanel from './RuleDecisionBinaryTreePanel.vue';
|
||||
import RuleDecisionTreeSimplePanel from './RuleDecisionTreeSimplePanel.vue';
|
||||
import RuleDecisionTreePanel from './RuleDecisionTreePanel.vue';
|
||||
import RuleFourBlocksPanel from './RuleFourBlocksPanel.vue';
|
||||
import type { RuleConfigRequest, RuleGraphPayload } from './types';
|
||||
|
||||
type RuleGraphDensityMode = 'decision-tree-simple' | 'decision-tree-binary' | 'decision-tree' | 'full' | 'four-blocks';
|
||||
|
||||
const emit = defineEmits<{
|
||||
densityChange: [RuleGraphDensityMode],
|
||||
}>();
|
||||
|
||||
const props = defineProps<{
|
||||
query: RuleConfigRequest,
|
||||
refreshKey: number,
|
||||
}>();
|
||||
|
||||
const graphShellRef = ref<HTMLElement | null>(null);
|
||||
const hostRef = ref<HTMLDivElement | null>(null);
|
||||
const isFullscreen = ref(false);
|
||||
const errorMsg = ref<string | null>(null);
|
||||
const emptyHint = ref<string | null>(null);
|
||||
const density = ref<RuleGraphDensityMode>('decision-tree-simple');
|
||||
const lastPayload = ref<RuleGraphPayload | null>(null);
|
||||
|
||||
let graph: Graph | null = null;
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
|
||||
const NODE_COLORS: Record<string, string> = {
|
||||
level: '#5B8FF9',
|
||||
kind: '#61DDAA',
|
||||
module: '#65789B',
|
||||
rule: '#F6903D',
|
||||
param: '#9270CA',
|
||||
taskType: '#269A99',
|
||||
};
|
||||
|
||||
const toGraphData = (payload: RuleGraphPayload) => ({
|
||||
nodes: payload.nodes.map((n) => ({
|
||||
id: n.id,
|
||||
data: {
|
||||
label: n.label,
|
||||
nodeType: n.nodeType,
|
||||
payload: n.payload ?? {},
|
||||
},
|
||||
})),
|
||||
edges: payload.edges.map((e) => ({
|
||||
id: e.id,
|
||||
source: e.source,
|
||||
target: e.target,
|
||||
data: {
|
||||
edgeType: e.edgeType ?? '',
|
||||
label: e.label ?? '',
|
||||
},
|
||||
})),
|
||||
});
|
||||
|
||||
const syncFullscreenState = () => {
|
||||
const el = graphShellRef.value;
|
||||
isFullscreen.value = Boolean(el && document.fullscreenElement === el);
|
||||
};
|
||||
|
||||
const refitMainGraphAfterLayout = () => {
|
||||
if (!graph || !hostRef.value) {
|
||||
return;
|
||||
}
|
||||
const w = Math.max(hostRef.value.clientWidth, 280);
|
||||
const h = Math.max(hostRef.value.clientHeight, 240);
|
||||
graph.setSize(w, h);
|
||||
void graph.fitView();
|
||||
};
|
||||
|
||||
const onFullscreenChange = () => {
|
||||
syncFullscreenState();
|
||||
void nextTick(() => {
|
||||
refitMainGraphAfterLayout();
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
window.setTimeout(() => {
|
||||
refitMainGraphAfterLayout();
|
||||
}, 120);
|
||||
});
|
||||
};
|
||||
|
||||
const toggleFullscreen = async () => {
|
||||
const el = graphShellRef.value;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (document.fullscreenElement === el) {
|
||||
await document.exitFullscreen();
|
||||
} else {
|
||||
await el.requestFullscreen();
|
||||
}
|
||||
} catch {
|
||||
message.warning('无法切换全屏,请检查浏览器权限或使用 Chrome / Edge');
|
||||
}
|
||||
};
|
||||
|
||||
const disposeGraph = async () => {
|
||||
resizeObserver?.disconnect();
|
||||
resizeObserver = null;
|
||||
if (graph) {
|
||||
try {
|
||||
graph.destroy();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
graph = null;
|
||||
}
|
||||
};
|
||||
|
||||
const buildGraph = async (payload: RuleGraphPayload) => {
|
||||
await disposeGraph();
|
||||
const el = hostRef.value;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
const data = toGraphData(payload);
|
||||
if (!payload.nodes.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const width = Math.max(el.clientWidth, 280);
|
||||
const height = Math.max(el.clientHeight, 240);
|
||||
|
||||
graph = new Graph({
|
||||
container: el,
|
||||
width,
|
||||
height,
|
||||
data,
|
||||
layout: {
|
||||
type: 'd3-force' as const,
|
||||
},
|
||||
node: {
|
||||
style: {
|
||||
size: (d: { data?: { nodeType?: string } }) => (d.data?.nodeType === 'param' ? 5 : 11),
|
||||
fill: (d: { data?: { nodeType?: string } }) => NODE_COLORS[d.data?.nodeType ?? ''] ?? '#8B8B8B',
|
||||
labelText: (d: { data?: { label?: string }; id: string }) => d.data?.label ?? String(d.id),
|
||||
labelFill: '#e8f4f8',
|
||||
labelFontSize: 9,
|
||||
labelMaxWidth: 100,
|
||||
labelWordWrap: true,
|
||||
lineWidth: 1.5,
|
||||
stroke: '#0d1f2c',
|
||||
},
|
||||
},
|
||||
edge: {
|
||||
style: {
|
||||
stroke: (d: { data?: { edgeType?: string } }) =>
|
||||
(d.data?.edgeType === 'rule_exec_before' ? '#faad14' : 'rgba(150, 175, 190, 0.35)'),
|
||||
lineWidth: (d: { data?: { edgeType?: string } }) =>
|
||||
(d.data?.edgeType === 'rule_exec_before' ? 2 : 1),
|
||||
endArrow: true,
|
||||
},
|
||||
},
|
||||
behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'],
|
||||
});
|
||||
await graph.render();
|
||||
await graph.fitView();
|
||||
resizeObserver = new ResizeObserver(() => {
|
||||
if (!graph || !hostRef.value) {
|
||||
return;
|
||||
}
|
||||
const w = Math.max(hostRef.value.clientWidth, 280);
|
||||
const h = Math.max(hostRef.value.clientHeight, 240);
|
||||
graph.setSize(w, h);
|
||||
void graph.fitView();
|
||||
});
|
||||
resizeObserver.observe(el);
|
||||
};
|
||||
|
||||
const renderFromCache = async () => {
|
||||
if (density.value !== 'full' || !lastPayload.value || !lastPayload.value.nodes?.length) {
|
||||
return;
|
||||
}
|
||||
await nextTick();
|
||||
await buildGraph(lastPayload.value);
|
||||
};
|
||||
|
||||
const load = async () => {
|
||||
errorMsg.value = null;
|
||||
emptyHint.value = null;
|
||||
await disposeGraph();
|
||||
try {
|
||||
const r = await findRuleConfigGraph({
|
||||
pageNum: props.query.pageNum,
|
||||
pageSize: props.query.pageSize,
|
||||
ruleCode: props.query.ruleCode ?? undefined,
|
||||
ruleName: props.query.ruleName ?? undefined,
|
||||
levelCode: props.query.levelCode ?? undefined,
|
||||
kindCode: props.query.kindCode ?? undefined,
|
||||
moduleCode: props.query.moduleCode ?? undefined,
|
||||
enabled: props.query.enabled ?? undefined,
|
||||
});
|
||||
if (r.code !== 200 || !r.data) {
|
||||
errorMsg.value = r.msg ?? '加载知识图谱失败';
|
||||
lastPayload.value = null;
|
||||
return;
|
||||
}
|
||||
if (!r.data.nodes?.length) {
|
||||
emptyHint.value = '当前页无规则数据,图谱为空';
|
||||
lastPayload.value = null;
|
||||
return;
|
||||
}
|
||||
lastPayload.value = r.data;
|
||||
await renderFromCache();
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
errorMsg.value = `图谱请求失败:${msg}`;
|
||||
lastPayload.value = null;
|
||||
message.error(errorMsg.value);
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [props.query.pageNum, props.query.pageSize, props.refreshKey],
|
||||
() => {
|
||||
if (density.value !== 'full') {
|
||||
return;
|
||||
}
|
||||
void load();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
watch(density, async (mode, prev) => {
|
||||
emit('densityChange', mode);
|
||||
if (mode !== 'full') {
|
||||
await disposeGraph();
|
||||
return;
|
||||
}
|
||||
if (prev !== 'full') {
|
||||
await load();
|
||||
return;
|
||||
}
|
||||
await renderFromCache();
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
syncFullscreenState();
|
||||
document.addEventListener('fullscreenchange', onFullscreenChange);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('fullscreenchange', onFullscreenChange);
|
||||
void disposeGraph();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="less">
|
||||
.rule-knowledge-graph {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.rule-knowledge-graph__toolbar {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 0 2px 4px;
|
||||
}
|
||||
|
||||
.rule-knowledge-graph__fullscreen-btn {
|
||||
margin-left: auto;
|
||||
flex-shrink: 0;
|
||||
color: #b8ccd6;
|
||||
border-color: rgba(120, 170, 200, 0.45);
|
||||
background: rgba(10, 28, 40, 0.65);
|
||||
}
|
||||
|
||||
.rule-knowledge-graph__hint {
|
||||
font-size: 11px;
|
||||
color: #7a8d96;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.rule-knowledge-graph__hint--compact {
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
|
||||
.rule-knowledge-graph__banner {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 12px;
|
||||
font-size: 13px;
|
||||
color: #a2b1ba;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.rule-knowledge-graph__banner--error {
|
||||
color: #ff9c9c;
|
||||
}
|
||||
|
||||
.rule-knowledge-graph__host {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
border: 1px solid rgba(80, 120, 150, 0.18);
|
||||
border-radius: 4px;
|
||||
background: rgba(4, 18, 28, 0.35);
|
||||
}
|
||||
|
||||
.rule-knowledge-graph--fullscreen {
|
||||
background: #061522;
|
||||
padding: 12px;
|
||||
}
|
||||
</style>
|
||||
@@ -7,9 +7,10 @@
|
||||
* that was distributed with this source code.
|
||||
*/
|
||||
|
||||
import { HttpRequestClient } from '@/utils/request';
|
||||
import { HttpRequestClient, originalAxios } from '@/utils/request';
|
||||
import type { ApiDataResponse, BasicResponse } from '@/types';
|
||||
import type { RuleConfig, RuleConfigPageableResponse, RuleConfigRequest, RuleDictItem, RuleParamMeta } from './types';
|
||||
import type { AxiosResponse } from 'axios';
|
||||
import type { RuleConfig, RuleConfigPageableResponse, RuleConfigRequest, RuleDecisionTreePayload, RuleDictItem, RuleFourBlocksPayload, RuleGraphPayload, RuleParamMeta } from './types';
|
||||
|
||||
const req = HttpRequestClient.create<BasicResponse>({
|
||||
baseURL: '/api',
|
||||
@@ -42,3 +43,36 @@ export const findRuleDictByType = (dictType: string): Promise<ApiDataResponse<Ru
|
||||
export const findRuleParamMeta = (): Promise<ApiDataResponse<RuleParamMeta[]>> => {
|
||||
return req.get('/system/rule/config/param-meta');
|
||||
};
|
||||
|
||||
export const findRuleConfigGraph = (query: Partial<RuleConfigRequest> = {}): Promise<ApiDataResponse<RuleGraphPayload>> => {
|
||||
return req.get('/system/rule/config/graph', query);
|
||||
};
|
||||
|
||||
export const findRuleFourBlocksGraph = (): Promise<ApiDataResponse<RuleFourBlocksPayload>> => {
|
||||
return req.get('/system/rule/config/graph/four-blocks');
|
||||
};
|
||||
|
||||
export const findRuleDecisionTree = (query: Partial<RuleConfigRequest> = {}): Promise<ApiDataResponse<RuleDecisionTreePayload>> => {
|
||||
return req.get('/system/rule/config/decision-tree', query);
|
||||
};
|
||||
|
||||
export const exportRuleConfig = (query: Partial<RuleConfigRequest> = {}): Promise<AxiosResponse<Blob>> => {
|
||||
return originalAxios.post('/api/system/rule/config/export', query, {
|
||||
responseType: 'blob',
|
||||
headers: {
|
||||
'Content-Type': 'application/json;charset=utf-8',
|
||||
'Accept': 'application/octet-stream',
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const importRuleConfig = (file: File, updateSupport: boolean = true): Promise<BasicResponse> => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('updateSupport', String(updateSupport));
|
||||
return originalAxios.post('/api/system/rule/config/importData', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
}).then((response) => response.data as BasicResponse);
|
||||
};
|
||||
|
||||
@@ -1,15 +1,36 @@
|
||||
<template>
|
||||
<Layout>
|
||||
<Layout sidebar-class="rule-config-sidebar">
|
||||
<template #sidebar>
|
||||
<div class="ks-sidebar-header">
|
||||
<a-flex class="ks-sidebar-title">
|
||||
<span class="icon"></span>
|
||||
<span class="text">规则聚合测试</span>
|
||||
</a-flex>
|
||||
<a-button class="ks-sidebar-add" size="small" @click="handleCreate">
|
||||
<PlusOutlined />
|
||||
新增
|
||||
</a-button>
|
||||
<a-space class="ks-sidebar-actions">
|
||||
<a-button class="ks-sidebar-add" size="small" @click="handleCreate">
|
||||
<PlusOutlined />
|
||||
新增
|
||||
</a-button>
|
||||
<a-tooltip title="导入 Excel">
|
||||
<a-button class="rule-config-sidebar-action" size="small" :loading="importLoading" @click="handleImportTrigger">
|
||||
<UploadOutlined />
|
||||
导入
|
||||
</a-button>
|
||||
</a-tooltip>
|
||||
<a-tooltip title="导出 Excel">
|
||||
<a-button class="rule-config-sidebar-action" size="small" :loading="exportLoading" @click="handleExport">
|
||||
<DownloadOutlined />
|
||||
导出
|
||||
</a-button>
|
||||
</a-tooltip>
|
||||
</a-space>
|
||||
<input
|
||||
ref="importInputRef"
|
||||
type="file"
|
||||
accept=".xls,.xlsx"
|
||||
style="display: none;"
|
||||
@change="handleImportChange"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<a-tree
|
||||
@@ -39,9 +60,49 @@
|
||||
</a-space>
|
||||
</template>
|
||||
|
||||
<div class="ks-scrollable" style="height: 80.5vh;overflow-y: auto;padding-right: 10px">
|
||||
<a-row :gutter="15">
|
||||
<a-col :span="16">
|
||||
<div
|
||||
ref="splitRootRef"
|
||||
class="ks-scrollable rule-config-main-split"
|
||||
style="height: 80.5vh;"
|
||||
>
|
||||
<div
|
||||
class="rule-config-graph-placeholder rule-config-graph-placeholder--chart"
|
||||
:style="{
|
||||
flex: `0 0 ${graphPanePercent}%`,
|
||||
minWidth: '140px',
|
||||
maxWidth: '78%',
|
||||
}"
|
||||
>
|
||||
<RuleKnowledgeGraph :query="query" :refresh-key="graphRevision" @density-change="onRuleGraphDensityChange" />
|
||||
</div>
|
||||
<div
|
||||
class="rule-config-main-split-resizer"
|
||||
title="拖动调节图谱与参数区占比"
|
||||
@mousedown="onGraphSplitMouseDown"
|
||||
/>
|
||||
<div class="rule-config-right-cluster">
|
||||
<button
|
||||
type="button"
|
||||
class="rule-config-panel-toggle"
|
||||
:title="rightPanelExpanded ? '收起参数面板' : '展开参数面板'"
|
||||
@click="rightPanelExpanded = !rightPanelExpanded"
|
||||
>
|
||||
<LeftOutlined v-if="rightPanelExpanded" />
|
||||
<RightOutlined v-else />
|
||||
</button>
|
||||
<div
|
||||
class="rule-config-right-panel"
|
||||
:class="{ 'rule-config-right-panel--collapsed': !rightPanelExpanded }"
|
||||
:style="rightPanelExpanded ? { flexBasis: `${rightPanelWidth}px`, width: `${rightPanelWidth}px` } : undefined"
|
||||
>
|
||||
<button
|
||||
v-if="rightPanelExpanded"
|
||||
type="button"
|
||||
class="rule-config-right-panel-edge"
|
||||
title="左右拖动调整参数配置区域宽度"
|
||||
@mousedown="onRightPanelResizeMouseDown"
|
||||
/>
|
||||
<div class="rule-config-right-panel__inner">
|
||||
<a-form
|
||||
ref="formRef"
|
||||
:label-col="{ span: 6 }"
|
||||
@@ -64,6 +125,22 @@
|
||||
>
|
||||
<a-form-item-rest>
|
||||
<div class="ks-sidebar-list-param-list">
|
||||
<div class="ks-sidebar-list-param-head">
|
||||
<a-row :gutter="10">
|
||||
<a-col :span="6">
|
||||
<div class="ks-sidebar-list-param-head-cell">参数作用</div>
|
||||
</a-col>
|
||||
<a-col :span="6">
|
||||
<div class="ks-sidebar-list-param-head-cell">参数键</div>
|
||||
</a-col>
|
||||
<a-col :span="9">
|
||||
<div class="ks-sidebar-list-param-head-cell">参数值</div>
|
||||
</a-col>
|
||||
<a-col :span="3">
|
||||
<div class="ks-sidebar-list-param-head-cell ks-sidebar-list-param-head-cell--actions">操作</div>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</div>
|
||||
<div class="ks-sidebar-list-param-item" v-for="(item,index) in selectedRuleConfig.params" :key="`param-${index}`">
|
||||
<a-row :gutter="10">
|
||||
<a-col :span="6">
|
||||
@@ -138,8 +215,9 @@
|
||||
</a-space>
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</a-card>
|
||||
</div>
|
||||
@@ -149,9 +227,10 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onMounted, ref } from 'vue';
|
||||
import { type FormInstance, message } from 'ant-design-vue';
|
||||
import { MinusCircleOutlined, PlusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
|
||||
import { DownloadOutlined, LeftOutlined, MinusCircleOutlined, PlusCircleOutlined, PlusOutlined, RightOutlined, UploadOutlined } from '@ant-design/icons-vue';
|
||||
import Layout from '../layout.vue';
|
||||
import { createRuleConfig, deleteRuleConfig, findRuleConfigByCode, findRuleConfigByQuery, findRuleParamMeta, updateRuleConfig } from './api';
|
||||
import RuleKnowledgeGraph from './RuleKnowledgeGraph.vue';
|
||||
import { createRuleConfig, deleteRuleConfig, exportRuleConfig, findRuleConfigByCode, findRuleConfigByQuery, findRuleParamMeta, importRuleConfig, updateRuleConfig } from './api';
|
||||
import type { RuleConfig, RuleConfigParam, RuleConfigRequest, RuleParamMeta } from './types';
|
||||
|
||||
const query = ref<RuleConfigRequest>({
|
||||
@@ -191,6 +270,9 @@ const datasource = ref<RuleConfig[]>([]);
|
||||
const datasourceTotal = ref<number>(0);
|
||||
const selectedRuleConfig = ref<RuleConfig>(JSON.parse(JSON.stringify(defaultRuleConfig)));
|
||||
const formRef = ref<FormInstance | null>(null);
|
||||
const importInputRef = ref<HTMLInputElement | null>(null);
|
||||
const importLoading = ref(false);
|
||||
const exportLoading = ref(false);
|
||||
const treeData = ref<any[]>([]);
|
||||
const selectedTreeKeys = ref<string[]>([]);
|
||||
const expandedTreeKeys = ref<string[]>([]);
|
||||
@@ -207,10 +289,92 @@ const paramMetaOptions = ref<{ label: string; value: string }[]>([]);
|
||||
|
||||
const levelOptions = [
|
||||
{ code: 'task', name: '任务级' },
|
||||
{ code: 'platform', name: '平台级' },
|
||||
{ code: 'action', name: '行动级' },
|
||||
{ code: 'platform', name: '平台级' },
|
||||
];
|
||||
|
||||
const rightPanelExpanded = ref(true);
|
||||
|
||||
const GRAPH_PANE_STORAGE_KEY = 'rule-config-graph-pane-percent';
|
||||
const GRAPH_PANE_MIN = 18;
|
||||
const GRAPH_PANE_MAX = 70;
|
||||
const RIGHT_PANEL_WIDTH_STORAGE_KEY = 'rule-config-right-panel-width';
|
||||
const RIGHT_PANEL_MIN = 360;
|
||||
const RIGHT_PANEL_MAX = 960;
|
||||
const graphPanePercent = ref(32);
|
||||
const graphPanePercentBeforeFourBlocks = ref<number | null>(null);
|
||||
const splitRootRef = ref<HTMLElement | null>(null);
|
||||
const graphRevision = ref(0);
|
||||
const rightPanelWidth = ref(480);
|
||||
|
||||
const clampGraphPercent = (n: number) =>
|
||||
Math.min(GRAPH_PANE_MAX, Math.max(GRAPH_PANE_MIN, Math.round(n)));
|
||||
|
||||
const clampRightPanelWidth = (n: number) => {
|
||||
const rootWidth = splitRootRef.value?.getBoundingClientRect().width ?? window.innerWidth;
|
||||
const dynamicMax = Math.min(RIGHT_PANEL_MAX, Math.max(420, Math.floor(rootWidth * 0.72)));
|
||||
return Math.min(dynamicMax, Math.max(RIGHT_PANEL_MIN, Math.round(n)));
|
||||
};
|
||||
|
||||
const onRuleGraphDensityChange = (mode: 'decision-tree-simple' | 'decision-tree-binary' | 'decision-tree' | 'full' | 'four-blocks') => {
|
||||
if (mode === 'four-blocks') {
|
||||
if (graphPanePercentBeforeFourBlocks.value === null) {
|
||||
graphPanePercentBeforeFourBlocks.value = graphPanePercent.value;
|
||||
}
|
||||
graphPanePercent.value = clampGraphPercent(62);
|
||||
return;
|
||||
}
|
||||
if (graphPanePercentBeforeFourBlocks.value !== null) {
|
||||
graphPanePercent.value = clampGraphPercent(graphPanePercentBeforeFourBlocks.value);
|
||||
graphPanePercentBeforeFourBlocks.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
const onGraphSplitMouseDown = (e: MouseEvent) => {
|
||||
e.preventDefault();
|
||||
const root = splitRootRef.value;
|
||||
if (!root) return;
|
||||
const rect = root.getBoundingClientRect();
|
||||
const onMove = (ev: MouseEvent) => {
|
||||
const x = ev.clientX - rect.left;
|
||||
const p = (x / rect.width) * 100;
|
||||
graphPanePercent.value = clampGraphPercent(p);
|
||||
};
|
||||
const onUp = () => {
|
||||
window.removeEventListener('mousemove', onMove);
|
||||
window.removeEventListener('mouseup', onUp);
|
||||
document.body.style.removeProperty('cursor');
|
||||
document.body.style.removeProperty('user-select');
|
||||
sessionStorage.setItem(GRAPH_PANE_STORAGE_KEY, String(graphPanePercent.value));
|
||||
};
|
||||
document.body.style.cursor = 'col-resize';
|
||||
document.body.style.userSelect = 'none';
|
||||
window.addEventListener('mousemove', onMove);
|
||||
window.addEventListener('mouseup', onUp);
|
||||
};
|
||||
|
||||
const onRightPanelResizeMouseDown = (e: MouseEvent) => {
|
||||
e.preventDefault();
|
||||
const root = splitRootRef.value;
|
||||
if (!root) return;
|
||||
const rect = root.getBoundingClientRect();
|
||||
const onMove = (ev: MouseEvent) => {
|
||||
const width = rect.right - ev.clientX;
|
||||
rightPanelWidth.value = clampRightPanelWidth(width);
|
||||
};
|
||||
const onUp = () => {
|
||||
window.removeEventListener('mousemove', onMove);
|
||||
window.removeEventListener('mouseup', onUp);
|
||||
document.body.style.removeProperty('cursor');
|
||||
document.body.style.removeProperty('user-select');
|
||||
sessionStorage.setItem(RIGHT_PANEL_WIDTH_STORAGE_KEY, String(rightPanelWidth.value));
|
||||
};
|
||||
document.body.style.cursor = 'col-resize';
|
||||
document.body.style.userSelect = 'none';
|
||||
window.addEventListener('mousemove', onMove);
|
||||
window.addEventListener('mouseup', onUp);
|
||||
};
|
||||
|
||||
const kindOptions = [
|
||||
{ code: 'select', name: '选择' },
|
||||
{ code: 'assign', name: '分配' },
|
||||
@@ -233,12 +397,14 @@ const buildTreeData = () => {
|
||||
const params = detail?.params?.filter((item) => item.paramKey) ?? [];
|
||||
if (params.length === 0) return;
|
||||
|
||||
group[levelCode] = group[levelCode] ?? {};
|
||||
group[levelCode][kindCode] = group[levelCode][kindCode] ?? [];
|
||||
const levelEntry = group[levelCode] ?? {};
|
||||
group[levelCode] = levelEntry;
|
||||
const kindList = levelEntry[kindCode] ?? [];
|
||||
levelEntry[kindCode] = kindList;
|
||||
|
||||
params.forEach((param, index) => {
|
||||
const paramTitle = param.paramName || param.paramKey || `参数${index + 1}`;
|
||||
group[levelCode][kindCode].push({
|
||||
kindList.push({
|
||||
title: paramTitle,
|
||||
key: `param:${rule.ruleCode}:${param.paramKey || index}`,
|
||||
isLeaf: true,
|
||||
@@ -302,6 +468,7 @@ const load = async () => {
|
||||
}),
|
||||
);
|
||||
buildTreeData();
|
||||
graphRevision.value += 1;
|
||||
};
|
||||
|
||||
const loadParamMeta = async () => {
|
||||
@@ -476,8 +643,9 @@ const handleChange = async (page: number, pageSize: number) => {
|
||||
|
||||
const handleAddParam = () => {
|
||||
const row = defaultParam();
|
||||
if (paramMetaOptions.value.length > 0) {
|
||||
row.paramKey = paramMetaOptions.value[0].value;
|
||||
const firstOpt = paramMetaOptions.value[0];
|
||||
if (firstOpt) {
|
||||
row.paramKey = firstOpt.value;
|
||||
handleParamKeyChange(row);
|
||||
}
|
||||
selectedRuleConfig.value.params.push(row);
|
||||
@@ -493,7 +661,94 @@ const handleMinusParam = (index: number) => {
|
||||
selectedRuleConfig.value.params = params;
|
||||
};
|
||||
|
||||
|
||||
const extractFilename = (contentDisposition?: string) => {
|
||||
if (!contentDisposition) {
|
||||
return 'rule-config.xlsx';
|
||||
}
|
||||
const match = /filename\*=UTF-8''([^;]+)|filename="?([^";]+)"?/i.exec(contentDisposition);
|
||||
const raw = match?.[1] ?? match?.[2] ?? 'rule-config.xlsx';
|
||||
try {
|
||||
return decodeURIComponent(raw.replace(/\+/g, '%20'));
|
||||
} catch {
|
||||
return raw;
|
||||
}
|
||||
};
|
||||
|
||||
const downloadBlob = (blob: Blob, filename: string) => {
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = url;
|
||||
anchor.download = filename;
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
anchor.remove();
|
||||
window.URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const handleExport = async () => {
|
||||
exportLoading.value = true;
|
||||
try {
|
||||
const response = await exportRuleConfig(query.value as Partial<RuleConfigRequest>);
|
||||
const filename = extractFilename(response.headers['content-disposition']);
|
||||
downloadBlob(response.data, filename);
|
||||
message.success('导出成功');
|
||||
} catch (err: any) {
|
||||
message.error(err?.message ?? '导出失败');
|
||||
} finally {
|
||||
exportLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportTrigger = () => {
|
||||
if (importInputRef.value) {
|
||||
importInputRef.value.value = '';
|
||||
importInputRef.value.click();
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportChange = async (event: Event) => {
|
||||
const input = event.target as HTMLInputElement | null;
|
||||
const file = input?.files?.[0];
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
if (!/\.(xls|xlsx)$/i.test(file.name)) {
|
||||
message.error('请选择 Excel 文件');
|
||||
if (input) {
|
||||
input.value = '';
|
||||
}
|
||||
return;
|
||||
}
|
||||
importLoading.value = true;
|
||||
try {
|
||||
const response = await importRuleConfig(file, true);
|
||||
await load();
|
||||
message.success(response.msg ?? '导入成功');
|
||||
} catch (err: any) {
|
||||
message.error(err?.message ?? '导入失败');
|
||||
} finally {
|
||||
importLoading.value = false;
|
||||
if (input) {
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
};
|
||||
onMounted(() => {
|
||||
const raw = sessionStorage.getItem(GRAPH_PANE_STORAGE_KEY);
|
||||
if (raw) {
|
||||
const v = Number(raw);
|
||||
if (!Number.isNaN(v)) {
|
||||
graphPanePercent.value = clampGraphPercent(v);
|
||||
}
|
||||
}
|
||||
const rightPanelRaw = sessionStorage.getItem(RIGHT_PANEL_WIDTH_STORAGE_KEY);
|
||||
if (rightPanelRaw) {
|
||||
const width = Number(rightPanelRaw);
|
||||
if (!Number.isNaN(width)) {
|
||||
rightPanelWidth.value = clampRightPanelWidth(width);
|
||||
}
|
||||
}
|
||||
loadParamMeta().then(() => load());
|
||||
});
|
||||
|
||||
@@ -517,7 +772,10 @@ const handleParamKeyChange = (item: RuleConfigParam) => {
|
||||
item.valType = 'string';
|
||||
if (meta.valueType === 'enum' && Array.isArray(meta.enumOptions) && meta.enumOptions.length > 0) {
|
||||
if (!meta.enumOptions.includes(String(item.paramVal ?? ''))) {
|
||||
item.paramVal = meta.enumOptions[0];
|
||||
const first = meta.enumOptions[0];
|
||||
if (first !== undefined) {
|
||||
item.paramVal = first;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -86,3 +86,75 @@ export interface RuleConfigRequest extends Partial<RuleConfig> {
|
||||
}
|
||||
|
||||
export interface RuleConfigPageableResponse extends PageableResponse<RuleConfig> {}
|
||||
|
||||
export interface RuleGraphNode {
|
||||
id: string,
|
||||
label: string,
|
||||
nodeType: string,
|
||||
payload?: Record<string, unknown> | null,
|
||||
}
|
||||
|
||||
export interface RuleGraphEdge {
|
||||
id: string,
|
||||
source: string,
|
||||
target: string,
|
||||
edgeType?: string | null,
|
||||
label?: string | null,
|
||||
}
|
||||
|
||||
export interface RuleGraphPayload {
|
||||
nodes: RuleGraphNode[],
|
||||
edges: RuleGraphEdge[],
|
||||
layoutHint?: string | null,
|
||||
focusNodeId?: string | null,
|
||||
}
|
||||
|
||||
export interface RuleFourBlockParamRow {
|
||||
ruleCode: NullableString,
|
||||
ruleName: NullableString,
|
||||
paramKey: NullableString,
|
||||
paramName: NullableString,
|
||||
whenText: NullableString,
|
||||
thenText: NullableString,
|
||||
outputText: NullableString,
|
||||
}
|
||||
|
||||
export interface RuleFourBlockCluster {
|
||||
blockId: string,
|
||||
moduleCode: NullableString,
|
||||
title: NullableString,
|
||||
droolsRuleName: NullableString,
|
||||
salience: number | null,
|
||||
whenExpr: NullableString,
|
||||
thenAction: NullableString,
|
||||
graph: RuleGraphPayload,
|
||||
paramRows?: RuleFourBlockParamRow[] | null,
|
||||
}
|
||||
|
||||
export interface RuleFourBlocksPayload {
|
||||
globalParamsPreview: Record<string, unknown>,
|
||||
blocks: RuleFourBlockCluster[],
|
||||
}
|
||||
|
||||
export interface RuleDecisionNode {
|
||||
key: string,
|
||||
title: string,
|
||||
nodeType: string,
|
||||
description?: string | null,
|
||||
valueText?: string | null,
|
||||
children?: RuleDecisionNode[] | null,
|
||||
}
|
||||
|
||||
export interface RuleDecisionBlock {
|
||||
blockId: string,
|
||||
moduleCode: NullableString,
|
||||
title: NullableString,
|
||||
droolsRuleName: NullableString,
|
||||
salience: number | null,
|
||||
nodes: RuleDecisionNode[],
|
||||
}
|
||||
|
||||
export interface RuleDecisionTreePayload {
|
||||
globalParamsPreview: Record<string, unknown>,
|
||||
blocks: RuleDecisionBlock[],
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ export interface PlatformComponent {
|
||||
|
||||
export interface PlatformWithComponents extends Platform {
|
||||
components: PlatformComponent[],
|
||||
behaviortreeId?: number | null,
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user