CMVR-IOT-UI/src/views/flow/components/params/Device_universal.vue
lixiaolong 65d219062e feat(flow): 优化设备执行流程配置功能
- 将设备ID参数从输入框改为选择框,并设置为必填项
- 添加设备绑定工具栏显示执行设备选择信息
- 集成机器人设备选择对话框功能
- 实现机器人列表加载和设备选项动态获取
- 添加设备选择表单验证和确认逻辑
- 支持自动选择唯一在线设备并锁定
- 优化键盘事件处理,区分编辑状态和流程操作
- 添加相关的API接口调用和工具函数
- 增加相应的样式定义和用户提示信息
2026-08-05 10:15:34 +08:00

616 lines
19 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<el-collapse v-model="activeNames">
<el-collapse v-model="activeNames">
<el-collapse-item name="1" icon-position="left">
<template #title>
输入参数
<el-tooltip
class="box-item"
effect="dark"
content="这里输入的变量可以被下方的代码引用。"
placement="top"
>
<el-icon class="header-icon" style="margin-left: 6px">
<info-filled />
</el-icon>
</el-tooltip>
</template>
<div class="form__container">
<div class="device-binding-toolbar">
<div>
<div class="device-binding-toolbar__title">执行设备</div>
<div class="device-binding-toolbar__desc">从机器人当前上报的全部在线设备中选择</div>
</div>
<el-button type="primary" plain size="small" @click="openDeviceDialog">
选择机器人设备
</el-button>
</div>
<el-form
:inline="true"
:model="formData"
:rules="rules"
ref="dynamicFormRef"
label-position="top"
label-width="auto"
>
<div v-for="(property, index) in formData.nodeParams" :key="index">
<el-row v-if="property.name !== 'requestJson'">
<el-form-item
:label="index === 0 ? '参数名' : ''"
:prop="`nodeParams.${index}.name`"
:rules="[
{ required: true, message: '请输入参数名', trigger: 'blur' },
]"
>
<el-input
:disabled="property?.disabled || false"
class="param-name"
v-model="property.name"
placeholder="请输入"
clearable
/>
</el-form-item>
<el-form-item
:label="index === 0 ? '参数值' : ''"
:prop="`nodeParams.${index}.type`"
>
<el-select
v-model="property.type"
class="param-type"
@change="handleTypeChange(index)"
>
<el-option label="引用" value="quote" />
<el-option label="输入" value="input" />
</el-select>
<el-form-item
v-if="property.type === 'input'"
:rules="[
{
required: property?.required ?? true,
message: '请输入参数值',
trigger: 'blur',
},
]"
:prop="`nodeParams.${index}.input`"
>
<el-input-number
class="param-value"
v-if="property.componentType === 'number'"
v-model="property.input"
:min="0"
:max="property.max || Infinity"
:controls="false"
:step-strictly="true"
placeholder="请输入"
clearable
/>
<el-select
v-model="property.input"
class="param-value"
v-else-if="property.componentType === 'select'"
:disabled="property.deviceLocked"
no-data-text="请先选择机器人设备"
>
<el-option
v-for="item in property.selectOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
<el-input
class="param-value"
v-else
v-model="property.input"
placeholder="请输入"
clearable
/>
</el-form-item>
<el-form-item
v-if="property.type === 'quote'"
:rules="[
{
required: true,
message: '请选择参数值',
trigger: 'blur',
},
]"
:prop="`nodeParams.${index}.quote`"
>
<el-cascader
:ref="
(el) => {
if (el) cascaderRefs[index] = el;
}
"
v-model="property.quote"
:checkStrictly="true"
:options="quoteOptions"
placeholder="请选择"
@visible-change="
(visible) => visibleChange(visible, index, property.quote)
"
@change="(value) => cascaderChange(value, index, formData, 'nodeParams')"
/>
</el-form-item>
</el-form-item>
<el-button
:icon="Minus"
circle
size="small"
@click="handleDelete(index)"
:disabled="property?.disabled || false"
class="deleteBtn"
/>
</el-row>
</div>
</el-form>
</div>
</el-collapse-item>
<el-collapse-item title="JSON" name="2" icon-position="left">
<div class="code__container">
<div ref="codeRef" style="width: 100%; height: 100%"></div>
</div>
</el-collapse-item>
<el-collapse-item name="3" icon-position="left">
<template #title>
输出参数
<el-tooltip
class="box-item"
effect="dark"
content="这里定义的输出变量可以被后续节点引用。"
placement="top"
>
<el-icon class="header-icon" style="margin-left: 6px">
<info-filled />
</el-icon>
</el-tooltip>
<el-button
:circle="true"
size="small"
@click="(e) => addFormItem(e, 'outputParams')"
class="addFormItem"
>
<el-icon :size="14"><Plus /></el-icon>
</el-button>
</template>
<div class="form__container">
<el-form
:inline="true"
:model="formData"
label-position="top"
label-width="auto"
:rules="outputRules"
ref="outputFormRef"
>
<FormItemRecursive
formType="output"
:current-list="formData.outputParams"
prop-path="outputParams"
:depth="0"
:is-first-level="true"
:endDepth="2"
:parent-path="[]"
@delete-item="(path) => deleteTopLevelItem(path, 'outputParams')"
/>
</el-form>
</div>
</el-collapse-item>
</el-collapse>
</el-collapse>
<el-dialog v-model="deviceDialogVisible" title="选择通用指令执行设备" width="520" append-to-body>
<div class="device-dialog-tip">通用指令不限制设备类型,设备列表来自机器人最近一次 QUIC 在线上报。</div>
<el-form ref="deviceFormRef" :model="deviceForm" :rules="deviceFormRules" label-width="86px">
<el-form-item label="机器人" prop="robotId">
<el-select
v-model="deviceForm.robotId"
filterable
:loading="robotLoading"
placeholder="请选择在线机器人"
style="width: 100%"
@change="loadRobotDevices"
>
<el-option v-for="item in robotOptions" :key="item.value" :label="item.label" :value="item.value" />
</el-select>
</el-form-item>
<el-form-item label="执行设备" prop="deviceId">
<el-select
v-model="deviceForm.deviceId"
filterable
:loading="deviceLoading"
:disabled="!deviceForm.robotId || deviceOptions.length === 1"
placeholder="请选择该机器人上的设备"
style="width: 100%"
>
<el-option v-for="item in deviceOptions" :key="item.value" :label="item.label" :value="item.value" />
</el-select>
<div v-if="deviceOptions.length === 1" class="device-auto-hint">仅有一个在线设备,已自动选择并锁定</div>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="deviceDialogVisible = false">取消</el-button>
<el-button type="primary" @click="confirmDevice">确定</el-button>
</template>
</el-dialog>
</template>
<script setup>
import { ref, reactive, watch, nextTick, onBeforeUnmount, onMounted } from 'vue'
import { Plus, Minus } from '@element-plus/icons-vue'
import FormItemRecursive from '../FormItemRecursive.vue'
import * as monaco from 'monaco-editor';
import { getInput } from '@/utils/flow'
import { useQuote } from './useQuote.js'
import { getRobotList, getRobotDevicesByRobotId } from '@/api/inspection/robot'
import { toDeviceOptions } from '@/utils/robotDevice'
import { ElMessage } from 'element-plus'
const props = defineProps({
data: Object
})
const emit = defineEmits(['save-success', 'save-error'])
const formData = reactive({
nodeParams: [],
outputParams: []
})
const codeRef = ref()
let editorInstance
function hasErrors() {
const model = editorInstance.getModel();
if (!model) return false;
// 获取当前模型的所有标记
const markers = monaco.editor.getModelMarkers({ resource: model.uri });
// 检查是否存在错误级别标记
return markers.some(marker => marker.severity === monaco.MarkerSeverity.Error);
}
const initEditor = (type) => {
monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
target: monaco.languages.typescript.ScriptTarget.ES2020,
allowNonTsExtensions: true, // 允许非 ts 扩展名(.js)
checkJs: true, // 对 .js 文件进行类型检查
strict: true, // 启用所有严格检查
noImplicitAny: false, // 禁止隐式 any
noUnusedLocals: true, // 未使用的局部变量报错(可选)
noUnusedParameters: true, // 未使用的参数报错(可选)
});
// 确保语义验证开启(默认就是开启的,但可以显式设置)
monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
noSemanticValidation: false, // 开启语义检查
noSyntaxValidation: false, // 开启语法检查
});
editorInstance = monaco.editor.create(codeRef.value, {
value: ['{}'].join('\n'),
language: type === 'code' ? 'javascript' : 'json',
fontSize: 14,
lineNumbers: 'on',
roundedSelection: true,
scrollBeyondLastLine: false,
formatOnPaste: true,
formatOnType: true,
quickSuggestions: true,
suggestOnTriggerCharacters: true,
// 自动完成
suggest: {
showWords: true,
showFunctions: true,
showVariables: true,
showClasses: true,
showModules: true,
},
});
}
// 设置代码值
const setValue = (value) => {
if (editorInstance) {
editorInstance.setValue(value)
}
}
// 销毁编辑器
const disposeEditor = () => {
if (editorInstance) {
editorInstance.dispose()
editorInstance = null
}
}
const rules = reactive({})
const outputRules = reactive({})
const dynamicFormRef = ref()
const outputFormRef = ref()
const activeNames = ref(['1', '2'])
const deviceDialogVisible = ref(false)
const deviceFormRef = ref()
const robotLoading = ref(false)
const deviceLoading = ref(false)
const robotOptions = ref([])
const deviceOptions = ref([])
const deviceForm = reactive({ robotId: '', deviceId: '' })
const deviceFormRules = {
robotId: [{ required: true, message: '请选择机器人', trigger: 'change' }],
deviceId: [{ required: true, message: '请选择执行设备', trigger: 'change' }]
}
const loadRobotOptions = async () => {
robotLoading.value = true
try {
const response = await getRobotList({ pageNum: 1, pageSize: 1000, connectStatus: '1' })
robotOptions.value = (response.rows || []).map(robot => ({
value: robot.robotId,
label: `${robot.robotName || robot.robotId} (${robot.robotId})`
}))
} finally {
robotLoading.value = false
}
}
const loadRobotDevices = async (robotId) => {
deviceForm.deviceId = ''
deviceOptions.value = []
if (!robotId) return
deviceLoading.value = true
try {
const response = await getRobotDevicesByRobotId(robotId)
const devices = Array.isArray(response.data) ? response.data : []
deviceOptions.value = toDeviceOptions(devices)
if (devices.length) deviceForm.deviceId = devices[0].deviceId
if (!devices.length) ElMessage.warning('当前机器人没有在线设备')
} finally {
deviceLoading.value = false
}
}
const openDeviceDialog = async () => {
deviceDialogVisible.value = true
deviceForm.robotId = ''
deviceForm.deviceId = ''
deviceOptions.value = []
await loadRobotOptions()
}
const confirmDevice = async () => {
const valid = await deviceFormRef.value?.validate().catch(() => false)
if (!valid) return
const deviceParam = formData.nodeParams.find(item => item.name === 'deviceId')
if (!deviceParam) return
deviceParam.type = 'input'
deviceParam.input = deviceForm.deviceId
deviceParam.componentType = 'select'
deviceParam.selectOptions = [...deviceOptions.value]
deviceParam.required = true
deviceParam.deviceLocked = deviceOptions.value.length === 1
deviceDialogVisible.value = false
ElMessage.success('执行设备已选择')
}
// 使用共享的 quote 逻辑
const { quoteOptions, cascaderRefs, handleTypeChange, cascaderChange, visibleChange } = useQuote(props.data.id)
// 添加表单项
const addFormItem = (e, type) => {
e.stopPropagation()
const obj = {
name: '',
type: type === 'nodeParams' ? 'input' : 'string',
required: false,
children: [],
input: ''
}
if (!formData[type]) formData[type] = []
formData[type].push(obj)
}
// 删除输入参数(非递归)
const handleDelete = (index) => {
formData.nodeParams.splice(index, 1)
}
// 删除顶层输出参数(递归删除通过 FormItemRecursive 的 emit 处理)
const deleteTopLevelItem = (fullPath, propPath) => {
let currentLevel = formData[propPath]
for (let i = 0; i < fullPath.length - 1; i++) {
currentLevel = currentLevel[fullPath[i]].children
}
const lastIndex = fullPath[fullPath.length - 1]
currentLevel.splice(lastIndex, 1)
}
// 初始化数据
const initData = () => {
const nodeParams = JSON.parse(JSON.stringify(props.data.properties.nodeParams || []))
const outputParams = JSON.parse(JSON.stringify(props.data.properties.outputParams || []))
formData.nodeParams = nodeParams;
formData.outputParams = outputParams;
const codeParams = props.data.properties.nodeParams.find(item => item.name === 'requestJson')
if (codeParams) {
setTimeout(() => {
if (editorInstance) {
setValue(codeParams.input)
}
}, 100)
}
}
// 保存验证
const validateAndSave = async () => {
const targetObj = formData.nodeParams.find(item => item.name === 'requestJson');
if (targetObj) {
// 存在:修改该对象的 input 属性
targetObj.input = editorInstance.getValue();
} else {
formData.nodeParams.push(
{ name: "requestJson", type: "input", input: editorInstance.getValue() }
)
}
let inputValid = true
let outputValid = true
if (dynamicFormRef.value) {
await dynamicFormRef.value.validate((valid) => { if (!valid) inputValid = false })
}
if (outputFormRef.value) {
await outputFormRef.value.validate((valid) => { if (!valid) outputValid = false })
}
// 保存到 lf
lf.setProperties(props.data.id, {
...props.data.properties,
...formData
})
if (hasErrors()) {
emit('save-error')
return
}
if (inputValid && outputValid) {
emit('save-success')
} else {
emit('save-error')
}
}
onMounted(() => {
nextTick(() => {
initEditor('requestJson')
initData()
})
})
defineExpose({ validateAndSave })
onBeforeUnmount(() => {
disposeEditor()
})
</script>
<style lang="scss" scoped>
.form__container {
margin: 12px 0;
:deep(.el-row) {
align-items: end;
.el-form-item {
margin-right: 12px;
}
.param-name {
width: 160px;
}
.param-type {
width: 80px;
}
.param-value {
width: 160px;
}
}
.sub-properties {
margin-left: 10px;
.zw {
margin-left: 15px;
&::before {
content: "";
position: absolute;
left: 0;
top: -4px;
width: 10px;
border-left: 1px solid gray;
border-bottom: 1px solid gray;
border-bottom-left-radius: 4px;
background-color: transparent;
height: 24px;
}
}
}
.gSon-properties {
margin-left: 10px;
.zw {
margin-left: 15px;
&::before {
content: "";
position: absolute;
left: 0;
top: -4px;
width: 10px;
border-left: 1px solid gray;
border-bottom: 1px solid gray;
border-bottom-left-radius: 4px;
background-color: transparent;
height: 24px;
}
}
}
.deleteBtn {
margin-bottom: 22px;
cursor: pointer;
}
}
.device-binding-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 14px;
padding: 12px 14px;
border: 1px solid #d9e5f4;
border-radius: 6px;
background: #f6f9fd;
}
.device-binding-toolbar__title {
color: #26364a;
font-size: 14px;
font-weight: 600;
}
.device-binding-toolbar__desc,
.device-dialog-tip,
.device-auto-hint {
color: #6b7a90;
font-size: 12px;
line-height: 20px;
}
.device-dialog-tip {
margin-bottom: 16px;
padding: 10px 12px;
border-radius: 6px;
background: #f5f7fa;
}
.device-auto-hint {
width: 100%;
margin-top: 4px;
color: var(--el-color-success);
}
.code__container {
display: flex;
position: relative;
text-align: initial;
width: 100%;
height: 300px;
margin: 12px 0;
}
</style>