feat(iot): 将 antd 的 rule scene 迁移到 ele 里。

pull/345/head
YunaiV 2026-05-21 08:53:16 +08:00
parent 9cc52f128c
commit b3462c3286
28 changed files with 5798 additions and 10 deletions

View File

@ -244,7 +244,7 @@ export function deleteThingModel(id: number) {
} }
/** 获取物模型 TSL */ /** 获取物模型 TSL */
export function getThingModelTSL(productId: number) { export function getThingModelTSLByProductId(productId: number) {
return requestClient.get<ThingModelApi.ThingModelTSL>( return requestClient.get<ThingModelApi.ThingModelTSL>(
'/iot/thing-model/get-tsl', '/iot/thing-model/get-tsl',
{ {

View File

@ -15,7 +15,7 @@ import { isObject } from '@vben/utils';
import { useVModel } from '@vueuse/core'; import { useVModel } from '@vueuse/core';
import { Col, Form, Row, Select, Tag } from 'ant-design-vue'; import { Col, Form, Row, Select, Tag } from 'ant-design-vue';
import { getThingModelTSL } from '#/api/iot/thingmodel'; import { getThingModelTSLByProductId } from '#/api/iot/thingmodel';
import JsonParamsInput from '../inputs/json-params-input.vue'; import JsonParamsInput from '../inputs/json-params-input.vue';
import DeviceSelector from '../selectors/device-selector.vue'; import DeviceSelector from '../selectors/device-selector.vue';
@ -137,7 +137,7 @@ function handleServiceChange(serviceIdentifier?: any) {
async function fetchThingModelTSL(productId: number) { async function fetchThingModelTSL(productId: number) {
if (!productId) return null; if (!productId) return null;
try { try {
return await getThingModelTSL(productId); return await getThingModelTSLByProductId(productId);
} catch (error) { } catch (error) {
console.error('获取物模型 TSL 数据失败:', error); console.error('获取物模型 TSL 数据失败:', error);
return null; return null;

View File

@ -18,7 +18,7 @@ import { IconifyIcon } from '@vben/icons';
import { useVModel } from '@vueuse/core'; import { useVModel } from '@vueuse/core';
import { Button, Popover, Select, Tag } from 'ant-design-vue'; import { Button, Popover, Select, Tag } from 'ant-design-vue';
import { getThingModelTSL } from '#/api/iot/thingmodel'; import { getThingModelTSLByProductId } from '#/api/iot/thingmodel';
/** 属性选择器组件 */ /** 属性选择器组件 */
defineOptions({ name: 'PropertySelector' }); defineOptions({ name: 'PropertySelector' });
@ -110,7 +110,7 @@ async function loadThingModelTSL() {
} }
loading.value = true; loading.value = true;
try { try {
const tsl = await getThingModelTSL(props.productId); const tsl = await getThingModelTSLByProductId(props.productId);
propertyList.value = parseThingModelData(tsl); propertyList.value = parseThingModelData(tsl);
} catch (error) { } catch (error) {
console.error('获取物模型 TSL 失败:', error); console.error('获取物模型 TSL 失败:', error);

View File

@ -10,7 +10,7 @@ import { IOT_PROVIDE_KEY } from '@vben/constants';
import { Radio, Textarea } from 'ant-design-vue'; import { Radio, Textarea } from 'ant-design-vue';
import { getThingModelTSL } from '#/api/iot/thingmodel'; import { getThingModelTSLByProductId } from '#/api/iot/thingmodel';
const product = inject<Ref<IotProductApi.Product>>(IOT_PROVIDE_KEY.PRODUCT); const product = inject<Ref<IotProductApi.Product>>(IOT_PROVIDE_KEY.PRODUCT);
@ -26,7 +26,7 @@ const [Modal, modalApi] = useVbenModal({
modalApi.lock(); modalApi.lock();
try { try {
// //
thingModelTSL.value = await getThingModelTSL(product?.value?.id || 0); thingModelTSL.value = await getThingModelTSLByProductId(product?.value?.id || 0);
// values // values
tslString.value = JSON.stringify(thingModelTSL.value, null, 2); tslString.value = JSON.stringify(thingModelTSL.value, null, 2);
} finally { } finally {

View File

@ -235,7 +235,7 @@ export function deleteThingModel(id: number) {
} }
/** 获取物模型 TSL */ /** 获取物模型 TSL */
export function getThingModelTSL(productId: number) { export function getThingModelTSLByProductId(productId: number) {
return requestClient.get<any>('/iot/thing-model/get-tsl', { return requestClient.get<any>('/iot/thing-model/get-tsl', {
params: { productId }, params: { productId },
}); });

View File

@ -0,0 +1,139 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { z } from '#/adapter/form';
import { getRangePickerDefaultProps } from '#/utils';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'id',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
component: 'Input',
fieldName: 'name',
label: '规则名称',
rules: 'required',
componentProps: {
placeholder: '请输入规则名称',
},
},
{
fieldName: 'status',
label: '规则状态',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
buttonStyle: 'solid',
optionType: 'button',
},
rules: z.number().default(CommonStatusEnum.ENABLE),
},
{
fieldName: 'description',
label: '规则描述',
component: 'Textarea',
componentProps: {
placeholder: '请输入规则描述',
rows: 3,
},
formItemClass: 'col-span-2',
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '规则名称',
component: 'Input',
componentProps: {
placeholder: '请输入规则名称',
allowClear: true,
},
},
{
fieldName: 'status',
label: '规则状态',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
placeholder: '请选择状态',
allowClear: true,
},
},
{
fieldName: 'createTime',
label: '创建时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{ type: 'checkbox', width: 40 },
{
field: 'id',
title: '规则编号',
minWidth: 80,
},
{
field: 'name',
title: '规则名称',
minWidth: 150,
},
{
field: 'description',
title: '规则描述',
minWidth: 200,
},
{
field: 'status',
title: '规则状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
},
},
{
field: 'actionCount',
title: '执行动作数',
minWidth: 100,
},
{
field: 'executeCount',
title: '执行次数',
minWidth: 100,
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '操作',
width: 240,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@ -0,0 +1,85 @@
<!-- 告警配置组件 -->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useVModel } from '@vueuse/core';
import { ElFormItem, ElOption, ElSelect, ElTag } from 'element-plus';
import { getAlertConfigPage } from '#/api/iot/alert/config';
/** 告警配置组件 */
defineOptions({ name: 'AlertConfig' });
const props = defineProps<{
modelValue?: number;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value?: number): void;
}>();
const localValue = useVModel(props, 'modelValue', emit);
const loading = ref(false); //
const alertConfigs = ref<any[]>([]); //
/**
* 处理选择变化事件
* @param value 选中的值
*/
function handleChange(value?: any) {
emit('update:modelValue', value);
}
/**
* 加载告警配置列表
*/
async function loadAlertConfigs() {
loading.value = true;
try {
const data = await getAlertConfigPage({
pageNo: 1,
pageSize: 100,
enabled: true, //
});
alertConfigs.value = data.list || [];
} finally {
loading.value = false;
}
}
//
onMounted(() => {
loadAlertConfigs();
});
</script>
<template>
<div class="w-full">
<ElFormItem label="告警配置" required>
<ElSelect
v-model="localValue"
placeholder="请选择告警配置"
filterable
clearable
@change="handleChange"
class="w-full"
:loading="loading"
>
<ElOption
v-for="config in alertConfigs"
:key="config.id"
:label="config.name"
:value="config.id"
>
<div class="flex items-center justify-between">
<span>{{ config.name }}</span>
<ElTag :type="config.enabled ? 'success' : 'danger'" size="small">
{{ config.enabled ? '启用' : '禁用' }}
</ElTag>
</div>
</ElOption>
</ElSelect>
</ElFormItem>
</div>
</template>

View File

@ -0,0 +1,344 @@
<!-- 单个条件配置组件 -->
<script setup lang="ts">
import type { TriggerCondition } from '#/api/iot/rule/scene';
import { computed, ref } from 'vue';
import {
getConditionTypeOptions,
IoTDeviceStatusEnum,
IotRuleSceneTriggerConditionParameterOperatorEnum,
IotRuleSceneTriggerConditionTypeEnum,
} from '@vben/constants';
import { useVModel } from '@vueuse/core';
import {
ElCol,
ElFormItem,
ElOption,
ElRow,
ElSelect,
} from 'element-plus';
import ValueInput from '../inputs/value-input.vue';
import DeviceSelector from '../selectors/device-selector.vue';
import OperatorSelector from '../selectors/operator-selector.vue';
import ProductSelector from '../selectors/product-selector.vue';
import PropertySelector from '../selectors/property-selector.vue';
import CurrentTimeConditionConfig from './current-time-condition-config.vue';
/** 单个条件配置组件 */
defineOptions({ name: 'ConditionConfig' });
const props = defineProps<{
modelValue: TriggerCondition;
triggerType: number;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: TriggerCondition): void;
}>();
/** 获取设备状态选项 */
const deviceStatusOptions = [
{
value: IoTDeviceStatusEnum.ONLINE.value,
label: IoTDeviceStatusEnum.ONLINE.label,
},
{
value: IoTDeviceStatusEnum.OFFLINE.value,
label: IoTDeviceStatusEnum.OFFLINE.label,
},
];
/** 获取状态操作符选项 */
const statusOperatorOptions = [
{
value: IotRuleSceneTriggerConditionParameterOperatorEnum.EQUALS.value,
label: IotRuleSceneTriggerConditionParameterOperatorEnum.EQUALS.name,
},
{
value: IotRuleSceneTriggerConditionParameterOperatorEnum.NOT_EQUALS.value,
label: IotRuleSceneTriggerConditionParameterOperatorEnum.NOT_EQUALS.name,
},
];
const condition = useVModel(props, 'modelValue', emit);
const propertyType = ref<string>('string'); //
const propertyConfig = ref<any>(null); //
const isDeviceCondition = computed(() => {
return (
condition.value.type ===
IotRuleSceneTriggerConditionTypeEnum.DEVICE_STATUS ||
condition.value.type ===
IotRuleSceneTriggerConditionTypeEnum.DEVICE_PROPERTY
);
}); //
/**
* 更新条件字段
* @param field 字段名
* @param value 字段值
*/
function updateConditionField(field: any, value: any) {
(condition.value as any)[field] = value;
emit('update:modelValue', condition.value);
}
/**
* 更新整个条件对象
* @param newCondition 新的条件对象
*/
function updateCondition(newCondition: TriggerCondition) {
condition.value = newCondition;
emit('update:modelValue', condition.value);
}
/**
* 处理条件类型变化事件
* @param type 条件类型
*/
function handleConditionTypeChange(type: any) {
//
const isCurrentTime =
type === IotRuleSceneTriggerConditionTypeEnum.CURRENT_TIME;
const isDeviceStatus =
type === IotRuleSceneTriggerConditionTypeEnum.DEVICE_STATUS;
//
if (isCurrentTime || isDeviceStatus) {
condition.value.identifier = undefined;
}
//
if (isCurrentTime) {
condition.value.productId = undefined;
condition.value.deviceId = undefined;
}
//
condition.value.operator = isCurrentTime
? 'at_time'
: IotRuleSceneTriggerConditionParameterOperatorEnum.EQUALS.value;
//
condition.value.param = '';
}
/** 处理产品变化事件 */
function handleProductChange(_: any) {
//
condition.value.deviceId = undefined;
condition.value.identifier = '';
}
/** 处理设备变化事件 */
function handleDeviceChange(_: any) {
//
condition.value.identifier = '';
}
/**
* 处理属性变化事件
* @param propertyInfo.config - 属性配置
* @param propertyInfo.type - 属性类型
*/
function handlePropertyChange(propertyInfo: { config: any; type: string }) {
propertyType.value = propertyInfo.type;
propertyConfig.value = propertyInfo.config;
//
condition.value.operator =
IotRuleSceneTriggerConditionParameterOperatorEnum.EQUALS.value;
condition.value.param = '';
}
/** 处理操作符变化事件 */
function handleOperatorChange() {
//
condition.value.param = '';
}
</script>
<template>
<div class="gap-16px flex flex-col">
<!-- 条件类型选择 -->
<ElRow :gutter="16">
<ElCol :span="8">
<ElFormItem label="条件类型" required>
<ElSelect
:model-value="condition.type"
@update:model-value="
(value: any) => updateConditionField('type', value)
"
@change="handleConditionTypeChange"
placeholder="请选择条件类型"
class="w-full"
>
<ElOption
v-for="option in getConditionTypeOptions()"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</ElSelect>
</ElFormItem>
</ElCol>
</ElRow>
<!-- 产品设备选择 - 设备相关条件的公共部分 -->
<ElRow v-if="isDeviceCondition" :gutter="16">
<ElCol :span="12">
<ElFormItem label="产品" required>
<ProductSelector
:model-value="condition.productId"
@update:model-value="
(value) => updateConditionField('productId', value)
"
@change="handleProductChange"
/>
</ElFormItem>
</ElCol>
<ElCol :span="12">
<ElFormItem label="设备" required>
<DeviceSelector
:model-value="condition.deviceId"
@update:model-value="
(value) => updateConditionField('deviceId', value)
"
:product-id="condition.productId"
@change="handleDeviceChange"
/>
</ElFormItem>
</ElCol>
</ElRow>
<!-- 设备状态条件配置 -->
<div
v-if="
condition.type ===
IotRuleSceneTriggerConditionTypeEnum.DEVICE_STATUS
"
class="gap-16px flex flex-col"
>
<!-- 状态和操作符选择 -->
<ElRow :gutter="16">
<!-- 操作符选择 -->
<ElCol :span="12">
<ElFormItem label="操作符" required>
<ElSelect
:model-value="condition.operator"
@update:model-value="
(value: any) => updateConditionField('operator', value)
"
placeholder="请选择操作符"
class="w-full"
>
<ElOption
v-for="option in statusOperatorOptions"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</ElSelect>
</ElFormItem>
</ElCol>
<!-- 状态选择 -->
<ElCol :span="12">
<ElFormItem label="设备状态" required>
<ElSelect
:model-value="condition.param"
@update:model-value="
(value: any) => updateConditionField('param', value)
"
placeholder="请选择设备状态"
class="w-full"
>
<ElOption
v-for="option in deviceStatusOptions"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</ElSelect>
</ElFormItem>
</ElCol>
</ElRow>
</div>
<!-- 设备属性条件配置 -->
<div
v-else-if="
condition.type ===
IotRuleSceneTriggerConditionTypeEnum.DEVICE_PROPERTY
"
class="space-y-16px"
>
<!-- 属性配置 -->
<ElRow :gutter="16">
<!-- 属性/事件/服务选择 -->
<ElCol :span="6">
<ElFormItem label="监控项" required>
<PropertySelector
:model-value="condition.identifier"
@update:model-value="
(value) => updateConditionField('identifier', value)
"
:trigger-type="triggerType"
:product-id="condition.productId"
:device-id="condition.deviceId"
@change="handlePropertyChange"
/>
</ElFormItem>
</ElCol>
<!-- 操作符选择 -->
<ElCol :span="6">
<ElFormItem label="操作符" required>
<OperatorSelector
:model-value="condition.operator"
@update:model-value="
(value) => updateConditionField('operator', value)
"
:property-type="propertyType"
@change="handleOperatorChange"
/>
</ElFormItem>
</ElCol>
<!-- 值输入 -->
<ElCol :span="12">
<ElFormItem label="比较值" required>
<ValueInput
:model-value="condition.param"
@update:model-value="
(value) => updateConditionField('param', value)
"
:property-type="propertyType"
:operator="condition.operator"
:property-config="propertyConfig"
/>
</ElFormItem>
</ElCol>
</ElRow>
</div>
<!-- 当前时间条件配置 -->
<CurrentTimeConditionConfig
v-else-if="
condition.type ===
IotRuleSceneTriggerConditionTypeEnum.CURRENT_TIME
"
:model-value="condition"
@update:model-value="updateCondition"
/>
</div>
</template>
<style scoped>
:deep(.el-form-item) {
margin-bottom: 0;
}
</style>

View File

@ -0,0 +1,258 @@
<!-- 当前时间条件配置组件 -->
<script setup lang="ts">
import type { TriggerCondition } from '#/api/iot/rule/scene';
import { computed, watch } from 'vue';
import { IotRuleSceneTriggerTimeOperatorEnum } from '@vben/constants';
import { IconifyIcon } from '@vben/icons';
import { useVModel } from '@vueuse/core';
import {
ElCol,
ElDatePicker,
ElFormItem,
ElOption,
ElRow,
ElSelect,
ElTag,
ElTimePicker,
} from 'element-plus';
/** 当前时间条件配置组件 */
defineOptions({ name: 'CurrentTimeConditionConfig' });
const props = defineProps<{
modelValue: TriggerCondition;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: TriggerCondition): void;
}>();
const condition = useVModel(props, 'modelValue', emit);
//
const timeOperatorOptions = [
{
value: IotRuleSceneTriggerTimeOperatorEnum.BEFORE_TIME.value,
label: IotRuleSceneTriggerTimeOperatorEnum.BEFORE_TIME.name,
icon: 'ep:arrow-left',
iconClass: 'text-blue-500',
tag: 'primary',
category: '时间点',
},
{
value: IotRuleSceneTriggerTimeOperatorEnum.AFTER_TIME.value,
label: IotRuleSceneTriggerTimeOperatorEnum.AFTER_TIME.name,
icon: 'ep:arrow-right',
iconClass: 'text-green-500',
tag: 'success',
category: '时间点',
},
{
value: IotRuleSceneTriggerTimeOperatorEnum.BETWEEN_TIME.value,
label: IotRuleSceneTriggerTimeOperatorEnum.BETWEEN_TIME.name,
icon: 'ep:sort',
iconClass: 'text-orange-500',
tag: 'warning',
category: '时间段',
},
{
value: IotRuleSceneTriggerTimeOperatorEnum.AT_TIME.value,
label: IotRuleSceneTriggerTimeOperatorEnum.AT_TIME.name,
icon: 'ep:position',
iconClass: 'text-purple-500',
tag: 'info',
category: '时间点',
},
{
value: IotRuleSceneTriggerTimeOperatorEnum.TODAY.value,
label: IotRuleSceneTriggerTimeOperatorEnum.TODAY.name,
icon: 'ep:calendar',
iconClass: 'text-red-500',
tag: 'danger',
category: '日期',
},
];
//
const needsTimeInput = computed(() => {
const timeOnlyOperators = [
IotRuleSceneTriggerTimeOperatorEnum.BEFORE_TIME.value,
IotRuleSceneTriggerTimeOperatorEnum.AFTER_TIME.value,
IotRuleSceneTriggerTimeOperatorEnum.BETWEEN_TIME.value,
IotRuleSceneTriggerTimeOperatorEnum.AT_TIME.value,
];
return timeOnlyOperators.includes(condition.value.operator as any);
});
//
const needsDateInput = computed(() => {
return false; //
});
//
const needsSecondTimeInput = computed(() => {
return (
condition.value.operator ===
IotRuleSceneTriggerTimeOperatorEnum.BETWEEN_TIME.value
);
});
// param
const timeValue = computed(() => {
if (!condition.value.param) return '';
const params = condition.value.param.split(',');
return params[0] || '';
});
// param
const timeValue2 = computed(() => {
if (!condition.value.param) return '';
const params = condition.value.param.split(',');
return params[1] || '';
});
/**
* 更新条件字段
* @param field 字段名
* @param value 字段值
*/
function updateConditionField(field: any, value: any) {
(condition.value as any)[field] = value;
}
/**
* 处理第一个时间值变化
* @param value 时间值
*/
function handleTimeValueChange(value: string) {
const currentParams = condition.value.param
? condition.value.param.split(',')
: [];
currentParams[0] = value || '';
//
condition.value.param = needsSecondTimeInput.value
? currentParams.slice(0, 2).join(',')
: currentParams[0];
}
/**
* 处理第二个时间值变化
* @param value 时间值
*/
function handleTimeValue2Change(value: string) {
const currentParams = condition.value.param
? condition.value.param.split(',')
: [''];
currentParams[1] = value || '';
condition.value.param = currentParams.slice(0, 2).join(',');
}
/** 监听操作符变化,清理不相关的时间值 */
watch(
() => condition.value.operator,
(newOperator) => {
if (newOperator === IotRuleSceneTriggerTimeOperatorEnum.TODAY.value) {
//
condition.value.param = '';
} else if (!needsSecondTimeInput.value) {
//
const currentParams = condition.value.param
? condition.value.param.split(',')
: [];
condition.value.param = currentParams[0] || '';
}
},
);
</script>
<template>
<div class="flex flex-col gap-4">
<ElRow :gutter="16">
<!-- 时间操作符选择 -->
<ElCol :span="8">
<ElFormItem label="时间条件" required>
<ElSelect
:model-value="condition.operator"
@update:model-value="
(value: any) => updateConditionField('operator', value)
"
placeholder="请选择时间条件"
class="w-full"
>
<ElOption
v-for="option in timeOperatorOptions"
:key="option.value"
:label="option.label"
:value="option.value"
>
<div class="flex w-full items-center justify-between">
<div class="flex items-center gap-2">
<IconifyIcon :icon="option.icon" :class="option.iconClass" />
<span>{{ option.label }}</span>
</div>
<ElTag :type="option.tag as any" size="small">
{{ option.category }}
</ElTag>
</div>
</ElOption>
</ElSelect>
</ElFormItem>
</ElCol>
<!-- 时间值输入 -->
<ElCol :span="8">
<ElFormItem label="时间值" required>
<ElTimePicker
v-if="needsTimeInput"
:model-value="timeValue"
@update:model-value="handleTimeValueChange"
placeholder="请选择时间"
format="HH:mm:ss"
value-format="HH:mm:ss"
class="w-full"
/>
<ElDatePicker
v-else-if="needsDateInput"
:model-value="timeValue"
@update:model-value="handleTimeValueChange"
type="datetime"
placeholder="请选择日期时间"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
class="w-full"
/>
<div v-else class="text-sm text-secondary">无需设置时间值</div>
</ElFormItem>
</ElCol>
<!-- 第二个时间值范围条件 -->
<ElCol :span="8" v-if="needsSecondTimeInput">
<ElFormItem label="结束时间" required>
<ElTimePicker
v-if="needsTimeInput"
:model-value="timeValue2"
@update:model-value="handleTimeValue2Change"
placeholder="请选择结束时间"
format="HH:mm:ss"
value-format="HH:mm:ss"
class="w-full"
/>
<ElDatePicker
v-else
:model-value="timeValue2"
@update:model-value="handleTimeValue2Change"
type="datetime"
placeholder="请选择结束日期时间"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
class="w-full"
/>
</ElFormItem>
</ElCol>
</ElRow>
</div>
</template>

View File

@ -0,0 +1,427 @@
<!-- 设备控制配置组件 -->
<script setup lang="ts">
import type { Action } from '#/api/iot/rule/scene';
import type {
ThingModelProperty,
ThingModelService,
} from '#/api/iot/thingmodel';
import { computed, onMounted, ref, watch } from 'vue';
import {
IoTDataSpecsDataTypeEnum,
IotRuleSceneActionTypeEnum,
IoTThingModelAccessModeEnum,
} from '@vben/constants';
import { isObject } from '@vben/utils';
import { useVModel } from '@vueuse/core';
import {
ElCol,
ElFormItem,
ElOption,
ElRow,
ElSelect,
ElTag,
} from 'element-plus';
import { getThingModelTSLByProductId } from '#/api/iot/thingmodel';
import JsonParamsInput from '../inputs/json-params-input.vue';
import DeviceSelector from '../selectors/device-selector.vue';
import ProductSelector from '../selectors/product-selector.vue';
/** 设备控制配置组件 */
defineOptions({ name: 'DeviceControlConfig' });
const props = defineProps<{
modelValue: Action;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: Action): void;
}>();
const action = useVModel(props, 'modelValue', emit);
const thingModelProperties = ref<ThingModelProperty[]>([]); //
const loadingThingModel = ref(false); //
const selectedService = ref<null | ThingModelService>(null); //
const serviceList = ref<ThingModelService[]>([]); //
const loadingServices = ref(false); //
//
const paramsValue = computed({
get: () => {
// params JSON
if (action.value.params && isObject(action.value.params)) {
return JSON.stringify(action.value.params, null, 2);
}
// params
return action.value.params || '';
},
set: (value: string) => {
// JSON
action.value.params = value.trim() || '';
},
});
//
const isPropertySetAction = computed(() => {
return (
action.value.type ===
IotRuleSceneActionTypeEnum.DEVICE_PROPERTY_SET
);
});
//
const isServiceInvokeAction = computed(() => {
return (
action.value.type ===
IotRuleSceneActionTypeEnum.DEVICE_SERVICE_INVOKE
);
});
/**
* 处理产品变化事件
* @param productId 产品 ID
*/
function handleProductChange(productId?: number) {
//
if (action.value.productId !== productId) {
action.value.deviceId = undefined;
action.value.identifier = undefined; //
action.value.params = ''; //
selectedService.value = null; //
serviceList.value = []; //
}
//
if (productId) {
if (isPropertySetAction.value) {
loadThingModelProperties(productId);
} else if (isServiceInvokeAction.value) {
loadServiceList(productId);
}
}
}
/**
* 处理设备变化事件
* @param deviceId 设备 ID
*/
function handleDeviceChange(deviceId?: number) {
//
if (action.value.deviceId !== deviceId) {
action.value.params = ''; //
}
}
/**
* 处理服务变化事件
* @param serviceIdentifier 服务标识符
*/
function handleServiceChange(serviceIdentifier?: any) {
//
const service =
serviceList.value.find((s) => s.identifier === serviceIdentifier) || null;
selectedService.value = service;
//
action.value.params = '';
//
if (service && service.inputParams && service.inputParams.length > 0) {
const defaultParams = {};
service.inputParams.forEach((param) => {
defaultParams[param.identifier] = getDefaultValueForParam(param);
});
// JSON
action.value.params = JSON.stringify(defaultParams, null, 2);
}
}
/**
* 获取物模型TSL数据
* @param productId 产品ID
* @returns 物模型TSL数据
*/
async function fetchThingModelTSL(productId: number) {
if (!productId) return null;
try {
return await getThingModelTSLByProductId(productId);
} catch (error) {
console.error('获取物模型 TSL 数据失败:', error);
return null;
}
}
/**
* 加载物模型属性可写属性
* @param productId 产品ID
*/
async function loadThingModelProperties(productId: number) {
if (!productId) {
thingModelProperties.value = [];
return;
}
try {
loadingThingModel.value = true;
const tslData = await fetchThingModelTSL(productId);
if (!tslData?.properties) {
thingModelProperties.value = [];
return;
}
// accessMode 'w'
thingModelProperties.value = tslData.properties.filter(
(property: ThingModelProperty) =>
property.accessMode &&
(property.accessMode === IoTThingModelAccessModeEnum.READ_WRITE.value ||
property.accessMode === IoTThingModelAccessModeEnum.WRITE_ONLY.value),
);
} catch (error) {
console.error('加载物模型属性失败:', error);
thingModelProperties.value = [];
} finally {
loadingThingModel.value = false;
}
}
/**
* 加载服务列表
* @param productId 产品ID
*/
async function loadServiceList(productId: number) {
if (!productId) {
serviceList.value = [];
return;
}
try {
loadingServices.value = true;
const tslData = await fetchThingModelTSL(productId);
if (!tslData?.services) {
serviceList.value = [];
return;
}
serviceList.value = tslData.services;
} catch (error) {
console.error('加载服务列表失败:', error);
serviceList.value = [];
} finally {
loadingServices.value = false;
}
}
/**
* 从TSL加载服务信息用于编辑模式回显
* @param productId 产品ID
* @param serviceIdentifier 服务标识符
*/
async function loadServiceFromTSL(
productId: number,
serviceIdentifier: string,
) {
//
await loadServiceList(productId);
//
const service = serviceList.value.find(
(s: any) => s.identifier === serviceIdentifier,
);
if (service) {
selectedService.value = service;
}
}
/**
* 根据参数类型获取默认值
* @param param 参数对象
* @returns 默认值
*/
function getDefaultValueForParam(param: any) {
switch (param.dataType) {
case IoTDataSpecsDataTypeEnum.BOOL: {
return false;
}
case IoTDataSpecsDataTypeEnum.DOUBLE:
case IoTDataSpecsDataTypeEnum.FLOAT: {
return 0;
}
case IoTDataSpecsDataTypeEnum.ENUM: {
// 使
if (
param.dataSpecs?.dataSpecsList &&
param.dataSpecs.dataSpecsList.length > 0
) {
return param.dataSpecs.dataSpecsList[0].value;
}
return '';
}
case IoTDataSpecsDataTypeEnum.INT: {
return 0;
}
case IoTDataSpecsDataTypeEnum.TEXT: {
return '';
}
default: {
return '';
}
}
}
const isInitialized = ref(false); //
/**
* 初始化组件数据
*/
async function initializeComponent() {
if (isInitialized.value) return;
const currentAction = action.value;
if (!currentAction) return;
//
if (currentAction.productId && isPropertySetAction.value) {
await loadThingModelProperties(currentAction.productId);
}
//
if (
currentAction.productId &&
isServiceInvokeAction.value &&
currentAction.identifier
) {
// TSL
await loadServiceFromTSL(currentAction.productId, currentAction.identifier);
}
isInitialized.value = true;
}
/** 组件初始化 */
onMounted(() => {
initializeComponent();
});
/** 监听关键字段的变化,避免深度监听导致的性能问题 */
watch(
() => [action.value.productId, action.value.type, action.value.identifier],
async ([newProductId, , newIdentifier], [oldProductId, , oldIdentifier]) => {
//
if (!isInitialized.value) return;
//
if (newProductId !== oldProductId) {
if (newProductId && isPropertySetAction.value) {
await loadThingModelProperties(newProductId as number);
} else if (newProductId && isServiceInvokeAction.value) {
await loadServiceList(newProductId as number);
}
}
//
if (
newIdentifier !== oldIdentifier &&
newProductId &&
isServiceInvokeAction.value &&
newIdentifier
) {
const service = serviceList.value.find(
(s: any) => s.identifier === newIdentifier,
);
if (service) {
selectedService.value = service;
}
}
},
);
</script>
<template>
<div class="gap-16px flex flex-col">
<!-- 产品和设备选择 - 与触发器保持一致的分离式选择器 -->
<ElRow :gutter="16">
<ElCol :span="12">
<ElFormItem label="产品" required>
<ProductSelector
v-model="action.productId"
@change="handleProductChange"
/>
</ElFormItem>
</ElCol>
<ElCol :span="12">
<ElFormItem label="设备" required>
<DeviceSelector
v-model="action.deviceId"
:product-id="action.productId"
@change="handleDeviceChange"
/>
</ElFormItem>
</ElCol>
</ElRow>
<!-- 服务选择 - 服务调用类型时显示 -->
<div v-if="action.productId && isServiceInvokeAction" class="space-y-16px">
<ElFormItem label="服务" required>
<ElSelect
v-model="action.identifier"
placeholder="请选择服务"
filterable
clearable
class="w-full"
:loading="loadingServices"
@change="handleServiceChange"
>
<ElOption
v-for="service in serviceList"
:key="service.identifier"
:label="service.name"
:value="service.identifier"
>
<div class="flex items-center justify-between">
<span>{{ service.name }}</span>
<ElTag
:type="service.callType === 'sync' ? 'primary' : 'success'"
size="small"
>
{{ service.callType === 'sync' ? '同步' : '异步' }}
</ElTag>
</div>
</ElOption>
</ElSelect>
</ElFormItem>
<!-- 服务参数配置 -->
<div v-if="action.identifier" class="space-y-16px">
<ElFormItem label="服务参数" required>
<JsonParamsInput
v-model="paramsValue"
type="service"
:config="{ service: selectedService } as any"
placeholder="请输入 JSON 格式的服务参数"
/>
</ElFormItem>
</div>
</div>
<!-- 控制参数配置 - 属性设置类型时显示 -->
<div v-if="action.productId && isPropertySetAction" class="space-y-16px">
<!-- 参数配置 -->
<ElFormItem label="参数" required>
<JsonParamsInput
v-model="paramsValue"
type="property"
:config="{ properties: thingModelProperties }"
placeholder="请输入 JSON 格式的控制参数"
/>
</ElFormItem>
</div>
</div>
</template>

View File

@ -0,0 +1,271 @@
<!-- 设备触发配置组件 -->
<script setup lang="ts">
import type { RuleSceneApi } from '#/api/iot/rule/scene';
import { nextTick } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { useVModel } from '@vueuse/core';
import { ElButton, ElTag } from 'element-plus';
import MainConditionInnerConfig from './main-condition-inner-config.vue';
import SubConditionGroupConfig from './sub-condition-group-config.vue';
/** 设备触发配置组件 */
defineOptions({ name: 'DeviceTriggerConfig' });
const props = defineProps<{
index: number;
modelValue: RuleSceneApi.Trigger;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: RuleSceneApi.Trigger): void;
(e: 'triggerTypeChange', type: number): void;
}>();
const trigger = useVModel(props, 'modelValue', emit);
const maxSubGroups = 3; // 3
const maxConditionsPerGroup = 3; // 3
/**
* 更新条件
* @param condition 条件对象
*/
function updateCondition(condition: RuleSceneApi.Trigger) {
trigger.value = condition;
}
/**
* 处理触发器类型变化事件
* @param type 触发器类型
*/
function handleTriggerTypeChange(type: number) {
trigger.value.type = type;
emit('triggerTypeChange', type);
}
/** 添加子条件组 */
async function addSubGroup() {
if (!trigger.value.conditionGroups) {
trigger.value.conditionGroups = [];
}
//
if (trigger.value.conditionGroups?.length >= maxSubGroups) {
return;
}
// 使 nextTick
await nextTick();
if (trigger.value.conditionGroups) {
trigger.value.conditionGroups.push([] as any);
}
}
/**
* 移除子条件组
* @param index 子条件组索引
*/
function removeSubGroup(index: number) {
if (trigger.value.conditionGroups) {
trigger.value.conditionGroups.splice(index, 1);
}
}
/**
* 更新子条件组
* @param index 子条件组索引
* @param subGroup 子条件组数据
*/
function updateSubGroup(index: number, subGroup: any) {
if (trigger.value.conditionGroups) {
trigger.value.conditionGroups[index] = subGroup;
}
}
/** 移除整个条件组 */
function removeConditionGroup() {
trigger.value.conditionGroups = undefined;
}
</script>
<template>
<div class="gap-16px flex flex-col">
<!-- 主条件配置 - 默认直接展示 -->
<div class="space-y-16px">
<!-- 主条件配置 -->
<div class="gap-16px flex flex-col">
<!-- 主条件配置 -->
<div class="space-y-16px">
<!-- 主条件头部 - 与附加条件组保持一致的绿色风格 -->
<div
class="p-16px rounded-8px flex items-center justify-between border border-green-200 bg-gradient-to-r from-green-50 to-emerald-50"
>
<div class="gap-12px flex items-center">
<div
class="gap-8px text-16px font-600 flex items-center text-green-700"
>
<div
class="w-24px h-24px text-12px flex items-center justify-center rounded-full bg-green-500 font-bold text-white"
>
</div>
<span>主条件</span>
</div>
<ElTag size="small" type="success">必须满足</ElTag>
</div>
</div>
<!-- 主条件内容配置 -->
<MainConditionInnerConfig
:model-value="trigger"
@update:model-value="updateCondition"
:trigger-type="trigger.type as any"
@trigger-type-change="handleTriggerTypeChange"
/>
</div>
</div>
</div>
<!-- 条件组配置 -->
<div class="space-y-16px">
<!-- 条件组配置 -->
<div class="gap-16px flex flex-col">
<!-- 条件组容器头部 -->
<div
class="p-16px rounded-8px flex items-center justify-between border border-green-200 bg-gradient-to-r from-green-50 to-emerald-50"
>
<div class="gap-12px flex items-center">
<div
class="gap-8px text-16px font-600 flex items-center text-green-700"
>
<div
class="w-24px h-24px text-12px flex items-center justify-center rounded-full bg-green-500 font-bold text-white"
>
</div>
<span>附加条件组</span>
</div>
<ElTag size="small" type="success">"主条件"为且关系</ElTag>
<ElTag size="small" type="info">
{{ trigger.conditionGroups?.length || 0 }} 个子条件组
</ElTag>
</div>
<div class="gap-8px flex items-center">
<ElButton
type="primary"
size="small"
@click="addSubGroup"
:disabled="(trigger.conditionGroups?.length || 0) >= maxSubGroups"
>
<IconifyIcon icon="lucide:plus" />
添加子条件组
</ElButton>
<ElButton type="danger" size="small" link @click="removeConditionGroup">
<IconifyIcon icon="lucide:trash-2" />
删除条件组
</ElButton>
</div>
</div>
<!-- 子条件组列表 -->
<div
v-if="trigger.conditionGroups && trigger.conditionGroups.length > 0"
class="space-y-16px"
>
<!-- 逻辑关系说明 -->
<div class="relative">
<div
v-for="(subGroup, subGroupIndex) in trigger.conditionGroups"
:key="`sub-group-${subGroupIndex}`"
class="relative"
>
<!-- 子条件组容器 -->
<div
class="rounded-8px border-2 border-orange-200 bg-orange-50 shadow-sm transition-shadow hover:shadow-md"
>
<div
class="p-16px rounded-t-6px flex items-center justify-between border-b border-orange-200 bg-gradient-to-r from-orange-50 to-yellow-50"
>
<div class="gap-12px flex items-center">
<div
class="gap-8px text-16px font-600 flex items-center text-orange-700"
>
<div
class="w-24px h-24px text-12px flex items-center justify-center rounded-full bg-orange-500 font-bold text-white"
>
{{ subGroupIndex + 1 }}
</div>
<span>子条件组 {{ subGroupIndex + 1 }}</span>
</div>
<ElTag size="small" type="warning" class="font-500">
组内条件为"且"关系
</ElTag>
<ElTag size="small" type="info">
{{ (subGroup as any)?.length || 0 }}个条件
</ElTag>
</div>
<ElButton
type="danger"
size="small"
link
@click="removeSubGroup(subGroupIndex)"
class="hover:bg-red-50"
>
<IconifyIcon icon="lucide:trash-2" />
删除组
</ElButton>
</div>
<SubConditionGroupConfig
:model-value="subGroup as any"
@update:model-value="
(value) => updateSubGroup(subGroupIndex, value)
"
:trigger-type="trigger.type as any"
:max-conditions="maxConditionsPerGroup"
/>
</div>
<!-- 子条件组间的'或'连接符 -->
<div
v-if="subGroupIndex < trigger.conditionGroups!.length - 1"
class="py-12px flex items-center justify-center"
>
<div class="gap-8px flex items-center">
<!-- 连接线 -->
<div class="w-32px h-1px bg-orange-300"></div>
<!-- 或标签 -->
<div
class="px-16px py-6px rounded-full border-2 border-orange-300 bg-orange-100"
>
<span class="text-14px font-600 text-orange-600"></span>
</div>
<!-- 连接线 -->
<div class="w-32px h-1px bg-orange-300"></div>
</div>
</div>
</div>
</div>
</div>
<!-- 空状态 -->
<div
v-else
class="p-24px rounded-8px border-2 border-dashed border-orange-200 bg-orange-50 text-center"
>
<div class="gap-12px flex flex-col items-center">
<IconifyIcon icon="lucide:plus" class="text-32px text-orange-400" />
<div class="text-orange-600">
<p class="text-14px font-500 mb-4px">暂无子条件组</p>
<p class="text-12px">点击上方"添加子条件组"按钮开始配置</p>
</div>
</div>
</div>
</div>
</div>
</div>
</template>

View File

@ -0,0 +1,380 @@
<script setup lang="ts">
import type { Trigger } from '#/api/iot/rule/scene';
import { computed, ref } from 'vue';
import {
getTriggerTypeLabel,
IoTDeviceStatusEnum,
IotRuleSceneTriggerConditionParameterOperatorEnum,
IotRuleSceneTriggerTypeEnum,
triggerTypeOptions,
} from '@vben/constants';
import { useVModel } from '@vueuse/core';
import {
ElCol,
ElFormItem,
ElOption,
ElRow,
ElSelect,
} from 'element-plus';
import JsonParamsInput from '../inputs/json-params-input.vue';
import ValueInput from '../inputs/value-input.vue';
import DeviceSelector from '../selectors/device-selector.vue';
import OperatorSelector from '../selectors/operator-selector.vue';
import ProductSelector from '../selectors/product-selector.vue';
import PropertySelector from '../selectors/property-selector.vue';
/** 主条件内部配置组件 */
defineOptions({ name: 'MainConditionInnerConfig' });
const props = defineProps<{
modelValue: Trigger;
triggerType: number;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: Trigger): void;
(e: 'triggerTypeChange', value: number): void;
}>();
/** 获取设备状态变更选项(用于触发器配置) */
const deviceStatusChangeOptions = [
{
label: IoTDeviceStatusEnum.ONLINE.label,
value: IoTDeviceStatusEnum.ONLINE.value,
},
{
label: IoTDeviceStatusEnum.OFFLINE.label,
value: IoTDeviceStatusEnum.OFFLINE.value,
},
];
const condition = useVModel(props, 'modelValue', emit);
const propertyType = ref(''); //
const propertyConfig = ref<any>(null); //
//
const isDevicePropertyTrigger = computed(() => {
return (
props.triggerType === IotRuleSceneTriggerTypeEnum.DEVICE_PROPERTY_POST ||
props.triggerType === IotRuleSceneTriggerTypeEnum.DEVICE_EVENT_POST ||
props.triggerType === IotRuleSceneTriggerTypeEnum.DEVICE_SERVICE_INVOKE
);
});
//
const isDeviceStatusTrigger = computed(() => {
return props.triggerType === IotRuleSceneTriggerTypeEnum.DEVICE_STATE_UPDATE;
});
//
const needsOperatorSelector = computed(() => {
const noOperatorTriggerTypes = [
IotRuleSceneTriggerTypeEnum.DEVICE_SERVICE_INVOKE,
IotRuleSceneTriggerTypeEnum.DEVICE_EVENT_POST,
] as number[];
return !noOperatorTriggerTypes.includes(props.triggerType);
});
//
const isWideValueColumn = computed(() => {
const wideColumnTriggerTypes = [
IotRuleSceneTriggerTypeEnum.DEVICE_SERVICE_INVOKE,
IotRuleSceneTriggerTypeEnum.DEVICE_EVENT_POST,
] as number[];
return wideColumnTriggerTypes.includes(props.triggerType);
});
//
const valueInputLabel = computed(() => {
return props.triggerType === IotRuleSceneTriggerTypeEnum.DEVICE_SERVICE_INVOKE
? '服务参数'
: '比较值';
});
// - JsonParamsInput
const serviceConfig = computed(() => {
if (
propertyConfig.value &&
props.triggerType === IotRuleSceneTriggerTypeEnum.DEVICE_SERVICE_INVOKE
) {
return {
service: {
name: propertyConfig.value.name || '服务',
inputParams: propertyConfig.value.inputParams || [],
},
};
}
return undefined;
});
// - JsonParamsInput
const eventConfig = computed(() => {
if (
propertyConfig.value &&
props.triggerType === IotRuleSceneTriggerTypeEnum.DEVICE_EVENT_POST
) {
return {
event: {
name: propertyConfig.value.name || '事件',
outputParams: propertyConfig.value.outputParams || [],
},
};
}
return undefined;
});
/**
* 更新条件字段
* @param field 字段名
* @param value 字段值
*/
function updateConditionField(field: any, value: any) {
(condition.value as any)[field] = value;
}
/**
* 处理触发器类型变化事件
* @param type 触发器类型
*/
function handleTriggerTypeChange(type: number) {
emit('triggerTypeChange', type);
}
/** 处理产品变化事件 */
function handleProductChange() {
//
condition.value.deviceId = undefined;
condition.value.identifier = '';
}
/** 处理设备变化事件 */
function handleDeviceChange() {
//
condition.value.identifier = '';
}
/**
* 处理属性变化事件
* @param propertyInfo 属性信息对象
*/
function handlePropertyChange(propertyInfo: any) {
if (propertyInfo) {
propertyType.value = propertyInfo.type;
propertyConfig.value = propertyInfo.config;
// '='
if (
props.triggerType === IotRuleSceneTriggerTypeEnum.DEVICE_EVENT_POST ||
props.triggerType === IotRuleSceneTriggerTypeEnum.DEVICE_SERVICE_INVOKE
) {
condition.value.operator =
IotRuleSceneTriggerConditionParameterOperatorEnum.EQUALS.value;
}
}
}
</script>
<template>
<div class="space-y-4">
<!-- 触发事件类型选择 -->
<ElFormItem label="触发事件类型" required>
<ElSelect
:model-value="triggerType"
@update:model-value="handleTriggerTypeChange"
placeholder="请选择触发事件类型"
class="w-full"
>
<ElOption
v-for="option in triggerTypeOptions"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</ElSelect>
</ElFormItem>
<!-- 设备属性条件配置 -->
<div v-if="isDevicePropertyTrigger" class="space-y-4">
<!-- 产品设备选择 -->
<ElRow :gutter="16">
<ElCol :span="12">
<ElFormItem label="产品" required>
<ProductSelector
:model-value="condition.productId"
@update:model-value="
(value) => updateConditionField('productId', value)
"
@change="handleProductChange"
/>
</ElFormItem>
</ElCol>
<ElCol :span="12">
<ElFormItem label="设备" required>
<DeviceSelector
:model-value="condition.deviceId"
@update:model-value="
(value) => updateConditionField('deviceId', value)
"
:product-id="condition.productId"
@change="handleDeviceChange"
/>
</ElFormItem>
</ElCol>
</ElRow>
<!-- 属性配置 -->
<ElRow :gutter="16">
<!-- 属性/事件/服务选择 -->
<ElCol :span="6">
<ElFormItem label="监控项" required>
<PropertySelector
:model-value="condition.identifier"
@update:model-value="
(value) => updateConditionField('identifier', value)
"
:trigger-type="triggerType"
:product-id="condition.productId"
:device-id="condition.deviceId"
@change="handlePropertyChange"
/>
</ElFormItem>
</ElCol>
<!-- 操作符选择 - 服务调用和事件上报不需要操作符 -->
<ElCol v-if="needsOperatorSelector" :span="6">
<ElFormItem label="操作符" required>
<OperatorSelector
:model-value="condition.operator"
@update:model-value="
(value) => updateConditionField('operator', value)
"
:property-type="propertyType"
/>
</ElFormItem>
</ElCol>
<!-- 值输入 -->
<ElCol :span="isWideValueColumn ? 18 : 12">
<ElFormItem :label="valueInputLabel" required>
<!-- 服务调用参数配置 -->
<JsonParamsInput
v-if="
triggerType ===
IotRuleSceneTriggerTypeEnum.DEVICE_SERVICE_INVOKE
"
v-model="condition.value"
type="service"
:config="serviceConfig as any"
placeholder="请输入 JSON 格式的服务参数"
/>
<!-- 事件上报参数配置 -->
<JsonParamsInput
v-else-if="
triggerType === IotRuleSceneTriggerTypeEnum.DEVICE_EVENT_POST
"
v-model="condition.value"
type="event"
:config="eventConfig as any"
placeholder="请输入 JSON 格式的事件参数"
/>
<!-- 普通值输入 -->
<ValueInput
v-else
:model-value="condition.value"
@update:model-value="
(value) => updateConditionField('value', value)
"
:property-type="propertyType"
:operator="condition.operator"
:property-config="propertyConfig"
/>
</ElFormItem>
</ElCol>
</ElRow>
</div>
<!-- 设备状态条件配置 -->
<div v-else-if="isDeviceStatusTrigger" class="space-y-4">
<!-- 设备状态触发器使用简化的配置 -->
<ElRow :gutter="16">
<ElCol :span="12">
<ElFormItem label="产品" required>
<ProductSelector
:model-value="condition.productId"
@update:model-value="
(value) => updateConditionField('productId', value)
"
@change="handleProductChange"
/>
</ElFormItem>
</ElCol>
<ElCol :span="12">
<ElFormItem label="设备" required>
<DeviceSelector
:model-value="condition.deviceId"
@update:model-value="
(value) => updateConditionField('deviceId', value)
"
:product-id="condition.productId"
@change="handleDeviceChange"
/>
</ElFormItem>
</ElCol>
</ElRow>
<ElRow :gutter="16">
<ElCol :span="6">
<ElFormItem label="操作符" required>
<ElSelect
:model-value="condition.operator"
@update:model-value="
(value: any) => updateConditionField('operator', value)
"
placeholder="请选择操作符"
class="w-full"
>
<ElOption
:label="
IotRuleSceneTriggerConditionParameterOperatorEnum.EQUALS.name
"
:value="
IotRuleSceneTriggerConditionParameterOperatorEnum.EQUALS.value
"
/>
</ElSelect>
</ElFormItem>
</ElCol>
<ElCol :span="6">
<ElFormItem label="参数" required>
<ElSelect
:model-value="condition.value"
@update:model-value="
(value: any) => updateConditionField('value', value)
"
placeholder="请选择操作符"
class="w-full"
>
<ElOption
v-for="option in deviceStatusChangeOptions"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</ElSelect>
</ElFormItem>
</ElCol>
</ElRow>
</div>
<!-- 其他触发类型的提示 -->
<div v-else class="py-5 text-center">
<p class="mb-1 text-sm text-secondary">
当前触发事件类型{{ getTriggerTypeLabel(triggerType) }}
</p>
<p class="text-xs text-secondary">此触发类型暂不需要配置额外条件</p>
</div>
</div>
</template>

View File

@ -0,0 +1,167 @@
<script setup lang="ts">
import type { TriggerCondition } from '#/api/iot/rule/scene';
import { computed, nextTick } from 'vue';
import {
IotRuleSceneTriggerConditionParameterOperatorEnum,
IotRuleSceneTriggerConditionTypeEnum,
} from '@vben/constants';
import { IconifyIcon } from '@vben/icons';
import { useVModel } from '@vueuse/core';
import { ElButton } from 'element-plus';
import ConditionConfig from './condition-config.vue';
/** 子条件组配置组件 */
defineOptions({ name: 'SubConditionGroupConfig' });
const props = defineProps<{
maxConditions?: number;
modelValue: TriggerCondition[];
triggerType: number;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: TriggerCondition[]): void;
}>();
const subGroup = useVModel(props, 'modelValue', emit);
const maxConditions = computed(() => props.maxConditions || 3); //
/** 添加条件 */
async function addCondition() {
// subGroup.value
if (!subGroup.value) {
subGroup.value = [];
}
//
if (subGroup.value?.length >= maxConditions.value) {
return;
}
const newCondition: TriggerCondition = {
type: IotRuleSceneTriggerConditionTypeEnum.DEVICE_PROPERTY, //
productId: undefined,
deviceId: undefined,
identifier: '',
operator: IotRuleSceneTriggerConditionParameterOperatorEnum.EQUALS.value, // 使
param: '',
};
// 使 nextTick
await nextTick();
if (subGroup.value) {
subGroup.value.push(newCondition);
}
}
/**
* 移除条件
* @param index 条件索引
*/
function removeCondition(index: number) {
if (subGroup.value) {
subGroup.value.splice(index, 1);
}
}
/**
* 更新条件
* @param index 条件索引
* @param condition 条件对象
*/
function updateCondition(index: number, condition: TriggerCondition) {
if (subGroup.value) {
subGroup.value[index] = condition;
}
}
</script>
<template>
<div class="p-4">
<!-- 空状态 -->
<div v-if="!subGroup || subGroup.length === 0" class="py-6 text-center">
<div class="flex flex-col items-center gap-3">
<IconifyIcon icon="lucide:plus" class="text-8 text-secondary" />
<div class="text-secondary">
<p class="mb-1 text-base font-bold">暂无条件</p>
<p class="text-xs">点击下方按钮添加第一个条件</p>
</div>
<ElButton type="primary" @click="addCondition">
<IconifyIcon icon="lucide:plus" />
添加条件
</ElButton>
</div>
</div>
<!-- 条件列表 -->
<div v-else class="space-y-4">
<div
v-for="(condition, conditionIndex) in subGroup"
:key="`condition-${conditionIndex}`"
class="relative"
>
<!-- 条件配置 -->
<div
class="rounded-3px bg-fill-color-blank border border-border shadow-sm"
>
<div
class="rounded-t-1 bg-fill-color-blank flex items-center justify-between border-b border-border p-3"
>
<div class="flex items-center gap-2">
<div
class="flex size-5 items-center justify-center rounded-full bg-primary text-xs font-bold text-white"
>
{{ conditionIndex + 1 }}
</div>
<span class="text-base font-bold text-primary">
条件 {{ conditionIndex + 1 }}
</span>
</div>
<ElButton
type="danger"
size="small"
link
@click="removeCondition(conditionIndex)"
v-if="subGroup!.length > 1"
class="hover:bg-red-50"
>
<IconifyIcon icon="lucide:trash-2" />
</ElButton>
</div>
<div class="p-3">
<ConditionConfig
:model-value="condition"
@update:model-value="
(value: TriggerCondition) =>
updateCondition(conditionIndex, value)
"
:trigger-type="triggerType"
/>
</div>
</div>
</div>
<!-- 添加条件按钮 -->
<div
v-if="
subGroup && subGroup.length > 0 && subGroup.length < maxConditions
"
class="py-4 text-center"
>
<ElButton type="primary" plain @click="addCondition">
<IconifyIcon icon="lucide:plus" />
继续添加条件
</ElButton>
<span class="mt-2 block text-xs text-secondary">
最多可添加 {{ maxConditions }} 个条件
</span>
</div>
</div>
</div>
</template>

View File

@ -0,0 +1,179 @@
<script setup lang="ts">
import type { TriggerCondition } from '#/api/iot/rule/scene';
import { nextTick } from 'vue';
import { IotRuleSceneTriggerTypeEnum } from '@vben/constants';
import { IconifyIcon } from '@vben/icons';
import { useVModel } from '@vueuse/core';
import { ElButton, ElTag } from 'element-plus';
import SubConditionGroupConfig from './sub-condition-group-config.vue';
const props = defineProps<{
modelValue?: TriggerCondition[][];
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: TriggerCondition[][]): void;
}>();
const conditionGroups = useVModel(props, 'modelValue', emit);
const maxGroups = 3; // 3
const maxConditionsPerGroup = 3; // 3
/** 添加条件组 */
async function addConditionGroup() {
if (!conditionGroups.value) {
conditionGroups.value = [];
}
if (conditionGroups.value.length >= maxGroups) {
return;
}
await nextTick();
if (conditionGroups.value) {
conditionGroups.value.push([]);
}
}
/** 移除条件组 */
function removeConditionGroup(index: number) {
if (conditionGroups.value) {
conditionGroups.value.splice(index, 1);
}
}
/** 更新条件组 */
function updateConditionGroup(index: number, group: TriggerCondition[]) {
if (conditionGroups.value) {
conditionGroups.value[index] = group;
}
}
</script>
<template>
<div class="space-y-[16px]">
<!-- 条件组容器头部蓝色主题 -->
<div
class="px-[16px] py-[10px] rounded-[6px] flex items-center justify-between border border-blue-200 bg-gradient-to-r from-blue-50 to-cyan-50 dark:border-blue-900/40 dark:from-blue-950/30 dark:to-cyan-950/30"
>
<div class="gap-[10px] flex items-center">
<div
class="gap-[8px] text-[14px] font-semibold flex items-center text-blue-700 dark:text-blue-300"
>
<div
class="w-[22px] h-[22px] text-[12px] flex items-center justify-center rounded-full bg-blue-500 font-bold text-white"
>
</div>
<span>附加条件组</span>
</div>
<ElTag type="primary">定时触发时需满足以下条件</ElTag>
<ElTag type="warning">
{{ conditionGroups?.length || 0 }} 个子条件组
</ElTag>
</div>
<ElButton
type="primary"
size="small"
:disabled="(conditionGroups?.length || 0) >= maxGroups"
@click="addConditionGroup"
>
<IconifyIcon icon="lucide:plus" />
添加条件组
</ElButton>
</div>
<!-- 条件组列表 -->
<div
v-if="conditionGroups && conditionGroups.length > 0"
class="space-y-[16px]"
>
<div
v-for="(group, groupIndex) in conditionGroups"
:key="`group-${groupIndex}`"
class="relative"
>
<!-- 条件组容器橙色主题 -->
<div
class="rounded-[8px] border border-orange-200 bg-orange-50/40 shadow-sm transition-shadow hover:shadow-md dark:border-orange-900/40 dark:bg-orange-950/20"
>
<div
class="px-[16px] py-[10px] rounded-t-[8px] flex items-center justify-between border-b border-orange-200 bg-gradient-to-r from-orange-50 to-yellow-50 dark:border-orange-900/40 dark:from-orange-950/30 dark:to-yellow-950/30"
>
<div class="gap-[10px] flex items-center">
<div
class="gap-[8px] text-[14px] font-semibold flex items-center text-orange-700 dark:text-orange-300"
>
<div
class="w-[22px] h-[22px] text-[12px] flex items-center justify-center rounded-full bg-orange-500 font-bold text-white"
>
{{ groupIndex + 1 }}
</div>
<span>子条件组 {{ groupIndex + 1 }}</span>
</div>
<ElTag type="warning" class="font-medium">
组内条件为关系
</ElTag>
<ElTag type="info">
{{ group?.length || 0 }} 个条件
</ElTag>
</div>
<ElButton
link
type="danger"
size="small"
class="hover:bg-red-50"
@click="removeConditionGroup(groupIndex)"
>
<IconifyIcon icon="lucide:trash-2" />
删除组
</ElButton>
</div>
<SubConditionGroupConfig
:model-value="group"
:trigger-type="IotRuleSceneTriggerTypeEnum.TIMER"
:max-conditions="maxConditionsPerGroup"
@update:model-value="
(value: TriggerCondition[]) =>
updateConditionGroup(groupIndex, value)
"
/>
</div>
<!-- 条件组间的连接符 -->
<div
v-if="groupIndex < conditionGroups.length - 1"
class="py-[12px] flex items-center justify-center"
>
<div class="gap-[8px] flex items-center">
<div class="w-[32px] h-[1px] bg-orange-300 dark:bg-orange-800"></div>
<div
class="px-[14px] py-[3px] rounded-full border border-orange-300 bg-orange-100 dark:border-orange-800 dark:bg-orange-950/50"
>
<span class="text-[13px] font-semibold text-orange-600 dark:text-orange-300"></span>
</div>
<div class="w-[32px] h-[1px] bg-orange-300 dark:bg-orange-800"></div>
</div>
</div>
</div>
</div>
<!-- 空状态蓝色主题 -->
<div
v-else
class="p-[24px] rounded-[8px] border-2 border-dashed border-blue-200 bg-blue-50/40 text-center dark:border-blue-900/40 dark:bg-blue-950/10"
>
<div class="gap-[10px] flex flex-col items-center">
<IconifyIcon icon="lucide:plus" class="text-[28px] text-blue-400 dark:text-blue-300" />
<div class="text-blue-600 dark:text-blue-300">
<p class="text-[13px] font-medium mb-[2px]">暂无附加条件</p>
<p class="text-[12px]">定时触发时将直接执行动作</p>
</div>
</div>
</div>
</div>
</template>

View File

@ -0,0 +1,587 @@
<!-- JSON参数输入组件 - 通用版本 -->
<script setup lang="ts">
import type { JsonParamsInputType } from '@vben/constants';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import {
IoTDataSpecsDataTypeEnum,
JSON_PARAMS_EXAMPLE_VALUES,
JSON_PARAMS_INPUT_CONSTANTS,
JSON_PARAMS_INPUT_ICONS,
JsonParamsInputTypeEnum,
} from '@vben/constants';
import { IconifyIcon } from '@vben/icons';
import { useVModel } from '@vueuse/core';
import { ElButton, ElInput, ElPopover, ElTag } from 'element-plus';
/** JSON参数输入组件 - 通用版本 */
defineOptions({ name: 'JsonParamsInput' });
const props = withDefaults(defineProps<Props>(), {
type: JsonParamsInputTypeEnum.SERVICE,
placeholder: JSON_PARAMS_INPUT_CONSTANTS.PLACEHOLDER,
});
const emit = defineEmits<Emits>();
interface JsonParamsConfig {
//
service?: {
inputParams?: any[];
name: string;
};
//
event?: {
name: string;
outputParams?: any[];
};
//
properties?: any[];
//
custom?: {
name: string;
params: any[];
};
}
interface Props {
modelValue: string;
config: JsonParamsConfig;
type?: JsonParamsInputType;
placeholder?: string;
}
interface Emits {
(e: 'update:modelValue', value: string): void;
}
const localValue = useVModel(props, 'modelValue', emit, {
defaultValue: '',
});
const paramsJson = ref(''); // JSON
const jsonError = ref(''); // JSON
//
const paramsList = computed(() => {
switch (props.type) {
case JsonParamsInputTypeEnum.CUSTOM: {
return props.config?.custom?.params || [];
}
case JsonParamsInputTypeEnum.EVENT: {
return props.config?.event?.outputParams || [];
}
case JsonParamsInputTypeEnum.PROPERTY: {
return props.config?.properties || [];
}
case JsonParamsInputTypeEnum.SERVICE: {
return props.config?.service?.inputParams || [];
}
default: {
return [];
}
}
});
//
const title = computed(() => {
switch (props.type) {
case JsonParamsInputTypeEnum.CUSTOM: {
return JSON_PARAMS_INPUT_CONSTANTS.TITLES.CUSTOM(
props.config?.custom?.name,
);
}
case JsonParamsInputTypeEnum.EVENT: {
return JSON_PARAMS_INPUT_CONSTANTS.TITLES.EVENT(
props.config?.event?.name,
);
}
case JsonParamsInputTypeEnum.PROPERTY: {
return JSON_PARAMS_INPUT_CONSTANTS.TITLES.PROPERTY;
}
case JsonParamsInputTypeEnum.SERVICE: {
return JSON_PARAMS_INPUT_CONSTANTS.TITLES.SERVICE(
props.config?.service?.name,
);
}
default: {
return JSON_PARAMS_INPUT_CONSTANTS.TITLES.DEFAULT;
}
}
});
//
const titleIcon = computed(() => {
switch (props.type) {
case JsonParamsInputTypeEnum.CUSTOM: {
return JSON_PARAMS_INPUT_ICONS.TITLE_ICONS.CUSTOM;
}
case JsonParamsInputTypeEnum.EVENT: {
return JSON_PARAMS_INPUT_ICONS.TITLE_ICONS.EVENT;
}
case JsonParamsInputTypeEnum.PROPERTY: {
return JSON_PARAMS_INPUT_ICONS.TITLE_ICONS.PROPERTY;
}
case JsonParamsInputTypeEnum.SERVICE: {
return JSON_PARAMS_INPUT_ICONS.TITLE_ICONS.SERVICE;
}
default: {
return JSON_PARAMS_INPUT_ICONS.TITLE_ICONS.DEFAULT;
}
}
});
//
const paramsIcon = computed(() => {
switch (props.type) {
case JsonParamsInputTypeEnum.CUSTOM: {
return JSON_PARAMS_INPUT_ICONS.PARAMS_ICONS.CUSTOM;
}
case JsonParamsInputTypeEnum.EVENT: {
return JSON_PARAMS_INPUT_ICONS.PARAMS_ICONS.EVENT;
}
case JsonParamsInputTypeEnum.PROPERTY: {
return JSON_PARAMS_INPUT_ICONS.PARAMS_ICONS.PROPERTY;
}
case JsonParamsInputTypeEnum.SERVICE: {
return JSON_PARAMS_INPUT_ICONS.PARAMS_ICONS.SERVICE;
}
default: {
return JSON_PARAMS_INPUT_ICONS.PARAMS_ICONS.DEFAULT;
}
}
});
//
const paramsLabel = computed(() => {
switch (props.type) {
case JsonParamsInputTypeEnum.CUSTOM: {
return JSON_PARAMS_INPUT_CONSTANTS.PARAMS_LABELS.CUSTOM;
}
case JsonParamsInputTypeEnum.EVENT: {
return JSON_PARAMS_INPUT_CONSTANTS.PARAMS_LABELS.EVENT;
}
case JsonParamsInputTypeEnum.PROPERTY: {
return JSON_PARAMS_INPUT_CONSTANTS.PARAMS_LABELS.PROPERTY;
}
case JsonParamsInputTypeEnum.SERVICE: {
return JSON_PARAMS_INPUT_CONSTANTS.PARAMS_LABELS.SERVICE;
}
default: {
return JSON_PARAMS_INPUT_CONSTANTS.PARAMS_LABELS.DEFAULT;
}
}
});
//
const emptyMessage = computed(() => {
switch (props.type) {
case JsonParamsInputTypeEnum.CUSTOM: {
return JSON_PARAMS_INPUT_CONSTANTS.EMPTY_MESSAGES.CUSTOM;
}
case JsonParamsInputTypeEnum.EVENT: {
return JSON_PARAMS_INPUT_CONSTANTS.EMPTY_MESSAGES.EVENT;
}
case JsonParamsInputTypeEnum.PROPERTY: {
return JSON_PARAMS_INPUT_CONSTANTS.EMPTY_MESSAGES.PROPERTY;
}
case JsonParamsInputTypeEnum.SERVICE: {
return JSON_PARAMS_INPUT_CONSTANTS.EMPTY_MESSAGES.SERVICE;
}
default: {
return JSON_PARAMS_INPUT_CONSTANTS.EMPTY_MESSAGES.DEFAULT;
}
}
});
//
// const noConfigMessage = computed(() => {
// switch (props.type) {
// case JsonParamsInputTypeEnum.CUSTOM: {
// return JSON_PARAMS_INPUT_CONSTANTS.NO_CONFIG_MESSAGES.CUSTOM;
// }
// case JsonParamsInputTypeEnum.EVENT: {
// return JSON_PARAMS_INPUT_CONSTANTS.NO_CONFIG_MESSAGES.EVENT;
// }
// case JsonParamsInputTypeEnum.PROPERTY: {
// return JSON_PARAMS_INPUT_CONSTANTS.NO_CONFIG_MESSAGES.PROPERTY;
// }
// case JsonParamsInputTypeEnum.SERVICE: {
// return JSON_PARAMS_INPUT_CONSTANTS.NO_CONFIG_MESSAGES.SERVICE;
// }
// default: {
// return JSON_PARAMS_INPUT_CONSTANTS.NO_CONFIG_MESSAGES.DEFAULT;
// }
// }
// });
/**
* 处理参数变化事件
*/
function handleParamsChange() {
try {
jsonError.value = ''; //
if (paramsJson.value.trim()) {
const parsed = JSON.parse(paramsJson.value);
localValue.value = paramsJson.value;
//
if (typeof parsed !== 'object' || parsed === null) {
jsonError.value = JSON_PARAMS_INPUT_CONSTANTS.PARAMS_MUST_BE_OBJECT;
return;
}
//
for (const param of paramsList.value) {
if (
param.required &&
(!parsed[param.identifier] || parsed[param.identifier] === '')
) {
jsonError.value = JSON_PARAMS_INPUT_CONSTANTS.PARAM_REQUIRED_ERROR(
param.name,
);
return;
}
}
} else {
localValue.value = '';
}
//
jsonError.value = '';
} catch (error) {
jsonError.value = JSON_PARAMS_INPUT_CONSTANTS.JSON_FORMAT_ERROR(
error instanceof Error
? error.message
: JSON_PARAMS_INPUT_CONSTANTS.UNKNOWN_ERROR,
);
}
}
/**
* 快速填充示例数据
*/
function fillExampleJson() {
paramsJson.value = generateExampleJson();
handleParamsChange();
}
/**
* 清空参数
*/
function clearParams() {
paramsJson.value = '';
localValue.value = '';
jsonError.value = '';
}
/**
* 获取参数类型名称
* @param dataType 数据类型
* @returns 类型名称
*/
function getParamTypeName(dataType: string) {
// 使 constants.ts getDataTypeName
const typeMap: Record<string, string> = {
[IoTDataSpecsDataTypeEnum.INT]: '整数',
[IoTDataSpecsDataTypeEnum.FLOAT]: '浮点数',
[IoTDataSpecsDataTypeEnum.DOUBLE]: '双精度',
[IoTDataSpecsDataTypeEnum.TEXT]: '字符串',
[IoTDataSpecsDataTypeEnum.BOOL]: '布尔值',
[IoTDataSpecsDataTypeEnum.ENUM]: '枚举',
[IoTDataSpecsDataTypeEnum.DATE]: '日期',
[IoTDataSpecsDataTypeEnum.STRUCT]: '结构体',
[IoTDataSpecsDataTypeEnum.ARRAY]: '数组',
};
return typeMap[dataType] || dataType;
}
/**
* 获取参数类型标签样式
* @param dataType 数据类型
* @returns 标签样式
*/
function getParamTypeTag(dataType: string) {
const tagMap: Record<string, string> = {
[IoTDataSpecsDataTypeEnum.INT]: 'primary',
[IoTDataSpecsDataTypeEnum.FLOAT]: 'success',
[IoTDataSpecsDataTypeEnum.DOUBLE]: 'success',
[IoTDataSpecsDataTypeEnum.TEXT]: 'info',
[IoTDataSpecsDataTypeEnum.BOOL]: 'warning',
[IoTDataSpecsDataTypeEnum.ENUM]: 'danger',
[IoTDataSpecsDataTypeEnum.DATE]: 'primary',
[IoTDataSpecsDataTypeEnum.STRUCT]: 'info',
[IoTDataSpecsDataTypeEnum.ARRAY]: 'warning',
};
return tagMap[dataType] || 'info';
}
/**
* 获取示例值
* @param param 参数对象
* @returns 示例值
*/
function getExampleValue(param: any) {
const exampleConfig: any =
JSON_PARAMS_EXAMPLE_VALUES[param.dataType] ||
JSON_PARAMS_EXAMPLE_VALUES.DEFAULT;
return exampleConfig.display;
}
/**
* 生成示例JSON
* @returns JSON字符串
*/
function generateExampleJson() {
if (paramsList.value.length === 0) {
return '{}';
}
const example: Record<string, any> = {};
paramsList.value.forEach((param) => {
const exampleConfig: any =
JSON_PARAMS_EXAMPLE_VALUES[param.dataType] ||
JSON_PARAMS_EXAMPLE_VALUES.DEFAULT;
example[param.identifier] = exampleConfig.value;
});
return JSON.stringify(example, null, 2);
}
/**
* 处理数据回显
* @param value 值字符串
*/
function handleDataDisplay(value: string) {
if (!value || !value.trim()) {
paramsJson.value = '';
jsonError.value = '';
return;
}
try {
// JSON
const parsed = JSON.parse(value);
paramsJson.value = JSON.stringify(parsed, null, 2);
jsonError.value = '';
} catch {
// JSON使
paramsJson.value = value;
jsonError.value = '';
}
}
//
watch(
() => localValue.value,
async (newValue, oldValue) => {
//
if (newValue === oldValue) return;
// 使 nextTick tick
await nextTick();
handleDataDisplay(newValue || '');
},
{ immediate: true },
);
//
onMounted(async () => {
await nextTick();
if (localValue.value) {
handleDataDisplay(localValue.value);
}
});
//
watch(
() => props.config,
(newConfig, oldConfig) => {
//
if (
JSON.stringify(newConfig) !== JSON.stringify(oldConfig) && //
!localValue.value
) {
paramsJson.value = '';
jsonError.value = '';
}
},
);
</script>
<template>
<!-- 参数配置 -->
<div class="w-full space-y-3">
<!-- JSON 输入框 -->
<div class="relative">
<ElInput
v-model="paramsJson"
type="textarea"
:rows="4"
:placeholder="placeholder"
@input="handleParamsChange"
:class="{ 'is-error': jsonError }"
/>
<!-- 查看详细示例弹出层 -->
<div class="absolute right-2 top-2">
<ElPopover
placement="left-start"
:width="450"
trigger="click"
:offset="8"
popper-class="json-params-detail-popover"
>
<template #reference>
<ElButton
link
type="primary"
circle
size="small"
:title="JSON_PARAMS_INPUT_CONSTANTS.VIEW_EXAMPLE_TITLE"
>
<IconifyIcon icon="ep:info-filled" />
</ElButton>
</template>
<template #default>
<!-- 弹出层内容 -->
<div class="json-params-detail-content">
<div class="mb-4 flex items-center gap-2">
<IconifyIcon :icon="titleIcon" class="text-lg text-primary" />
<span class="text-base font-bold text-primary">
{{ title }}
</span>
</div>
<div class="space-y-4">
<!-- 参数列表 -->
<div v-if="paramsList.length > 0">
<div class="mb-2 flex items-center gap-2">
<IconifyIcon
:icon="paramsIcon"
class="text-base text-primary"
/>
<span class="text-base font-bold text-primary">
{{ paramsLabel }}
</span>
</div>
<div class="ml-6 space-y-2">
<div
v-for="param in paramsList"
:key="param.identifier"
class="flex items-center justify-between rounded-lg bg-card p-2"
>
<div class="flex-1">
<div class="text-base font-bold text-primary">
{{ param.name }}
<ElTag
v-if="param.required"
size="small"
type="danger"
class="ml-1"
>
{{ JSON_PARAMS_INPUT_CONSTANTS.REQUIRED_TAG }}
</ElTag>
</div>
<div class="text-xs text-secondary">
{{ param.identifier }}
</div>
</div>
<div class="flex items-center gap-2">
<ElTag :type="getParamTypeTag(param.dataType)" size="small">
{{ getParamTypeName(param.dataType) }}
</ElTag>
<span class="text-xs text-secondary">
{{ getExampleValue(param) }}
</span>
</div>
</div>
</div>
<div class="ml-6 mt-3">
<div class="mb-1 text-xs text-secondary">
{{ JSON_PARAMS_INPUT_CONSTANTS.COMPLETE_JSON_FORMAT }}
</div>
<pre
class="border-l-3px overflow-x-auto rounded-lg border-primary bg-card p-3 text-sm text-primary"
>
<code>{{ generateExampleJson() }}</code>
</pre>
</div>
</div>
<!-- 无参数提示 -->
<div v-else>
<div class="py-4 text-center">
<p class="text-sm text-secondary">
{{ emptyMessage }}
</p>
</div>
</div>
</div>
</div>
</template>
</ElPopover>
</div>
</div>
<!-- 验证状态和错误提示 -->
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
<IconifyIcon
:icon="
jsonError
? JSON_PARAMS_INPUT_ICONS.STATUS_ICONS.ERROR
: JSON_PARAMS_INPUT_ICONS.STATUS_ICONS.SUCCESS
"
:class="jsonError ? 'text-danger' : 'text-success'"
class="text-sm"
/>
<span
:class="jsonError ? 'text-danger' : 'text-success'"
class="text-xs"
>
{{ jsonError || JSON_PARAMS_INPUT_CONSTANTS.JSON_FORMAT_CORRECT }}
</span>
</div>
<!-- 快速填充按钮 -->
<div v-if="paramsList.length > 0" class="flex items-center gap-2">
<span class="text-xs text-secondary">
{{ JSON_PARAMS_INPUT_CONSTANTS.QUICK_FILL_LABEL }}
</span>
<ElButton size="small" type="primary" plain @click="fillExampleJson">
{{ JSON_PARAMS_INPUT_CONSTANTS.EXAMPLE_DATA_BUTTON }}
</ElButton>
<ElButton size="small" type="danger" @click="clearParams">
{{ JSON_PARAMS_INPUT_CONSTANTS.CLEAR_BUTTON }}
</ElButton>
</div>
</div>
</div>
</template>
<style scoped>
/* 弹出层内容样式 */
.json-params-detail-content {
padding: 4px 0;
}
/* 弹出层自定义样式 */
:global(.json-params-detail-popover) {
max-width: 500px !important;
}
:global(.json-params-detail-popover .el-popover__content) {
padding: 16px !important;
}
/* JSON 代码块样式 */
.json-params-detail-content pre {
max-height: 200px;
overflow-y: auto;
}
</style>

View File

@ -0,0 +1,302 @@
<!-- 值输入组件 -->
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import {
IoTDataSpecsDataTypeEnum,
IotRuleSceneTriggerConditionParameterOperatorEnum,
} from '@vben/constants';
import { IconifyIcon } from '@vben/icons';
import { useVModel } from '@vueuse/core';
import {
ElDatePicker,
ElInput,
ElInputNumber,
ElOption,
ElSelect,
ElTag,
ElTooltip,
} from 'element-plus';
/** 值输入组件 */
defineOptions({ name: 'ValueInput' });
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
interface Props {
modelValue?: string;
propertyType?: string;
operator?: string;
propertyConfig?: any;
}
interface Emits {
(e: 'update:modelValue', value: string): void;
}
const localValue = useVModel(props, 'modelValue', emit, {
defaultValue: '',
});
const rangeStart = ref(''); //
const rangeEnd = ref(''); //
const dateValue = ref(''); //
const numberValue = ref<number>(); //
/** 计算属性:枚举选项 */
const enumOptions = computed(() => {
if (props.propertyConfig?.enum) {
return props.propertyConfig.enum.map((item: any) => ({
label: item.name || item.label || item.value,
value: item.value,
}));
}
return [];
});
/** 计算属性:列表预览 */
const listPreview = computed(() => {
if (
props.operator ===
IotRuleSceneTriggerConditionParameterOperatorEnum.IN.value &&
localValue.value
) {
return localValue.value
.split(',')
.map((item) => item.trim())
.filter(Boolean);
}
return [];
});
/** 判断是否为数字类型 */
function isNumericType() {
return [
IoTDataSpecsDataTypeEnum.DOUBLE,
IoTDataSpecsDataTypeEnum.FLOAT,
IoTDataSpecsDataTypeEnum.INT,
].includes((props.propertyType || '') as any);
}
/** 获取输入框类型 */
function getInputType() {
switch (props.propertyType) {
case IoTDataSpecsDataTypeEnum.DOUBLE:
case IoTDataSpecsDataTypeEnum.FLOAT:
case IoTDataSpecsDataTypeEnum.INT: {
return 'number';
}
default: {
return 'text';
}
}
}
/** 获取占位符文本 */
function getPlaceholder() {
const typeMap: Record<string, string> = {
[IoTDataSpecsDataTypeEnum.TEXT]: '请输入字符串',
[IoTDataSpecsDataTypeEnum.INT]: '请输入整数',
[IoTDataSpecsDataTypeEnum.FLOAT]: '请输入浮点数',
[IoTDataSpecsDataTypeEnum.DOUBLE]: '请输入双精度数',
[IoTDataSpecsDataTypeEnum.STRUCT]: '请输入 JSON 格式数据',
[IoTDataSpecsDataTypeEnum.ARRAY]: '请输入数组格式数据',
};
return typeMap[props.propertyType || ''] || '请输入值';
}
/** 获取数字精度 */
function getPrecision() {
return props.propertyType === IoTDataSpecsDataTypeEnum.INT ? 0 : 2;
}
/** 获取数字步长 */
function getStep() {
return props.propertyType === IoTDataSpecsDataTypeEnum.INT ? 1 : 0.1;
}
/** 获取最小值 */
function getMin() {
return props.propertyConfig?.min || undefined;
}
/** 获取最大值 */
function getMax() {
return props.propertyConfig?.max || undefined;
}
/** 处理范围变化事件 */
function handleRangeChange() {
localValue.value =
rangeStart.value && rangeEnd.value
? `${rangeStart.value},${rangeEnd.value}`
: '';
}
/** 处理日期变化事件 */
function handleDateChange(value: any) {
localValue.value = value || '';
}
/** 处理数字变化事件 */
function handleNumberChange(value: number | undefined) {
localValue.value = value?.toString() || '';
}
/** 监听操作符变化 */
watch(
() => props.operator,
() => {
localValue.value = '';
rangeStart.value = '';
rangeEnd.value = '';
dateValue.value = '';
numberValue.value = undefined;
},
);
</script>
<template>
<div class="w-full min-w-0">
<!-- 布尔值选择 -->
<ElSelect
v-if="propertyType === IoTDataSpecsDataTypeEnum.BOOL"
v-model="localValue"
placeholder="请选择布尔值"
class="w-full!"
>
<ElOption label="真 (true)" :value="true" />
<ElOption label="假 (false)" :value="false" />
</ElSelect>
<!-- 枚举值选择 -->
<ElSelect
v-else-if="
propertyType === IoTDataSpecsDataTypeEnum.ENUM && enumOptions.length > 0
"
v-model="localValue"
placeholder="请选择枚举值"
class="w-full!"
>
<ElOption
v-for="option in enumOptions"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</ElSelect>
<!-- 范围输入 (between 操作符) -->
<div
v-else-if="
operator ===
IotRuleSceneTriggerConditionParameterOperatorEnum.BETWEEN.value
"
class="w-full! flex items-center gap-2"
>
<ElInput
v-model="rangeStart"
:type="getInputType()"
placeholder="最小值"
@input="handleRangeChange"
class="min-w-0 flex-1"
style="width: auto !important"
/>
<span class="whitespace-nowrap text-xs text-secondary"> </span>
<ElInput
v-model="rangeEnd"
:type="getInputType()"
placeholder="最大值"
@input="handleRangeChange"
class="min-w-0 flex-1"
/>
</div>
<!-- 列表输入 (in 操作符) -->
<div
v-else-if="
operator === IotRuleSceneTriggerConditionParameterOperatorEnum.IN.value
"
class="w-full!"
>
<ElInput
v-model="localValue"
placeholder="请输入值列表,用逗号分隔"
class="w-full!"
>
<template #suffix>
<ElTooltip content="多个值用逗号分隔1,2,3" placement="top">
<IconifyIcon
icon="ep:question-filled"
class="cursor-help text-gray-400"
/>
</ElTooltip>
</template>
</ElInput>
<div
v-if="listPreview.length > 0"
class="mt-2 flex flex-wrap items-center gap-1"
>
<span class="text-xs text-secondary"> 解析结果 </span>
<ElTag
v-for="(item, index) in listPreview"
:key="index"
size="small"
class="m-0"
>
{{ item }}
</ElTag>
</div>
</div>
<!-- 日期时间输入 -->
<ElDatePicker
v-else-if="propertyType === IoTDataSpecsDataTypeEnum.DATE"
v-model="dateValue"
type="datetime"
placeholder="请选择日期时间"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
@change="handleDateChange"
class="w-full!"
/>
<!-- 数字输入 -->
<ElInputNumber
v-else-if="isNumericType()"
v-model="numberValue"
:precision="getPrecision()"
:step="getStep()"
:min="getMin()"
:max="getMax()"
:controls="false"
placeholder="请输入数值"
@change="handleNumberChange"
class="w-full!"
/>
<!-- 文本输入 -->
<ElInput
v-else
v-model="localValue"
:type="getInputType()"
:placeholder="getPlaceholder()"
class="w-full!"
>
<template #suffix>
<ElTooltip
v-if="propertyConfig?.unit"
:content="`单位:${propertyConfig.unit}`"
placement="top"
>
<span class="px-1 text-xs text-secondary">
{{ propertyConfig.unit }}
</span>
</ElTooltip>
</template>
</ElInput>
</div>
</template>

View File

@ -0,0 +1,312 @@
<!-- 执行器配置组件 -->
<script setup lang="ts">
import type { Action } from '#/api/iot/rule/scene';
import {
getActionTypeLabel,
getActionTypeOptions,
IotRuleSceneActionTypeEnum,
} from '@vben/constants';
import { IconifyIcon } from '@vben/icons';
import { useVModel } from '@vueuse/core';
import {
ElButton,
ElCard,
ElEmpty,
ElFormItem,
ElOption,
ElSelect,
ElTag,
} from 'element-plus';
import AlertConfig from '../configs/alert-config.vue';
import DeviceControlConfig from '../configs/device-control-config.vue';
/** 执行器配置组件 */
defineOptions({ name: 'ActionSection' });
const props = defineProps<{
actions: Action[];
}>();
const emit = defineEmits<{
(e: 'update:actions', value: Action[]): void;
}>();
const actions = useVModel(props, 'actions', emit);
/** 获取执行器标签类型(用于 el-tag 的 type 属性) */
function getActionTypeTag(
type: number,
): 'danger' | 'info' | 'primary' | 'success' | 'warning' {
const actionTypeTags: Record<
number,
'danger' | 'info' | 'primary' | 'success' | 'warning'
> = {
[IotRuleSceneActionTypeEnum.DEVICE_PROPERTY_SET]: 'primary',
[IotRuleSceneActionTypeEnum.DEVICE_SERVICE_INVOKE]: 'success',
[IotRuleSceneActionTypeEnum.ALERT_TRIGGER]: 'danger',
[IotRuleSceneActionTypeEnum.ALERT_RECOVER]: 'warning',
} as const;
return actionTypeTags[type] || 'info';
}
/** 判断是否为设备执行器类型 */
function isDeviceAction(type: number): boolean {
const deviceActionTypes = [
IotRuleSceneActionTypeEnum.DEVICE_PROPERTY_SET,
IotRuleSceneActionTypeEnum.DEVICE_SERVICE_INVOKE,
] as number[];
return deviceActionTypes.includes(type);
}
/** 判断是否为告警执行器类型 */
function isAlertAction(type: number): boolean {
const alertActionTypes = [
IotRuleSceneActionTypeEnum.ALERT_TRIGGER,
IotRuleSceneActionTypeEnum.ALERT_RECOVER,
] as number[];
return alertActionTypes.includes(type);
}
/**
* 创建默认的执行器数据
* @returns 默认执行器对象
*/
function createDefaultActionData(): Action {
return {
type: IotRuleSceneActionTypeEnum.DEVICE_PROPERTY_SET, //
productId: undefined,
deviceId: undefined,
identifier: undefined, // 使
params: undefined,
alertConfigId: undefined,
};
}
/**
* 添加执行器
*/
function addAction() {
const newAction = createDefaultActionData();
actions.value.push(newAction);
}
/**
* 删除执行器
* @param index 执行器索引
*/
function removeAction(index: number) {
actions.value.splice(index, 1);
}
/**
* 更新执行器类型
* @param index 执行器索引
* @param type 执行器类型
*/
function updateActionType(index: number, type: number) {
actions.value[index]!.type = type;
onActionTypeChange(actions.value[index] as Action, type);
}
/**
* 更新执行器
* @param index 执行器索引
* @param action 执行器对象
*/
function updateAction(index: number, action: Action) {
actions.value[index] = action;
}
/**
* 更新告警配置
* @param index 执行器索引
* @param alertConfigId 告警配置ID
*/
function updateActionAlertConfig(index: number, alertConfigId?: number) {
actions.value[index]!.alertConfigId = alertConfigId;
if (actions.value[index]) {
actions.value[index].alertConfigId = alertConfigId;
}
}
/**
* 监听执行器类型变化
* @param action 执行器对象
* @param type 执行器类型
*/
function onActionTypeChange(action: Action, type: any) {
//
if (isDeviceAction(type)) {
//
action.alertConfigId = undefined;
if (!(action as any).params) {
(action as any).params = '';
}
// identifier
if (action.identifier && type !== (action as any).type) {
action.identifier = undefined;
}
} else if (isAlertAction(type)) {
action.productId = undefined;
action.deviceId = undefined;
action.identifier = undefined; //
action.params = undefined;
action.alertConfigId = undefined;
}
}
</script>
<template>
<ElCard class="rounded-lg border border-primary" shadow="never">
<template #header>
<div class="flex items-center justify-between">
<div class="gap-8px flex items-center">
<IconifyIcon icon="ep:setting" class="text-18px text-primary" />
<span class="text-16px font-600 text-primary"> 执行器配置 </span>
<ElTag size="small" type="info"> {{ actions.length }} 个执行器 </ElTag>
</div>
<div class="gap-8px flex items-center">
<ElButton type="primary" size="small" @click="addAction">
<IconifyIcon icon="ep:plus" />
添加执行器
</ElButton>
</div>
</div>
</template>
<div class="p-0">
<!-- 空状态 -->
<div v-if="actions.length === 0">
<ElEmpty description="暂无执行器配置">
<ElButton type="primary" @click="addAction">
<IconifyIcon icon="ep:plus" />
添加第一个执行器
</ElButton>
</ElEmpty>
</div>
<!-- 执行器列表 -->
<div v-else class="space-y-24px">
<div
v-for="(action, index) in actions"
:key="`action-${index}`"
class="rounded-lg border-2 border-blue-200 bg-blue-50 shadow-sm transition-shadow hover:shadow-md"
>
<!-- 执行器头部 - 蓝色主题 -->
<div
class="flex items-center justify-between rounded-t-lg border-b border-blue-200 bg-gradient-to-r from-blue-50 to-sky-50 p-4"
>
<div class="gap-12px flex items-center">
<div
class="font-600 flex items-center gap-2 text-base text-blue-700"
>
<div
class="flex size-6 items-center justify-center rounded-full bg-blue-500 text-xs font-bold text-white"
>
{{ index + 1 }}
</div>
<span>执行器 {{ index + 1 }}</span>
</div>
<ElTag
:type="getActionTypeTag(action.type as any)"
size="small"
class="font-500"
>
{{ getActionTypeLabel(action.type as any) }}
</ElTag>
</div>
<div class="gap-8px flex items-center">
<ElButton
v-if="actions.length > 1"
type="danger"
size="small"
link
@click="removeAction(index)"
class="hover:bg-red-50"
>
<IconifyIcon icon="lucide:trash-2" />
删除
</ElButton>
</div>
</div>
<!-- 执行器内容区域 -->
<div class="p-16px space-y-16px">
<!-- 执行类型选择 -->
<div class="w-full">
<ElFormItem label="执行类型" required>
<ElSelect
v-model="action.type"
@change="
(value: any) => {
updateActionType(index, value);
onActionTypeChange(action, value);
}
"
placeholder="请选择执行类型"
class="w-full"
>
<ElOption
v-for="option in getActionTypeOptions()"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</ElSelect>
</ElFormItem>
</div>
<!-- 设备控制配置 -->
<DeviceControlConfig
v-if="isDeviceAction(action.type as any)"
:model-value="action"
@update:model-value="(value) => updateAction(index, value)"
/>
<!-- 告警配置 - 只有恢复告警时才显示 -->
<AlertConfig
v-if="
action.type ===
IotRuleSceneActionTypeEnum.ALERT_RECOVER
"
:model-value="action.alertConfigId"
@update:model-value="
(value) => updateActionAlertConfig(index, value)
"
/>
<!-- 触发告警提示 - 触发告警时显示 -->
<div
v-if="
action.type ===
IotRuleSceneActionTypeEnum.ALERT_TRIGGER
"
class="bg-fill-color-blank rounded-lg border border-border p-4"
>
<div class="mb-2 flex items-center gap-2">
<IconifyIcon icon="ep:warning" class="text-base text-warning" />
<span class="font-600 text-sm text-primary">触发告警</span>
<ElTag size="small" type="warning">自动执行</ElTag>
</div>
<div class="text-xs leading-relaxed text-secondary">
当触发条件满足时系统将自动发送告警通知可在菜单 [告警中心 ->
告警配置] 管理
</div>
</div>
</div>
</div>
</div>
<!-- 添加提示 -->
<div v-if="actions.length > 0" class="py-16px text-center">
<ElButton type="primary" plain @click="addAction">
<IconifyIcon icon="ep:plus" />
继续添加执行器
</ElButton>
</div>
</div>
</ElCard>
</template>

View File

@ -0,0 +1,104 @@
<!-- 基础信息配置组件 -->
<script setup lang="ts">
import type { IotSceneRule } from '#/api/iot/rule/scene';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { IconifyIcon } from '@vben/icons';
import { useVModel } from '@vueuse/core';
import {
ElCard,
ElCol,
ElFormItem,
ElInput,
ElRadio,
ElRadioGroup,
ElRow,
} from 'element-plus';
import { DictTag } from '#/components/dict-tag';
/** 基础信息配置组件 */
defineOptions({ name: 'BasicInfoSection' });
const props = defineProps<{
modelValue: IotSceneRule;
rules?: any;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: IotSceneRule): void;
}>();
const formData = useVModel(props, 'modelValue', emit); //
</script>
<template>
<ElCard class="rounded-8px mb-10px border border-primary" shadow="never">
<template #header>
<div class="flex items-center justify-between">
<div class="gap-8px flex items-center">
<IconifyIcon icon="ep:info-filled" class="text-18px text-primary" />
<span class="text-16px font-600 text-primary">基础信息</span>
</div>
<div class="gap-8px flex items-center">
<DictTag :type="DICT_TYPE.COMMON_STATUS" :value="formData.status" />
</div>
</div>
</template>
<div class="p-0">
<ElRow :gutter="24" class="mb-24px">
<ElCol :span="12">
<ElFormItem label="场景名称" prop="name" required>
<ElInput
v-model="formData.name"
placeholder="请输入场景名称"
:maxlength="50"
show-word-limit
clearable
/>
</ElFormItem>
</ElCol>
<ElCol :span="12">
<ElFormItem label="场景状态" prop="status" required>
<ElRadioGroup v-model="formData.status">
<ElRadio
v-for="(dict, index) in getDictOptions(
DICT_TYPE.COMMON_STATUS,
'number',
)"
:key="index"
:label="dict.value"
>
{{ dict.label }}
</ElRadio>
</ElRadioGroup>
</ElFormItem>
</ElCol>
</ElRow>
<ElFormItem label="场景描述" prop="description">
<ElInput
v-model="formData.description"
type="textarea"
placeholder="请输入场景描述(可选)"
:rows="3"
:maxlength="200"
show-word-limit
resize="none"
/>
</ElFormItem>
</div>
</ElCard>
</template>
<style scoped>
:deep(.el-form-item) {
margin-bottom: 20px;
}
:deep(.el-form-item:last-child) {
margin-bottom: 0;
}
</style>

View File

@ -0,0 +1,254 @@
<script setup lang="ts">
import type { Trigger } from '#/api/iot/rule/scene';
import { onMounted } from 'vue';
import {
getTriggerTypeLabel,
IotRuleSceneTriggerTypeEnum,
isDeviceTrigger,
} from '@vben/constants';
import { IconifyIcon } from '@vben/icons';
import { useVModel } from '@vueuse/core';
import {
ElButton,
ElCard,
ElEmpty,
ElFormItem,
ElTag,
} from 'element-plus';
import { CronTab } from '#/components/cron-tab';
import DeviceTriggerConfig from '../configs/device-trigger-config.vue';
/** 触发器配置组件 */
defineOptions({ name: 'TriggerSection' });
const props = defineProps<{
triggers: Trigger[];
}>();
const emit = defineEmits<{
(e: 'update:triggers', value: Trigger[]): void;
}>();
const triggers = useVModel(props, 'triggers', emit);
/** 获取触发器标签类型(用于 el-tag 的 type 属性) */
function getTriggerTagType(
type: number,
): 'danger' | 'info' | 'primary' | 'success' | 'warning' {
if (type === IotRuleSceneTriggerTypeEnum.TIMER) {
return 'warning';
}
return isDeviceTrigger(type) ? 'success' : 'info';
}
/** 添加触发器 */
function addTrigger() {
const newTrigger: Trigger = {
type: IotRuleSceneTriggerTypeEnum.DEVICE_STATE_UPDATE,
productId: undefined,
deviceId: undefined,
identifier: undefined,
operator: undefined,
value: undefined,
cronExpression: undefined,
conditionGroups: [], //
};
triggers.value.push(newTrigger);
}
/**
* 删除触发器
* @param index 触发器索引
*/
function removeTrigger(index: number) {
if (triggers.value.length > 1) {
triggers.value.splice(index, 1);
}
}
/**
* 更新触发器类型
* @param index 触发器索引
* @param type 触发器类型
*/
function updateTriggerType(index: number, type: number) {
triggers.value[index]!.type = type;
onTriggerTypeChange(index, type);
}
/**
* 更新触发器设备配置
* @param index 触发器索引
* @param newTrigger 新的触发器对象
*/
function updateTriggerDeviceConfig(index: number, newTrigger: Trigger) {
triggers.value[index] = newTrigger;
}
/**
* 更新触发器 CRON 配置
* @param index 触发器索引
* @param cronExpression CRON 表达式
*/
function updateTriggerCronConfig(index: number, cronExpression?: string) {
triggers.value[index]!.cronExpression = cronExpression;
}
/**
* 处理触发器类型变化事件
* @param index 触发器索引
* @param _ 触发器类型未使用
*/
function onTriggerTypeChange(index: number, _: number) {
const triggerItem = triggers.value[index]!;
triggerItem.productId = undefined;
triggerItem.deviceId = undefined;
triggerItem.identifier = undefined;
triggerItem.operator = undefined;
triggerItem.value = undefined;
triggerItem.cronExpression = undefined;
triggerItem.conditionGroups = [];
}
/** 初始化:确保至少有一个触发器 */
onMounted(() => {
if (triggers.value.length === 0) {
addTrigger();
}
});
</script>
<template>
<ElCard class="rounded-8px mb-10px border border-primary" shadow="never">
<template #header>
<div class="flex items-center justify-between">
<div class="gap-8px flex items-center">
<IconifyIcon icon="ep:lightning" class="text-18px text-primary" />
<span class="text-16px font-600 text-primary">触发器配置</span>
<ElTag size="small" type="info"> {{ triggers.length }} 个触发器 </ElTag>
</div>
<ElButton type="primary" size="small" @click="addTrigger">
<IconifyIcon icon="lucide:plus" />
添加触发器
</ElButton>
</div>
</template>
<div class="p-16px space-y-24px">
<!-- 触发器列表 -->
<div v-if="triggers.length > 0" class="space-y-24px">
<div
v-for="(triggerItem, index) in triggers"
:key="`trigger-${index}`"
class="rounded-8px border-2 border-green-200 bg-green-50 shadow-sm transition-shadow hover:shadow-md"
>
<!-- 触发器头部 - 绿色主题 -->
<div
class="p-16px rounded-t-6px flex items-center justify-between border-b border-green-200 bg-gradient-to-r from-green-50 to-emerald-50"
>
<div class="gap-12px flex items-center">
<div
class="gap-8px text-16px font-600 flex items-center text-green-700"
>
<div
class="w-24px h-24px text-12px flex items-center justify-center rounded-full bg-green-500 font-bold text-white"
>
{{ index + 1 }}
</div>
<span>触发器 {{ index + 1 }}</span>
</div>
<ElTag
size="small"
:type="getTriggerTagType(triggerItem.type as any)"
class="font-500"
>
{{ getTriggerTypeLabel(triggerItem.type as any) }}
</ElTag>
</div>
<div class="gap-8px flex items-center">
<ElButton
v-if="triggers.length > 1"
type="danger"
size="small"
link
@click="removeTrigger(index)"
class="hover:bg-red-50"
>
<IconifyIcon icon="lucide:trash-2" />
删除
</ElButton>
</div>
</div>
<!-- 触发器内容区域 -->
<div class="p-16px space-y-16px">
<!-- 设备触发配置 -->
<DeviceTriggerConfig
v-if="isDeviceTrigger(triggerItem.type as any)"
:model-value="triggerItem"
:index="index"
@update:model-value="
(value) => updateTriggerDeviceConfig(index, value)
"
@trigger-type-change="(type) => updateTriggerType(index, type)"
/>
<!-- 定时触发配置 -->
<div
v-else-if="
triggerItem.type ===
IotRuleSceneTriggerTypeEnum.TIMER
"
class="gap-16px flex flex-col"
>
<div
class="gap-8px p-12px px-16px rounded-6px flex items-center border border-primary bg-background"
>
<IconifyIcon
icon="lucide:timer"
class="text-18px text-danger"
/>
<span class="text-14px font-500 text-primary">
定时触发配置
</span>
</div>
<!-- CRON 表达式配置 -->
<div
class="p-16px rounded-6px border border-primary bg-background"
>
<ElFormItem label="CRON表达式" required>
<CronTab
:model-value="triggerItem.cronExpression || '0 0 12 * * ?'"
@update:model-value="
(value) => updateTriggerCronConfig(index, value)
"
/>
</ElFormItem>
</div>
</div>
</div>
</div>
</div>
<!-- 空状态 -->
<div v-else class="py-40px text-center">
<ElEmpty description="暂无触发器">
<template #description>
<div class="space-y-8px">
<p class="text-secondary">暂无触发器配置</p>
<p class="text-12px text-primary">
请使用上方的"添加触发器"按钮来设置触发规则
</p>
</div>
</template>
</ElEmpty>
</div>
</div>
</ElCard>
</template>

View File

@ -0,0 +1,111 @@
<!-- 设备选择器组件 -->
<script setup lang="ts">
import { ref, watch } from 'vue';
import { DICT_TYPE } from '@vben/constants';
import { DEVICE_SELECTOR_OPTIONS } from '@vben/constants';
import { ElOption, ElSelect } from 'element-plus';
import { getDeviceListByProductId } from '#/api/iot/device/device';
import { DictTag } from '#/components/dict-tag';
/** 设备选择器组件 */
defineOptions({ name: 'DeviceSelector' });
const props = defineProps<{
modelValue?: number;
productId?: number;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value?: number): void;
(e: 'change', value?: number): void;
}>();
const deviceLoading = ref(false); //
const deviceList = ref<any[]>([]); //
/**
* 处理选择变化事件
* @param value 选中的设备ID
*/
function handleChange(value?: number) {
emit('update:modelValue', value);
emit('change', value);
}
/**
* 获取设备列表
*/
async function getDeviceList() {
if (!props.productId) {
deviceList.value = [];
return;
}
try {
deviceLoading.value = true;
const data = await getDeviceListByProductId(props.productId);
deviceList.value = data || [];
} catch (error) {
console.error('获取设备列表失败:', error);
deviceList.value = [];
} finally {
deviceList.value.unshift(DEVICE_SELECTOR_OPTIONS.ALL_DEVICES);
deviceLoading.value = false;
}
}
//
watch(
() => props.productId,
(newProductId) => {
if (newProductId) {
getDeviceList();
} else {
deviceList.value = [];
//
if (props.modelValue) {
emit('update:modelValue', undefined);
emit('change', undefined);
}
}
},
{ immediate: true },
);
</script>
<template>
<ElSelect
:model-value="modelValue"
@update:model-value="handleChange"
placeholder="请选择设备"
filterable
clearable
class="w-full"
:loading="deviceLoading"
:disabled="!productId"
>
<ElOption
v-for="device in deviceList"
:key="device.id"
:label="device.deviceName"
:value="device.id"
>
<div class="py-4px flex w-full items-center justify-between">
<div class="flex-1">
<div class="text-14px font-500 mb-2px text-primary">
{{ device.deviceName }}
</div>
<div class="text-12px text-primary">
{{ device.deviceKey }}
</div>
</div>
<div class="gap-4px flex items-center" v-if="device.id > 0">
<DictTag :type="DICT_TYPE.IOT_DEVICE_STATE" :value="device.state" />
</div>
</div>
</ElOption>
</ElSelect>
</template>

View File

@ -0,0 +1,278 @@
<!-- 操作符选择器组件 -->
<script setup lang="ts">
import { computed, watch } from 'vue';
import {
IoTDataSpecsDataTypeEnum,
IotRuleSceneTriggerConditionParameterOperatorEnum,
} from '@vben/constants';
import { useVModel } from '@vueuse/core';
import { ElOption, ElSelect } from 'element-plus';
/** 操作符选择器组件 */
defineOptions({ name: 'OperatorSelector' });
const props = defineProps<{
modelValue?: string;
propertyType?: string;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: string): void;
(e: 'change', value: string): void;
}>();
const localValue = useVModel(props, 'modelValue', emit);
//
const allOperators = [
{
value: IotRuleSceneTriggerConditionParameterOperatorEnum.EQUALS.value,
label: IotRuleSceneTriggerConditionParameterOperatorEnum.EQUALS.name,
symbol: '=',
description: '值完全相等时触发',
example: 'temperature = 25',
supportedTypes: [
IoTDataSpecsDataTypeEnum.INT,
IoTDataSpecsDataTypeEnum.FLOAT,
IoTDataSpecsDataTypeEnum.DOUBLE,
IoTDataSpecsDataTypeEnum.TEXT,
IoTDataSpecsDataTypeEnum.BOOL,
IoTDataSpecsDataTypeEnum.ENUM,
],
},
{
value: IotRuleSceneTriggerConditionParameterOperatorEnum.NOT_EQUALS.value,
label: IotRuleSceneTriggerConditionParameterOperatorEnum.NOT_EQUALS.name,
symbol: '≠',
description: '值不相等时触发',
example: 'power != false',
supportedTypes: [
IoTDataSpecsDataTypeEnum.INT,
IoTDataSpecsDataTypeEnum.FLOAT,
IoTDataSpecsDataTypeEnum.DOUBLE,
IoTDataSpecsDataTypeEnum.TEXT,
IoTDataSpecsDataTypeEnum.BOOL,
IoTDataSpecsDataTypeEnum.ENUM,
],
},
{
value: IotRuleSceneTriggerConditionParameterOperatorEnum.GREATER_THAN.value,
label: IotRuleSceneTriggerConditionParameterOperatorEnum.GREATER_THAN.name,
symbol: '>',
description: '值大于指定值时触发',
example: 'temperature > 30',
supportedTypes: [
IoTDataSpecsDataTypeEnum.INT,
IoTDataSpecsDataTypeEnum.FLOAT,
IoTDataSpecsDataTypeEnum.DOUBLE,
IoTDataSpecsDataTypeEnum.DATE,
],
},
{
value:
IotRuleSceneTriggerConditionParameterOperatorEnum.GREATER_THAN_OR_EQUALS
.value,
label:
IotRuleSceneTriggerConditionParameterOperatorEnum.GREATER_THAN_OR_EQUALS
.name,
symbol: '≥',
description: '值大于或等于指定值时触发',
example: 'humidity >= 80',
supportedTypes: [
IoTDataSpecsDataTypeEnum.INT,
IoTDataSpecsDataTypeEnum.FLOAT,
IoTDataSpecsDataTypeEnum.DOUBLE,
IoTDataSpecsDataTypeEnum.DATE,
],
},
{
value: IotRuleSceneTriggerConditionParameterOperatorEnum.LESS_THAN.value,
label: IotRuleSceneTriggerConditionParameterOperatorEnum.LESS_THAN.name,
symbol: '<',
description: '值小于指定值时触发',
example: 'temperature < 10',
supportedTypes: [
IoTDataSpecsDataTypeEnum.INT,
IoTDataSpecsDataTypeEnum.FLOAT,
IoTDataSpecsDataTypeEnum.DOUBLE,
IoTDataSpecsDataTypeEnum.DATE,
],
},
{
value:
IotRuleSceneTriggerConditionParameterOperatorEnum.LESS_THAN_OR_EQUALS
.value,
label:
IotRuleSceneTriggerConditionParameterOperatorEnum.LESS_THAN_OR_EQUALS
.name,
symbol: '≤',
description: '值小于或等于指定值时触发',
example: 'battery <= 20',
supportedTypes: [
IoTDataSpecsDataTypeEnum.INT,
IoTDataSpecsDataTypeEnum.FLOAT,
IoTDataSpecsDataTypeEnum.DOUBLE,
IoTDataSpecsDataTypeEnum.DATE,
],
},
{
value: IotRuleSceneTriggerConditionParameterOperatorEnum.IN.value,
label: IotRuleSceneTriggerConditionParameterOperatorEnum.IN.name,
symbol: '∈',
description: '值在指定列表中时触发',
example: 'status in [1,2,3]',
supportedTypes: [
IoTDataSpecsDataTypeEnum.INT,
IoTDataSpecsDataTypeEnum.FLOAT,
IoTDataSpecsDataTypeEnum.TEXT,
IoTDataSpecsDataTypeEnum.ENUM,
],
},
{
value: IotRuleSceneTriggerConditionParameterOperatorEnum.NOT_IN.value,
label: IotRuleSceneTriggerConditionParameterOperatorEnum.NOT_IN.name,
symbol: '∉',
description: '值不在指定列表中时触发',
example: 'status not in [1,2,3]',
supportedTypes: [
IoTDataSpecsDataTypeEnum.INT,
IoTDataSpecsDataTypeEnum.FLOAT,
IoTDataSpecsDataTypeEnum.TEXT,
IoTDataSpecsDataTypeEnum.ENUM,
],
},
{
value: IotRuleSceneTriggerConditionParameterOperatorEnum.BETWEEN.value,
label: IotRuleSceneTriggerConditionParameterOperatorEnum.BETWEEN.name,
symbol: '⊆',
description: '值在指定范围内时触发',
example: 'temperature between 20,30',
supportedTypes: [
IoTDataSpecsDataTypeEnum.INT,
IoTDataSpecsDataTypeEnum.FLOAT,
IoTDataSpecsDataTypeEnum.DOUBLE,
IoTDataSpecsDataTypeEnum.DATE,
],
},
{
value: IotRuleSceneTriggerConditionParameterOperatorEnum.NOT_BETWEEN.value,
label: IotRuleSceneTriggerConditionParameterOperatorEnum.NOT_BETWEEN.name,
symbol: '⊄',
description: '值不在指定范围内时触发',
example: 'temperature not between 20,30',
supportedTypes: [
IoTDataSpecsDataTypeEnum.INT,
IoTDataSpecsDataTypeEnum.FLOAT,
IoTDataSpecsDataTypeEnum.DOUBLE,
IoTDataSpecsDataTypeEnum.DATE,
],
},
{
value: IotRuleSceneTriggerConditionParameterOperatorEnum.LIKE.value,
label: IotRuleSceneTriggerConditionParameterOperatorEnum.LIKE.name,
symbol: '≈',
description: '字符串匹配指定模式时触发',
example: 'message like "%error%"',
supportedTypes: [IoTDataSpecsDataTypeEnum.TEXT],
},
{
value: IotRuleSceneTriggerConditionParameterOperatorEnum.NOT_NULL.value,
label: IotRuleSceneTriggerConditionParameterOperatorEnum.NOT_NULL.name,
symbol: '≠∅',
description: '值非空时触发',
example: 'data not null',
supportedTypes: [
IoTDataSpecsDataTypeEnum.INT,
IoTDataSpecsDataTypeEnum.FLOAT,
IoTDataSpecsDataTypeEnum.DOUBLE,
IoTDataSpecsDataTypeEnum.TEXT,
IoTDataSpecsDataTypeEnum.BOOL,
IoTDataSpecsDataTypeEnum.ENUM,
IoTDataSpecsDataTypeEnum.DATE,
],
},
];
//
const availableOperators = computed(() => {
if (!props.propertyType) {
return allOperators;
}
return allOperators.filter((op) =>
(op.supportedTypes as any[]).includes(props.propertyType || ''),
);
});
//
const selectedOperator = computed(() => {
return allOperators.find((op) => op.value === localValue.value);
});
/**
* 处理选择变化事件
* @param value 选中的操作符值
*/
function handleChange(value: any) {
emit('change', value);
}
/** 监听属性类型变化 */
watch(
() => props.propertyType,
() => {
//
if (
localValue.value &&
selectedOperator.value &&
!(selectedOperator.value.supportedTypes as any[]).includes(
props.propertyType || '',
)
) {
localValue.value = '';
}
},
);
</script>
<template>
<div class="w-full">
<ElSelect
v-model="localValue"
placeholder="请选择操作符"
@change="handleChange"
class="w-full"
>
<ElOption
v-for="operator in availableOperators"
:key="operator.value"
:label="operator.label"
:value="operator.value"
>
<div class="py-4px flex w-full items-center justify-between">
<div class="gap-8px flex items-center">
<div class="text-14px font-500 text-primary">
{{ operator.label }}
</div>
<div
class="text-12px px-6px py-2px rounded-4px bg-primary-light-9 font-mono text-primary"
>
{{ operator.symbol }}
</div>
</div>
<div class="text-12px text-secondary">
{{ operator.description }}
</div>
</div>
</ElOption>
</ElSelect>
</div>
</template>
<style scoped>
:deep(.el-select-dropdown__item) {
height: auto;
padding: 8px 20px;
}
</style>

View File

@ -0,0 +1,85 @@
<!-- 产品选择器组件 -->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { DICT_TYPE } from '@vben/constants';
import { ElOption, ElSelect } from 'element-plus';
import { getSimpleProductList } from '#/api/iot/product/product';
import { DictTag } from '#/components/dict-tag';
/** 产品选择器组件 */
defineOptions({ name: 'ProductSelector' });
defineProps<{
modelValue?: number;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value?: number): void;
(e: 'change', value?: number): void;
}>();
const productLoading = ref(false); //
const productList = ref<any[]>([]); //
/**
* 处理选择变化事件
* @param value 选中的产品 ID
*/
function handleChange(value?: number) {
emit('update:modelValue', value);
emit('change', value);
}
/** 获取产品列表 */
async function getProductList() {
try {
productLoading.value = true;
const data = await getSimpleProductList();
productList.value = data || [];
} catch (error) {
console.error('获取产品列表失败:', error);
productList.value = [];
} finally {
productLoading.value = false;
}
}
//
onMounted(() => {
getProductList();
});
</script>
<template>
<ElSelect
:model-value="modelValue"
@update:model-value="handleChange"
placeholder="请选择产品"
filterable
clearable
class="w-full"
:loading="productLoading"
>
<ElOption
v-for="product in productList"
:key="product.id"
:label="product.name"
:value="product.id"
>
<div class="py-4px flex w-full items-center justify-between">
<div class="flex-1">
<div class="text-14px font-500 mb-2px text-primary">
{{ product.name }}
</div>
<div class="text-12px text-secondary">
{{ product.productKey }}
</div>
</div>
<DictTag :type="DICT_TYPE.COMMON_STATUS" :value="product.status" />
</div>
</ElOption>
</ElSelect>
</template>

View File

@ -0,0 +1,465 @@
<!-- 属性选择器组件 -->
<script setup lang="ts">
import type {
ThingModelApi,
ThingModelEvent,
ThingModelProperty,
ThingModelService,
} from '#/api/iot/thingmodel';
import { computed, ref, watch } from 'vue';
import {
getAccessModeLabel,
getDataTypeName,
getEventTypeLabel,
getThingModelServiceCallTypeLabel,
IotRuleSceneTriggerTypeEnum,
IoTThingModelTypeEnum,
THING_MODEL_GROUP_LABELS,
} from '@vben/constants';
import { IconifyIcon } from '@vben/icons';
import { useVModel } from '@vueuse/core';
import {
ElButton,
ElOption,
ElOptionGroup,
ElPopover,
ElSelect,
ElTag,
} from 'element-plus';
import { getThingModelTSLByProductId } from '#/api/iot/thingmodel';
/** 属性选择器组件 */
defineOptions({ name: 'PropertySelector' });
const props = defineProps<{
deviceId?: number;
modelValue?: string;
productId?: number;
triggerType: number;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: string): void;
(e: 'change', value: { config: any; type: string }): void;
}>();
// TODO
/** 属性选择器内部使用的统一数据结构 */
interface PropertySelectorItem {
identifier: string;
name: string;
description?: string;
dataType: string;
type: number; // IoTThingModelTypeEnum
accessMode?: string;
required?: boolean;
unit?: string;
range?: string;
eventType?: string;
callType?: string;
inputParams?: ThingModelParam[];
outputParams?: ThingModelParam[];
property?: ThingModelProperty;
event?: ThingModelEvent;
service?: ThingModelService;
}
const localValue = useVModel(props, 'modelValue', emit);
const loading = ref(false); //
const propertyList = ref<ThingModelApi.Property[]>([]); //
const thingModelTSL = ref<null | ThingModelApi.ThingModel>(null); // TSL
//
const propertyGroups = computed(() => {
const groups: { label: string; options: any[] }[] = [];
if (props.triggerType === IotRuleSceneTriggerTypeEnum.DEVICE_PROPERTY_POST) {
groups.push({
label: THING_MODEL_GROUP_LABELS.PROPERTY,
options: propertyList.value.filter(
(p) => p.type === IoTThingModelTypeEnum.PROPERTY,
),
});
}
if (props.triggerType === IotRuleSceneTriggerTypeEnum.DEVICE_EVENT_POST) {
groups.push({
label: THING_MODEL_GROUP_LABELS.EVENT,
options: propertyList.value.filter(
(p) => p.type === IoTThingModelTypeEnum.EVENT,
),
});
}
if (props.triggerType === IotRuleSceneTriggerTypeEnum.DEVICE_SERVICE_INVOKE) {
groups.push({
label: THING_MODEL_GROUP_LABELS.SERVICE,
options: propertyList.value.filter(
(p) => p.type === IoTThingModelTypeEnum.SERVICE,
),
});
}
return groups.filter((group) => group.options.length > 0);
});
//
const selectedProperty = computed(() => {
return propertyList.value.find((p) => p.identifier === localValue.value);
});
/**
* 处理选择变化事件
* @param value 选中的属性标识符
*/
function handleChange(value: any) {
const property = propertyList.value.find((p) => p.identifier === value);
if (property) {
emit('change', {
type: property.dataType,
config: property,
});
}
}
/**
* 获取物模型 TSL 数据
*/
async function fetchThingModelTSL() {
if (!props.productId) {
thingModelTSL.value = null;
propertyList.value = [];
return;
}
loading.value = true;
try {
const tslData = await getThingModelTSLByProductId(props.productId);
if (tslData) {
thingModelTSL.value = tslData;
parseThingModelData();
} else {
console.error('获取物模型TSL失败: 返回数据为空');
propertyList.value = [];
}
} catch (error) {
console.error('获取物模型TSL失败:', error);
propertyList.value = [];
} finally {
loading.value = false;
}
}
/** 解析物模型 TSL 数据 */
function parseThingModelData() {
const tsl = thingModelTSL.value;
const properties: PropertySelectorItem[] = [];
if (!tsl) {
propertyList.value = properties;
return;
}
//
if (tsl.properties && Array.isArray(tsl.properties)) {
tsl.properties.forEach((prop) => {
properties.push({
identifier: prop.identifier,
name: prop.name,
description: prop.description,
dataType: prop.dataType,
type: IoTThingModelTypeEnum.PROPERTY,
accessMode: prop.accessMode,
required: prop.required,
unit: getPropertyUnit(prop),
range: getPropertyRange(prop),
property: prop,
});
});
}
//
if (tsl.events && Array.isArray(tsl.events)) {
tsl.events.forEach((event) => {
properties.push({
identifier: event.identifier,
name: event.name,
description: event.description,
dataType: 'struct',
type: IoTThingModelTypeEnum.EVENT,
eventType: event.type,
required: event.required,
outputParams: event.outputParams,
event,
});
});
}
//
if (tsl.services && Array.isArray(tsl.services)) {
tsl.services.forEach((service) => {
properties.push({
identifier: service.identifier,
name: service.name,
description: service.description,
dataType: 'struct',
type: IoTThingModelTypeEnum.SERVICE,
callType: service.callType,
required: service.required,
inputParams: service.inputParams,
outputParams: service.outputParams,
service,
});
});
}
propertyList.value = properties;
}
/**
* 获取属性单位
* @param property 属性对象
* @returns 属性单位
*/
function getPropertyUnit(property: any) {
if (!property) return undefined;
//
if (property.dataSpecs && property.dataSpecs.unit) {
return property.dataSpecs.unit;
}
return undefined;
}
/**
* 获取属性范围描述
* @param property 属性对象
* @returns 属性范围描述
*/
function getPropertyRange(property: any) {
if (!property) return undefined;
//
if (property.dataSpecs) {
const specs = property.dataSpecs;
if (specs.min !== undefined && specs.max !== undefined) {
return `${specs.min}~${specs.max}`;
}
}
//
if (property.dataSpecsList && Array.isArray(property.dataSpecsList)) {
return property.dataSpecsList
.map((item: any) => `${item.name}(${item.value})`)
.join(', ');
}
return undefined;
}
/** 监听产品变化 */
watch(
() => props.productId,
() => {
fetchThingModelTSL();
},
{ immediate: true },
);
/** 监听触发类型变化 */
watch(
() => props.triggerType,
() => {
localValue.value = '';
},
);
</script>
<template>
<div class="gap-8px flex items-center">
<ElSelect
v-model="localValue"
placeholder="请选择监控项"
filterable
clearable
@change="handleChange"
class="!w-150px"
:loading="loading"
>
<ElOptionGroup
v-for="group in propertyGroups"
:key="group.label"
:label="group.label"
>
<ElOption
v-for="property in group.options"
:key="property.identifier"
:label="property.name"
:value="property.identifier"
>
<div class="py-2px flex w-full items-center justify-between">
<span class="text-14px font-500 flex-1 truncate text-primary">
{{ property.name }}
</span>
<ElTag size="small" class="ml-8px flex-shrink-0">
{{ property.identifier }}
</ElTag>
</div>
</ElOption>
</ElOptionGroup>
</ElSelect>
<!-- 属性详情弹出层 -->
<ElPopover
v-if="selectedProperty"
placement="right-start"
:width="350"
trigger="click"
:offset="8"
popper-class="property-detail-popover"
>
<template #reference>
<ElButton
type="primary"
link
circle
size="small"
class="flex-shrink-0"
title="查看属性详情"
>
<IconifyIcon icon="ep:info-filled" />
</ElButton>
</template>
<template #default>
<!-- 弹出层内容 -->
<div class="property-detail-content">
<div class="gap-8px mb-12px flex items-center">
<IconifyIcon icon="ep:info-filled" class="text-16px text-info" />
<span class="text-14px font-500 text-primary">
{{ selectedProperty.name }}
</span>
<ElTag size="small">
{{ getDataTypeName(selectedProperty.dataType) }}
</ElTag>
</div>
<div class="space-y-8px ml-24px">
<div class="gap-8px flex items-start">
<span class="text-12px min-w-60px flex-shrink-0 text-secondary">
标识符
</span>
<span class="text-12px flex-1 text-primary">
{{ selectedProperty.identifier }}
</span>
</div>
<div
v-if="selectedProperty.description"
class="gap-8px flex items-start"
>
<span class="text-12px min-w-60px flex-shrink-0 text-secondary">
描述
</span>
<span class="text-12px flex-1 text-primary">
{{ selectedProperty.description }}
</span>
</div>
<div v-if="selectedProperty.unit" class="gap-8px flex items-start">
<span class="text-12px min-w-60px flex-shrink-0 text-secondary">
单位
</span>
<span class="text-12px flex-1 text-primary">
{{ selectedProperty.unit }}
</span>
</div>
<div v-if="selectedProperty.range" class="gap-8px flex items-start">
<span class="text-12px min-w-60px flex-shrink-0 text-secondary">
取值范围
</span>
<span class="text-12px flex-1 text-primary">
{{ selectedProperty.range }}
</span>
</div>
<!-- 根据属性类型显示额外信息 -->
<div
v-if="
selectedProperty.type === IoTThingModelTypeEnum.PROPERTY &&
selectedProperty.accessMode
"
class="gap-8px flex items-start"
>
<span class="text-12px min-w-60px flex-shrink-0 text-secondary">
访问模式
</span>
<span class="text-12px flex-1 text-primary">
{{ getAccessModeLabel(selectedProperty.accessMode) }}
</span>
</div>
<div
v-if="
selectedProperty.type === IoTThingModelTypeEnum.EVENT &&
selectedProperty.eventType
"
class="gap-8px flex items-start"
>
<span class="text-12px min-w-60px flex-shrink-0 text-secondary">
事件类型
</span>
<span class="text-12px flex-1 text-primary">
{{ getEventTypeLabel(selectedProperty.eventType) }}
</span>
</div>
<div
v-if="
selectedProperty.type === IoTThingModelTypeEnum.SERVICE &&
selectedProperty.callType
"
class="gap-8px flex items-start"
>
<span class="text-12px min-w-60px flex-shrink-0 text-secondary">
调用类型
</span>
<span class="text-12px flex-1 text-primary">
{{ getThingModelServiceCallTypeLabel(selectedProperty.callType) }}
</span>
</div>
</div>
</div>
</template>
</ElPopover>
</div>
</template>
<style scoped>
/* 下拉选项样式 */
:deep(.el-select-dropdown__item) {
height: auto;
padding: 6px 20px;
}
/* 弹出层内容样式 */
.property-detail-content {
padding: 4px 0;
}
/* 弹出层自定义样式 */
:global(.property-detail-popover) {
/* 可以在这里添加全局弹出层样式 */
max-width: 400px !important;
}
:global(.property-detail-popover .el-popover__content) {
padding: 16px !important;
}
</style>

