<template>
	<div class="select-device">
		选择设备：
		<el-select style="width: 15vw" v-model="deviceKey" @change="deviceChnage" placeholder="">
			<el-option v-for="row in deviceList" :key="row.key" :label="row.name" :value="row.key"></el-option>
		</el-select>
	</div>
	<section class="baseinfo" v-loading="loading">
		<div class="flex-item" v-for="row in propertiyList" :key="row.devicePropertiyKey">
			<div class="label">{{ row.devicePropertiyName }}</div>
			<div class="val">
				{{ row.devicePropertiyValue }}
				<span class="unit" v-if="row.devicePropertiyUnit">{{ row.devicePropertiyUnit }}</span>
			</div>
		</div>
		<template v-if="propertiyList.length % 3">
			<div class="flex-item space" v-for="i in 3 - (propertiyList.length % 3)" :key="i"></div>
		</template>
	</section>
</template>
<script setup lang="ts">
import { ref, inject, watch, Ref } from 'vue'
import api from '/@/api/projects'

const emit = defineEmits(['change'])

const projectCode = inject<Ref<string>>('projectCode', ref(''))

const loading = ref(true)
const deviceKey = ref('')
const deviceList = ref<any[]>([])
const propertiyList = ref<any[]>([])

watch(() => projectCode.value, getData)

function getData(code: string) {
	if (!code) return

	loading.value = true

	deviceKey.value = ''
	deviceList.value = []
	propertiyList.value = []

	api.screen.projectDevices(code).then((res: any) => {
		if (!res?.length) return (loading.value = false)

		const keys = (res || []).filter((row: any) => row.resourcesTypes === 1).map((item: any) => item.resourcesKey)

		loading.value = true
		api.screen.projectDevicesList(keys).then((res: any) => {
			const list = res.device || []

			deviceList.value = list

			if (list.length) {
				deviceKey.value = list[0].key
				deviceChnage()
			} else {
				emit('change', '')
				loading.value = false
			}
		})
	})
}

function deviceChnage() {
	emit('change', deviceKey.value)

	loading.value = true
	api.screen
		.propertyListValue(projectCode.value, deviceKey.value)
		.then((res: any) => {
			propertiyList.value = res || []
		})
		.finally(() => (loading.value = false))
}
</script>

<style lang="scss" scoped>
.select-device {
	display: flex;
	align-items: center;
	font-size: 1.5vh;
	font-weight: 500;
}

.baseinfo {
	background-size: 100% 100%;
	margin-top: 1.5vh;
	display: flex;
	flex-flow: row wrap;
	justify-content: space-between;
	gap: 2vh;
	height: 20vh;
	overflow-y: auto;

	.flex-item {
		background-size: 100% 100%;
		display: flex;
		align-items: center;
		flex: 1;
		height: 3.5vh;
		max-width: 33%;
		min-width: 30%;
		text-indent: 1.1em;
		font-size: 1.55vh;
		white-space: nowrap;
		overflow: hidden;

		&.space {
			background: none;
		}

		.label {
			flex: 1;
		}

		.val {
			font-size: 2.2vh;
			font-weight: bold;
			flex: 1;

			.unit {
				font-weight: normal;
				font-size: 1.4vh;
			}
		}
	}
}
</style>
