<template>
	<view class="page-container">
		<uni-collapse ref="collapse" accordion v-if="list.length > 0">
			<uni-collapse-item
				v-for="(item,index) in list"
				:key="index + 'ylList'"
				:open="index === 0"
				class="common-collapse-item"
				:class="handleCardClass(item)"
			>
				<template v-slot:title>
					<view class="title-wrapper">
						<view class="top">
							<view class="status">{{ item.statusText }}</view>
							<text class="name">{{ item.deviceName }}</text>
						</view>
					</view>
				</template>
				<view class="content">
					<uni-group mode="card" class="data-card-group">
						<uni-row
							v-for="(field, fieldIndex) in (item.fieldConfigs || fallbackFieldConfigs)"
							:key="fieldIndex + 'ylField'"
							class="data-row"
						>
							<uni-col :span="8">
								<view class="title">{{ field.name }}</view>
							</uni-col>
							<uni-col :span="16">
								<view class="value">
									{{ item[field.attr] | formatNumber }}
									<text v-if="field.unit" v-html="field.unit"></text>
								</view>
							</uni-col>
						</uni-row>
					</uni-group>
				</view>
			</uni-collapse-item>
		</uni-collapse>
		<view class="no-data" v-else>
			暂无数据
		</view>
	</view>
</template>

<script>
	import {
		getProjectDisplayData,
		getDeviceList
	} from '@/api/ems/site.js'
	import {
		mapState
	} from 'vuex'

	export default {
		computed: {
			...mapState({
				deviceStatusOptions: (state) => state.ems.deviceStatusOptions,
			}),
		},
		data() {
			return {
				siteId: '',
				displayData: [],
				coolingDeviceList: [],
				list: [],
				fallbackFieldConfigs: [{
					name: '供水温度',
					attr: 'gsTemp',
					unit: '&#8451;'
				}, {
					name: '回水温度',
					attr: 'hsTemp',
					unit: '&#8451;'
				}, {
					name: '供水压力',
					attr: 'gsPressure',
					unit: 'MPa'
				}, {
					name: '回水压力',
					attr: 'hsPressure',
					unit: 'MPa'
				}, {
					name: '冷源水温度',
					attr: 'lysTemp',
					unit: '&#8451;'
				}, {
					name: 'VB01开度',
					attr: 'vb01Kd',
					unit: '%'
				}, {
					name: 'VB02开度',
					attr: 'vb02Kd',
					unit: '%'
				}]
			}
		},
		methods: {
			normalizeDeviceId(value) {
				return String(value == null ? '' : value).trim().toUpperCase()
			},
			getModuleRows(menuCode) {
				return (this.displayData || []).filter((item) => item.menuCode === menuCode)
			},
			getFieldName(fieldCode) {
				const raw = String(fieldCode || '').trim()
				if (!raw) return ''
				const index = raw.lastIndexOf('__')
				return index >= 0 ? raw.slice(index + 2) : raw
			},
			getFieldUnit(attr) {
				const field = (this.fallbackFieldConfigs || []).find((item) => item.attr === attr)
				return field ? (field.unit || '') : ''
			},
			getFieldConfigs(rows = []) {
				const result = []
				const seen = {}
				;(rows || []).forEach((item) => {
					const attr = this.getFieldName(item?.fieldCode)
					const name = String(item?.fieldName || '').trim()
					if (!attr || !name || seen[name]) return
					result.push({
						name,
						attr,
						unit: this.getFieldUnit(attr),
					})
					seen[name] = true
				})
				return result.length > 0 ? result : this.fallbackFieldConfigs
			},
			getFieldRowMap(rows = [], deviceId = '') {
				const map = {}
				const targetDeviceId = this.normalizeDeviceId(deviceId || '')
				rows.forEach((item) => {
					if (!item || !item.fieldCode) return
					const itemDeviceId = this.normalizeDeviceId(item.deviceId || '')
					if (itemDeviceId !== targetDeviceId) return
					map[this.getFieldName(item.fieldCode)] = item
				})
				rows.forEach((item) => {
					if (!item || !item.fieldCode) return
					const itemDeviceId = this.normalizeDeviceId(item.deviceId || '')
					if (itemDeviceId !== '') return
					const fieldName = this.getFieldName(item.fieldCode)
					if (!map[fieldName]) {
						map[fieldName] = item
					}
				})
				return map
			},
			getLatestUpdateTime(rows = []) {
				const times = (rows || [])
					.map((item) => new Date(item?.valueTime).getTime())
					.filter((ts) => !isNaN(ts))
				if (times.length === 0) return '-'
				const date = new Date(Math.max(...times))
				const p = (n) => String(n).padStart(2, '0')
				return `${date.getFullYear()}-${p(date.getMonth() + 1)}-${p(date.getDate())} ${p(date.getHours())}:${p(date.getMinutes())}:${p(date.getSeconds())}`
			},
			formatStatusText(statusValue) {
				const key = String(statusValue == null ? '' : statusValue).trim()
				if (!key) return '暂无数据'
				return (this.deviceStatusOptions || {})[key] || key
			},
			handleCardClass(item) {
				const key = String(item?.statusValue == null ? '' : item.statusValue).trim()
				if (key === '1') return 'running-collapse-item'
				if (key === '2') return 'warning-collapse-item'
				return 'timing-collapse-item'
			},
			buildList() {
				const rows = this.getModuleRows('SBJK_YL')
				const fieldConfigs = this.getFieldConfigs(rows)
				let devices = (this.coolingDeviceList || []).filter((item) => item.deviceCategory === 'COOLING')
				if (devices.length === 0) {
					const grouped = {}
					rows.forEach((item) => {
						const id = this.normalizeDeviceId(item?.deviceId || '')
						if (!id || grouped[id]) return
						grouped[id] = {
							deviceId: id,
							deviceName: item?.deviceName || id,
							deviceStatus: ''
						}
					})
					devices = Object.values(grouped)
				}
				if (devices.length === 0) {
					devices = [{
						deviceId: '',
						deviceName: '冷却',
						deviceStatus: ''
					}]
				}

				this.list = devices.map((device) => {
					const id = this.normalizeDeviceId(device.deviceId || device.id || '')
					const fieldRowMap = this.getFieldRowMap(rows, id)
					const values = {}
					fieldConfigs.forEach((cfg) => {
						values[cfg.attr] = fieldRowMap[cfg.attr]?.fieldValue
					})
					const statusField = Object.values(fieldRowMap).find((row) => String(row?.fieldName || '').includes('状态'))
					const statusValue = statusField?.fieldValue || device.deviceStatus || ''
					return {
						...values,
						deviceId: id,
						deviceName: device.deviceName || device.name || id || '冷却',
						statusValue: String(statusValue || ''),
						statusText: this.formatStatusText(statusValue),
						fieldConfigs,
						dataUpdateTime: this.getLatestUpdateTime(Object.values(fieldRowMap)),
					}
				})
			}
		},
		onLoad(options) {
			uni.showLoading()
			this.siteId = options.siteId || ''
			Promise.all([
				getProjectDisplayData(this.siteId),
				getDeviceList(this.siteId)
			]).then(([displayResponse, deviceResponse]) => {
				this.displayData = displayResponse?.data || []
				this.coolingDeviceList = deviceResponse?.data || []
				this.buildList()
				if (this.list.length > 0) {
					this.$nextTick(() => {
						setTimeout(() => {
							this.$refs.collapse.resize()
							uni.hideLoading()
						}, 100)
					})
				} else {
					uni.hideLoading()
				}
			}).catch(() => {
				uni.hideLoading()
			})
		}
	}
</script>