View File

@ -0,0 +1,394 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { RuleSceneApi } from '#/api/iot/rule/scene';
import { ref } from 'vue';
import { Page, useVbenDrawer } from '@vben/common-ui';
import {
CommonStatusEnum,
DICT_TYPE,
getActionTypeLabel,
getTriggerTypeLabel,
IotRuleSceneTriggerTypeEnum,
} from '@vben/constants';
import { IconifyIcon } from '@vben/icons';
import { CronUtils, formatDateTime } from '@vben/utils';
import { ElCard, ElCol, ElLoading, ElMessage, ElRow, ElTag, ElTooltip } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteSceneRule,
getSceneRulePage,
updateSceneRuleStatus,
} from '#/api/iot/rule/scene';
import { DictTag } from '#/components/dict-tag';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const [FormDrawer, formDrawerApi] = useVbenDrawer({
connectedComponent: Form,
destroyOnClose: true,
});
const statistics = ref({
total: 0,
enabled: 0,
disabled: 0,
timerRules: 0,
}); //
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 创建场景规则 */
function handleCreate() {
formDrawerApi.setData(null).open();
}
/** 编辑场景规则 */
function handleEdit(row: RuleSceneApi.SceneRule) {
formDrawerApi.setData(row).open();
}
/** 启用/停用场景规则 */
async function handleToggleStatus(row: RuleSceneApi.SceneRule) {
const newStatus =
row.status === CommonStatusEnum.ENABLE
? CommonStatusEnum.DISABLE
: CommonStatusEnum.ENABLE;
const loadingInstance = ElLoading.service({
text:
newStatus === CommonStatusEnum.ENABLE ? '正在启用...' : '正在停用...',
});
try {
await updateSceneRuleStatus(row.id as number, newStatus);
ElMessage.success(
newStatus === CommonStatusEnum.ENABLE ? '启用成功' : '停用成功',
);
handleRefresh();
} finally {
loadingInstance.close();
}
}
/** 删除场景规则 */
async function handleDelete(row: RuleSceneApi.SceneRule) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.name]),
});
try {
await deleteSceneRule(row.id as number);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
/** 判断规则是否包含定时触发器 */
function hasTimerTrigger(row: RuleSceneApi.SceneRule): boolean {
return (
row.triggers?.some(
(trigger) =>
trigger.type === IotRuleSceneTriggerTypeEnum.TIMER,
) || false
);
}
/** 触发条件摘要文本(拼接所有触发器) */
function getTriggerSummary(row: RuleSceneApi.SceneRule): string {
if (!row.triggers?.length) return '无触发器';
return row.triggers
.map((trigger) => {
const type = trigger.type ?? 0;
let description = getTriggerTypeLabel(type);
if (
(type === IotRuleSceneTriggerTypeEnum.DEVICE_PROPERTY_POST ||
type === IotRuleSceneTriggerTypeEnum.DEVICE_EVENT_POST ||
type === IotRuleSceneTriggerTypeEnum.DEVICE_SERVICE_INVOKE) &&
trigger.identifier
) {
description += ` (${trigger.identifier})`;
} else if (type === IotRuleSceneTriggerTypeEnum.TIMER) {
description = `${getTriggerTypeLabel(type)} (${CronUtils.format(trigger.cronExpression || '')})`;
}
if (trigger.deviceId) {
description += ` [设备 ID: ${trigger.deviceId}]`;
} else if (trigger.productId) {
description += ` [产品 ID: ${trigger.productId}]`;
}
return description;
})
.join(', ');
}
/** 执行动作摘要文本(拼接所有动作) */
function getActionSummary(row: RuleSceneApi.SceneRule): string {
if (!row.actions?.length) return '无执行器';
return row.actions
.map((action) => {
let description = getActionTypeLabel(action.type ?? 0);
if (action.deviceId) {
description += ` [设备 ID: ${action.deviceId}]`;
} else if (action.productId) {
description += ` [产品 ID: ${action.productId}]`;
}
if (action.alertConfigId) {
description += ` [告警配置 ID: ${action.alertConfigId}]`;
}
return description;
})
.join(', ');
}
/** 取定时触发器的 CRON 频率描述 */
function getCronFrequency(row: RuleSceneApi.SceneRule): string {
const timerTrigger = row.triggers?.find(
(trigger) =>
trigger.type === IotRuleSceneTriggerTypeEnum.TIMER,
);
return timerTrigger?.cronExpression
? CronUtils.getFrequencyDescription(timerTrigger.cronExpression)
: '';
}
/** 取定时触发器原始 CRON 表达式 */
function getCronExpression(row: RuleSceneApi.SceneRule): string {
const timerTrigger = row.triggers?.find(
(trigger) =>
trigger.type === IotRuleSceneTriggerTypeEnum.TIMER,
);
return timerTrigger?.cronExpression || '';
}
/** 取定时触发器下次执行时间 */
function getNextExecutionTime(row: RuleSceneApi.SceneRule): Date | null {
const timerTrigger = row.triggers?.find(
(trigger) =>
trigger.type === IotRuleSceneTriggerTypeEnum.TIMER,
);
return timerTrigger?.cronExpression
? CronUtils.getNextExecutionTime(timerTrigger.cronExpression)
: null;
}
/** 基于当前页列表刷新统计数据 */
function updateStatistics(rows: RuleSceneApi.SceneRule[]) {
statistics.value = {
total: rows.length,
enabled: rows.filter((item) => item.status === CommonStatusEnum.ENABLE)
.length,
disabled: rows.filter((item) => item.status === CommonStatusEnum.DISABLE)
.length,
timerRules: rows.filter((item) => hasTimerTrigger(item)).length,
};
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
const result = await getSceneRulePage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
updateStatistics(result.list || []);
return result;
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<RuleSceneApi.SceneRule>,
});
</script>
<template>
<Page auto-content-height>
<FormDrawer @success="handleRefresh" />
<!-- 统计卡片 -->
<ElRow :gutter="16" class="mb-4">
<ElCol :span="6">
<ElCard body-class="!p-3">
<div class="flex items-center">
<div
class="w-10 h-10 rounded-lg flex items-center justify-center text-xl text-white mr-3 bg-gradient-to-br from-indigo-500 to-purple-600"
>
<IconifyIcon icon="ant-design:file-text-outlined" />
</div>
<div class="leading-tight">
<div class="text-xl font-semibold">
{{ statistics.total }}
</div>
<div class="text-xs text-muted-foreground">总规则数</div>
</div>
</div>
</ElCard>
</ElCol>
<ElCol :span="6">
<ElCard body-class="!p-3">
<div class="flex items-center">
<div
class="w-10 h-10 rounded-lg flex items-center justify-center text-xl text-white mr-3 bg-gradient-to-br from-pink-400 to-red-500"
>
<IconifyIcon icon="ant-design:check-outlined" />
</div>
<div class="leading-tight">
<div class="text-xl font-semibold">
{{ statistics.enabled }}
</div>
<div class="text-xs text-muted-foreground">启用规则</div>
</div>
</div>
</ElCard>
</ElCol>
<ElCol :span="6">
<ElCard body-class="!p-3">
<div class="flex items-center">
<div
class="w-10 h-10 rounded-lg flex items-center justify-center text-xl text-white mr-3 bg-gradient-to-br from-cyan-400 to-blue-500"
>
<IconifyIcon icon="ant-design:close-outlined" />
</div>
<div class="leading-tight">
<div class="text-xl font-semibold">
{{ statistics.disabled }}
</div>
<div class="text-xs text-muted-foreground">禁用规则</div>
</div>
</div>
</ElCard>
</ElCol>
<ElCol :span="6">
<ElCard body-class="!p-3">
<div class="flex items-center">
<div
class="w-10 h-10 rounded-lg flex items-center justify-center text-xl text-white mr-3 bg-gradient-to-br from-green-400 to-teal-400"
>
<IconifyIcon icon="lucide:timer" />
</div>
<div class="leading-tight">
<div class="text-xl font-semibold">
{{ statistics.timerRules }}
</div>
<div class="text-xs text-muted-foreground">定时规则</div>
</div>
</div>
</ElCard>
</ElCol>
</ElRow>
<Grid table-title="">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['场景规则']),
type: 'primary',
icon: ACTION_ICON.ADD,
onClick: handleCreate,
},
]"
/>
</template>
<!-- 规则名称列名称 + 状态 tag inline + 描述 -->
<template #name="{ row }">
<div class="flex items-center gap-2">
<span class="font-medium text-foreground">{{ row.name }}</span>
<DictTag :type="DICT_TYPE.COMMON_STATUS" :value="row.status" />
</div>
<ElTooltip
v-if="row.description"
:content="row.description"
placement="top"
>
<div class="mt-1 max-w-[200px] truncate text-xs text-muted-foreground">
{{ row.description }}
</div>
</ElTooltip>
</template>
<!-- 触发条件列 tag 汇总 + 定时触发额外信息 -->
<template #triggers="{ row }">
<div class="space-y-1">
<ElTag type="primary" class="m-0">{{ getTriggerSummary(row) }}</ElTag>
<ElTooltip
v-if="hasTimerTrigger(row)"
:content="getCronExpression(row)"
placement="top"
>
<div class="text-xs text-muted-foreground">
<IconifyIcon icon="lucide:clock" class="mr-1 inline" />
{{ getCronFrequency(row) }}
<template v-if="getNextExecutionTime(row)">
· 下次 {{ formatDateTime(getNextExecutionTime(row) as Date) }}
</template>
</div>
</ElTooltip>
</div>
</template>
<!-- 执行动作列 tag 汇总 -->
<template #actionsCol="{ row }">
<ElTag type="success" class="m-0">{{ getActionSummary(row) }}</ElTag>
</template>
<!-- 最近触发列 -->
<template #lastTriggeredTime="{ row }">
<span v-if="row.lastTriggeredTime">
{{ formatDateTime(row.lastTriggeredTime) }}
</span>
<span v-else class="text-muted-foreground">未触发</span>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: row.status === CommonStatusEnum.ENABLE ? '停用' : '启用',
type: 'link',
icon:
row.status === CommonStatusEnum.ENABLE
? 'ant-design:stop-outlined'
: 'ant-design:check-circle-outlined',
onClick: handleToggleStatus.bind(null, row),
},
{
label: $t('common.edit'),
type: 'link',
icon: ACTION_ICON.EDIT,
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'link',
danger: true,
icon: ACTION_ICON.DELETE,
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@ -0,0 +1,255 @@
<script lang="ts" setup>
import type { IotSceneRule, RuleSceneApi } from '#/api/iot/rule/scene';
import { computed, nextTick, reactive, ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import {
CommonStatusEnum,
IotRuleSceneActionTypeEnum,
IotRuleSceneTriggerTypeEnum,
isDeviceTrigger,
} from '@vben/constants';
import { ElForm, ElMessage } from 'element-plus';
import {
createSceneRule,
getSceneRule,
updateSceneRule,
} from '#/api/iot/rule/scene';
import { $t } from '#/locales';
import ActionSection from '../form/sections/action-section.vue';
import BasicInfoSection from '../form/sections/basic-info-section.vue';
import TriggerSection from '../form/sections/trigger-section.vue';
defineOptions({ name: 'IoTRuleSceneForm' });
const emit = defineEmits(['success']);
const formRef = ref();
const formData = ref<IotSceneRule>(buildEmptyFormData());
const getTitle = computed(() =>
formData.value.id
? $t('ui.actionTitle.edit', ['场景规则'])
: $t('ui.actionTitle.create', ['场景规则']),
);
const [Drawer, drawerApi] = useVbenDrawer({
async onConfirm() {
try {
await formRef.value?.validate();
} catch {
return;
}
drawerApi.lock();
try {
const data = { ...formData.value } as IotSceneRule;
await (data.id ? updateSceneRule(data) : createSceneRule(data));
await drawerApi.close();
emit('success');
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} finally {
drawerApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
return;
}
const data = drawerApi.getData<RuleSceneApi.SceneRule>();
// await
formData.value = data?.id ? normalizeFormData(data) : buildEmptyFormData();
await nextTick();
formRef.value?.clearValidate?.();
//
if (data?.id) {
drawerApi.lock();
try {
const fresh = await getSceneRule(data.id);
formData.value = normalizeFormData(fresh);
} finally {
drawerApi.unlock();
}
}
},
});
/** 构造空白表单数据 */
function buildEmptyFormData(): IotSceneRule {
return {
name: '',
description: '',
status: CommonStatusEnum.ENABLE,
triggers: [
{
type: IotRuleSceneTriggerTypeEnum.DEVICE_PROPERTY_POST,
productId: undefined,
deviceId: undefined,
identifier: undefined,
operator: undefined,
value: undefined,
cronExpression: undefined,
conditionGroups: [],
},
],
actions: [],
};
}
/** 回显时兜底,保证触发器/执行器数组不为空 */
function normalizeFormData(result: any): IotSceneRule {
return {
...result,
triggers: result.triggers?.length
? result.triggers
: buildEmptyFormData().triggers,
actions: result.actions || [],
};
}
/** 触发器校验 */
function validateTriggers(_rule: any, value: any, callback: any) {
if (!value || !Array.isArray(value) || value.length === 0) {
callback(new Error('至少需要一个触发器'));
return;
}
for (const [i, trigger] of value.entries()) {
if (!trigger.type) {
callback(new Error(`触发器 ${i + 1}:触发器类型不能为空`));
return;
}
if (isDeviceTrigger(trigger.type)) {
if (!trigger.productId) {
callback(new Error(`触发器 ${i + 1}:产品不能为空`));
return;
}
if (!trigger.deviceId) {
callback(new Error(`触发器 ${i + 1}:设备不能为空`));
return;
}
if (!trigger.identifier) {
callback(new Error(`触发器 ${i + 1}:物模型标识符不能为空`));
return;
}
// / operator '=' /
const isEventOrService =
trigger.type === IotRuleSceneTriggerTypeEnum.DEVICE_EVENT_POST ||
trigger.type === IotRuleSceneTriggerTypeEnum.DEVICE_SERVICE_INVOKE;
if (!isEventOrService) {
if (!trigger.operator) {
callback(new Error(`触发器 ${i + 1}:操作符不能为空`));
return;
}
if (
trigger.value === undefined ||
trigger.value === null ||
trigger.value === ''
) {
callback(new Error(`触发器 ${i + 1}:参数值不能为空`));
return;
}
}
}
if (
trigger.type === IotRuleSceneTriggerTypeEnum.TIMER &&
!trigger.cronExpression
) {
callback(new Error(`触发器 ${i + 1}CRON 表达式不能为空`));
return;
}
}
callback();
}
/** 执行器校验 */
function validateActions(_rule: any, value: any, callback: any) {
if (!value || !Array.isArray(value) || value.length === 0) {
callback(new Error('至少需要一个执行器'));
return;
}
for (const [i, action] of value.entries()) {
if (!action.type) {
callback(new Error(`执行器 ${i + 1}:执行器类型不能为空`));
return;
}
if (
action.type === IotRuleSceneActionTypeEnum.DEVICE_PROPERTY_SET ||
action.type === IotRuleSceneActionTypeEnum.DEVICE_SERVICE_INVOKE
) {
if (!action.productId) {
callback(new Error(`执行器 ${i + 1}:产品不能为空`));
return;
}
if (!action.deviceId) {
callback(new Error(`执行器 ${i + 1}:设备不能为空`));
return;
}
if (
action.type === IotRuleSceneActionTypeEnum.DEVICE_SERVICE_INVOKE &&
!action.identifier
) {
callback(new Error(`执行器 ${i + 1}:服务不能为空`));
return;
}
if (!action.params || Object.keys(action.params).length === 0) {
callback(new Error(`执行器 ${i + 1}:参数配置不能为空`));
return;
}
}
if (
(action.type === IotRuleSceneActionTypeEnum.ALERT_TRIGGER ||
action.type === IotRuleSceneActionTypeEnum.ALERT_RECOVER) &&
!action.alertConfigId
) {
callback(new Error(`执行器 ${i + 1}:告警配置不能为空`));
return;
}
}
callback();
}
const formRules = reactive({
name: [
{ required: true, message: '场景名称不能为空', trigger: 'blur' },
{
type: 'string',
min: 1,
max: 50,
message: '场景名称长度应在 1-50 个字符之间',
trigger: 'blur',
},
],
status: [{ required: true, message: '场景状态不能为空', trigger: 'change' }],
description: [
{
type: 'string',
max: 200,
message: '场景描述不能超过 200 个字符',
trigger: 'blur',
},
],
triggers: [
{ required: true, validator: validateTriggers, trigger: 'change' },
],
actions: [{ required: true, validator: validateActions, trigger: 'change' }],
});
</script>
<template>
<Drawer :title="getTitle" class="w-4/5">
<ElForm
ref="formRef"
:model="formData"
:rules="formRules as any"
class="mx-4"
label-width="110px"
>
<BasicInfoSection v-model="formData" />
<TriggerSection v-model:triggers="formData.triggers as any" />
<ActionSection v-model:actions="formData.actions as any" />
</ElForm>
</Drawer>
</template>

View File

@ -10,7 +10,7 @@ import { IOT_PROVIDE_KEY } from '@vben/constants';
import { ElInput, ElRadioButton, ElRadioGroup } from 'element-plus'; import { ElInput, ElRadioButton, ElRadioGroup } from 'element-plus';
import { getThingModelTSL } from '#/api/iot/thingmodel'; import { getThingModelTSLByProductId } from '#/api/iot/thingmodel';
const product = inject<Ref<IotProductApi.Product>>(IOT_PROVIDE_KEY.PRODUCT); const product = inject<Ref<IotProductApi.Product>>(IOT_PROVIDE_KEY.PRODUCT);
@ -26,7 +26,7 @@ const [Modal, modalApi] = useVbenModal({
modalApi.lock(); modalApi.lock();
try { try {
// //
thingModelTSL.value = await getThingModelTSL(product?.value?.id || 0); thingModelTSL.value = await getThingModelTSLByProductId(product?.value?.id || 0);
// values // values
tslString.value = JSON.stringify(thingModelTSL.value, null, 2); tslString.value = JSON.stringify(thingModelTSL.value, null, 2);
} finally { } finally {

390
packages/utils/src/cron.ts Normal file
View File

@ -0,0 +1,390 @@
/**
* CRON CRON
*/
/** CRON 字段类型枚举 */
export enum CronFieldType {
DAY = 'day',
HOUR = 'hour',
MINUTE = 'minute',
MONTH = 'month',
SECOND = 'second',
WEEK = 'week',
YEAR = 'year',
}
/** CRON 字段配置 */
export interface CronFieldConfig {
key: CronFieldType;
label: string;
max: number;
min: number;
names?: Record<string, number>;
}
/** CRON 字段配置常量 */
export const CRON_FIELD_CONFIGS: Record<CronFieldType, CronFieldConfig> = {
[CronFieldType.SECOND]: {
key: CronFieldType.SECOND,
label: '秒',
min: 0,
max: 59,
},
[CronFieldType.MINUTE]: {
key: CronFieldType.MINUTE,
label: '分',
min: 0,
max: 59,
},
[CronFieldType.HOUR]: {
key: CronFieldType.HOUR,
label: '时',
min: 0,
max: 23,
},
[CronFieldType.DAY]: {
key: CronFieldType.DAY,
label: '日',
min: 1,
max: 31,
},
[CronFieldType.MONTH]: {
key: CronFieldType.MONTH,
label: '月',
min: 1,
max: 12,
names: {
JAN: 1,
FEB: 2,
MAR: 3,
APR: 4,
MAY: 5,
JUN: 6,
JUL: 7,
AUG: 8,
SEP: 9,
OCT: 10,
NOV: 11,
DEC: 12,
},
},
[CronFieldType.WEEK]: {
key: CronFieldType.WEEK,
label: '周',
min: 0,
max: 7,
names: {
SUN: 0,
MON: 1,
TUE: 2,
WED: 3,
THU: 4,
FRI: 5,
SAT: 6,
},
},
[CronFieldType.YEAR]: {
key: CronFieldType.YEAR,
label: '年',
min: 1970,
max: 2099,
},
};
/** 解析后的 CRON 字段 */
export interface ParsedCronField {
description: string;
original: string;
type:
| 'any'
| 'last'
| 'list'
| 'nth'
| 'range'
| 'specific'
| 'step'
| 'weekday';
values: number[];
}
/** 解析后的 CRON 表达式 */
export interface ParsedCronExpression {
day: ParsedCronField;
description: string;
hour: ParsedCronField;
isValid: boolean;
minute: ParsedCronField;
month: ParsedCronField;
nextExecutionTime?: Date;
second: ParsedCronField;
week: ParsedCronField;
year?: ParsedCronField;
}
/** CRON 表达式工具类 */
export const CronUtils = {
/** 验证 CRON 表达式格式 */
validate(cronExpression: string): boolean {
if (!cronExpression || typeof cronExpression !== 'string') {
return false;
}
const parts = cronExpression.trim().split(/\s+/);
if (parts.length < 5 || parts.length > 7) {
return false;
}
const cronRegex = /^[\d#*,/?LW\-]+$/;
return parts.every((part) => cronRegex.test(part));
},
/** 解析单个 CRON 字段 */
parseField(
fieldValue: string,
fieldType: CronFieldType,
config: CronFieldConfig,
): ParsedCronField {
const field: ParsedCronField = {
type: 'any',
values: [],
original: fieldValue,
description: '',
};
if (fieldValue === '*' || fieldValue === '?') {
field.type = 'any';
field.description = `${config.label}`;
return field;
}
if (fieldValue === 'L' && fieldType === CronFieldType.DAY) {
field.type = 'last';
field.description = '每月最后一天';
return field;
}
if (fieldValue.includes('-')) {
const [start, end] = fieldValue.split('-').map(Number);
if (
!Number.isNaN(start) &&
!Number.isNaN(end) &&
start! >= config.min &&
end! <= config.max
) {
field.type = 'range';
field.values = Array.from(
{ length: end! - start! + 1 },
(_, i) => start! + i,
);
field.description = `${config.label} ${start}-${end}`;
}
return field;
}
if (fieldValue.includes('/')) {
const [base, step] = fieldValue.split('/');
const stepNum = Number(step);
if (!Number.isNaN(stepNum) && stepNum > 0) {
field.type = 'step';
if (base === '*') {
field.description = `${stepNum} ${config.label}`;
} else {
const startNum = Number(base);
field.description = `${startNum} 开始每 ${stepNum} ${config.label}`;
}
}
return field;
}
if (fieldValue.includes(',')) {
const values = fieldValue
.split(',')
.map(Number)
.filter((n) => !Number.isNaN(n));
if (values.length > 0) {
field.type = 'list';
field.values = values;
field.description = `${config.label} ${values.join(',')}`;
}
return field;
}
const numValue = Number(fieldValue);
if (
!Number.isNaN(numValue) &&
numValue >= config.min &&
numValue <= config.max
) {
field.type = 'specific';
field.values = [numValue];
field.description = `${config.label} ${numValue}`;
}
return field;
},
/** 解析完整的 CRON 表达式 */
parse(cronExpression: string): ParsedCronExpression {
const result: ParsedCronExpression = {
second: { type: 'any', values: [], original: '*', description: '每秒' },
minute: { type: 'any', values: [], original: '*', description: '每分' },
hour: { type: 'any', values: [], original: '*', description: '每时' },
day: { type: 'any', values: [], original: '*', description: '每日' },
month: { type: 'any', values: [], original: '*', description: '每月' },
week: { type: 'any', values: [], original: '?', description: '任意周' },
isValid: false,
description: '',
};
if (!this.validate(cronExpression)) {
result.description = '无效的 CRON 表达式';
return result;
}
const parts = cronExpression.trim().split(/\s+/);
const fieldTypes = [
CronFieldType.SECOND,
CronFieldType.MINUTE,
CronFieldType.HOUR,
CronFieldType.DAY,
CronFieldType.MONTH,
CronFieldType.WEEK,
];
const startIndex = parts.length === 5 ? 1 : 0;
for (const [i, part] of parts.entries()) {
const fieldType = fieldTypes[i + startIndex];
if (fieldType && CRON_FIELD_CONFIGS[fieldType]) {
const config = CRON_FIELD_CONFIGS[fieldType];
(result as any)[fieldType] = this.parseField(part, fieldType, config);
}
}
if (parts.length === 7) {
const yearConfig = CRON_FIELD_CONFIGS[CronFieldType.YEAR];
result.year = this.parseField(parts[6]!, CronFieldType.YEAR, yearConfig);
}
result.isValid = true;
result.description = this.generateDescription(result);
return result;
},
/** 生成 CRON 表达式的可读描述 */
generateDescription(parsed: ParsedCronExpression): string {
const parts: string[] = [];
if (parsed.hour.type === 'specific' && parsed.minute.type === 'specific') {
const hour = parsed.hour.values[0]!;
const minute = parsed.minute.values[0]!;
parts.push(
`${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`,
);
} else if (parsed.hour.type === 'specific') {
parts.push(`每天 ${parsed.hour.values[0]}`);
} else if (
parsed.minute.type === 'specific' &&
parsed.minute.values[0] === 0 &&
parsed.hour.type === 'any'
) {
parts.push('每小时整点');
} else if (parsed.minute.type === 'step') {
const step = parsed.minute.original.split('/')[1];
parts.push(`${step} 分钟`);
} else if (parsed.hour.type === 'step') {
const step = parsed.hour.original.split('/')[1];
parts.push(`${step} 小时`);
}
if (parsed.day.type === 'specific') {
parts.push(`每月 ${parsed.day.values[0]}`);
} else if (parsed.week.type === 'specific') {
const weekNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
const weekDay = parsed.week.values[0]!;
if (weekDay >= 0 && weekDay <= 6) {
parts.push(`${weekNames[weekDay]}`);
}
} else if (parsed.week.type === 'range') {
parts.push('工作日');
}
if (parsed.month.type === 'specific') {
parts.push(`${parsed.month.values[0]}`);
}
return parts.length > 0 ? parts.join(' ') : '自定义时间规则';
},
/** 格式化 CRON 表达式为可读文本 */
format(cronExpression: string): string {
if (!cronExpression) return '';
const parsed = this.parse(cronExpression);
return parsed.isValid ? parsed.description : cronExpression;
},
/** 计算 CRON 表达式的下次执行时间(简化版,仅覆盖常见模式) */
getNextExecutionTime(
cronExpression: string,
fromDate?: Date,
): Date | null {
const parsed = this.parse(cronExpression);
if (!parsed.isValid) {
return null;
}
const now = fromDate || new Date();
const nextTime = new Date(now.getTime() + 1000);
if (parsed.second.type === 'specific' && parsed.minute.type === 'any') {
const targetSecond = parsed.second.values[0]!;
nextTime.setSeconds(targetSecond, 0);
if (nextTime <= now) {
nextTime.setMinutes(nextTime.getMinutes() + 1);
}
return nextTime;
}
if (
parsed.second.type === 'specific' &&
parsed.minute.type === 'specific' &&
parsed.hour.type === 'any'
) {
const targetSecond = parsed.second.values[0]!;
const targetMinute = parsed.minute.values[0]!;
nextTime.setMinutes(targetMinute, targetSecond, 0);
if (nextTime <= now) {
nextTime.setHours(nextTime.getHours() + 1);
}
return nextTime;
}
if (
parsed.second.type === 'specific' &&
parsed.minute.type === 'specific' &&
parsed.hour.type === 'specific'
) {
const targetSecond = parsed.second.values[0]!;
const targetMinute = parsed.minute.values[0]!;
const targetHour = parsed.hour.values[0]!;
nextTime.setHours(targetHour, targetMinute, targetSecond, 0);
if (nextTime <= now) {
nextTime.setDate(nextTime.getDate() + 1);
}
return nextTime;
}
if (parsed.minute.type === 'step') {
const step = Number.parseInt(parsed.minute.original.split('/')[1]!);
const currentMinute = nextTime.getMinutes();
const nextMinute = Math.ceil(currentMinute / step) * step;
if (nextMinute >= 60) {
nextTime.setHours(nextTime.getHours() + 1, 0, 0, 0);
} else {
nextTime.setMinutes(nextMinute, 0, 0);
}
return nextTime;
}
return new Date(now.getTime() + 60_000);
},
/** 获取 CRON 表达式的执行频率描述 */
getFrequencyDescription(cronExpression: string): string {
const parsed = this.parse(cronExpression);
if (!parsed.isValid) {
return '无效表达式';
}
if (parsed.second.type === 'any' && parsed.minute.type === 'any') {
return '每秒执行';
}
if (parsed.minute.type === 'any' && parsed.hour.type === 'any') {
return '每分钟执行';
}
if (parsed.hour.type === 'any' && parsed.day.type === 'any') {
return '每小时执行';
}
if (parsed.day.type === 'any' && parsed.month.type === 'any') {
return '每天执行';
}
if (parsed.month.type === 'any') {
return '每月执行';
}
return '按计划执行';
},
};

View File

@ -1,3 +1,4 @@
export * from './cron';
export * from './helpers'; export * from './helpers';
export * from './validator'; export * from './validator';
export * from '@vben-core/shared/cache'; export * from '@vben-core/shared/cache';