useObjectModelValue.ts
1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import type { DataType, Specs, StructJSON } from '@/api/device/model'
import { DataTypeEnum } from '@/enums/datasource'
import { useJsonParse } from '@/hooks/business/useJSONParse'
import { useProductsStoreWithOut } from '@/store/modules/products'
function getBoolTypeValue(value: number, Specs: Specs) {
const { boolOpen, boolClose } = Specs
return Number(value) ? boolOpen : boolClose
}
function getEnumTypeValue(value: number, specsList: Specs[]) {
const res = specsList.find(item => item.value === Number(value))
return res?.name
}
function getStructTypeValue(value: string, specs: StructJSON[]): string {
const res = useJsonParse(value).value
function generateStruct(specs: StructJSON[], value: Recordable) {
if (!value) return {}
return specs.reduce((prev, next) => {
return {
...prev,
[next.functionName]: getValueByType(next.dataType!.type, value[next.identifier], next.dataType!),
}
}, {})
}
return JSON.stringify(generateStruct(specs, res))
}
function getValueByType(type: string, value: any, dataType: DataType) {
switch (type) {
case DataTypeEnum.BOOL:
return getBoolTypeValue(value, dataType.specs as Specs)
case DataTypeEnum.STRUCT:
return getStructTypeValue(value, dataType.specs as StructJSON[])
case DataTypeEnum.ENUM:
return getEnumTypeValue(value, dataType.specsList as Specs[])
default:
return value
}
}
export function useObjectModelValue(deviceProfileId: string, attr: string, value: any) {
const productsStore = useProductsStoreWithOut()
const result = productsStore.getObjectModelByIdWithIdentifier(deviceProfileId, attr)
if (!result)
return value
return getValueByType(result.specs.dataType.type as DataTypeEnum, value, result.specs.dataType)
}