<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+'dbList'" :open="index===0"
				class="common-collapse-item" :class="{
					'timing-collapse-item':!['0','2'].includes(item.emsCommunicationStatus),
							'warning-collapse-item':item.emsCommunicationStatus === '2',
							'running-collapse-item':item.emsCommunicationStatus === '0'
				}">
				<template v-slot:title>
					<view class='title-wrapper'>
						<view class="top">
							<view class="status">{{communicationStatusOptions[item.emsCommunicationStatus] || '暂无数据'}}
							</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="(tempDataItem,tempDataIndex) in
						(item.fieldConfigs || otherTypeMsg)" :key="tempDataIndex+'dbTempData'" class="data-row">
							<uni-col :span="8">
								<view class="title">{{tempDataItem.name}}</view>
							</uni-col>
							<uni-col :span="16">
								<view class="value">{{item[tempDataItem.attr] | formatNumber}}
									<text v-if="tempDataItem.unit" v-html="tempDataItem.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({
				communicationStatusOptions: (state) =>
					state.ems.communicationStatusOptions,
			})
		},
		data() {
			return {
				siteId: '',
				displayData: [],
				ammeterDeviceList: [],
				list: [],
				otherTypeMsg: [{
						name: '正向有功电能',
						attr: 'forwardActive',
						pointName: '正向有功电能',
						unit: 'kWh'
					},
					{
						name: '反向有功电能',
						attr: 'reverseActive',
						pointName: '反向有功电能',
						unit: 'kWh'
					},
					{
						name: '正向无功电能',
						attr: 'forwardReactive',
						pointName: '正向无功电能',
						unit: 'kvarh'
					},
					{
						name: '反向无功电能',
						attr: 'reverseReactive',
						pointName: '反向无功电能',
						unit: 'kvarh'
					},
					{
						name: '有功功率',
						attr: 'activePower',
						pointName: '总有功功率',
						unit: 'kW'
					},
					{
						name: '无功功率',
						attr: 'reactivePower',
						pointName: '总无功功率',
						unit: 'kvar'
					},
				]
			}
		},
		methods: {
			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
			},
			isEmptyValue(value) {
				return value === undefined || value === null || value === ''
			},
			getFieldRowMap(rows = [], deviceId = '') {
				const map = {}
				const targetDeviceId = String(deviceId || '')
				rows.forEach(item => {
					if (!item || !item.fieldCode) return
					const itemDeviceId = String(item.deviceId || '')
					if (itemDeviceId !== targetDeviceId) return
					map[this.getFieldName(item.fieldCode)] = item
				})
				rows.forEach(item => {
					if (!item || !item.fieldCode) return
					const itemDeviceId = String(item.deviceId || '')
					if (itemDeviceId !== '') return
					const fieldName = this.getFieldName(item.fieldCode)
					const existRow = map[fieldName]
					if (!existRow || this.isEmptyValue(existRow.fieldValue)) {
						map[fieldName] = item
					}
				})
				return map
			},
			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
					const base = this.otherTypeMsg.find(i => i.attr === attr) || {}
					result.push({
						name,
						attr,
						pointName: base.pointName || name,
						unit: base.unit || ''
					})
					seen[name] = true
				})
				return result.length > 0 ? result : this.otherTypeMsg
			},
			buildList() {
				const rows = this.getModuleRows('SBJK_DB')
				const fieldConfigs = this.getFieldConfigs(rows)
				let devices = (this.ammeterDeviceList || []).filter(item => item.deviceCategory === 'AMMETER')
				if (devices.length === 0) {
					const grouped = {}
					rows.forEach(item => {
						const id = String(item?.deviceId || '').trim()
						if (!id || grouped[id]) return
						grouped[id] = {
							deviceId: id,
							deviceName: id
						}
					})
					devices = Object.values(grouped)
				}
				if (devices.length === 0) {
					devices = [{
						deviceId: '',
						deviceName: '电表'
					}]
				}
				this.list = devices.map(device => {
					const id = String(device.deviceId || device.id || '').trim()
					const fieldRowMap = this.getFieldRowMap(rows, id)
					const statusValue = fieldRowMap.communicationStatus?.fieldValue || fieldRowMap.emsCommunicationStatus?.fieldValue || ''
					const values = {}
					fieldConfigs.forEach(cfg => {
						values[cfg.attr] = fieldRowMap[cfg.attr]?.fieldValue
					})
					return {
						...values,
						deviceId: id,
						deviceName: device.deviceName || device.name || id || '电表',
						emsCommunicationStatus: String(statusValue || ''),
						fieldConfigs
					}
				})
			}
		},
		onLoad(options) {
			uni.showLoading()
			this.siteId = options.siteId || ''
			Promise.all([
				getProjectDisplayData(this.siteId),
				getDeviceList(this.siteId)
			]).then(([displayResponse, deviceResponse]) => {
				this.displayData = displayResponse?.data || []
				this.ammeterDeviceList = 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>
<style lang="scss" scoped>
	.unknow-bd-device {
		text-align: center;
		padding: 20rpx;
		font-size: 28rpx;
		line-height: 50rpx;
		background-color: #fff;
		color: #000;
	}
</style>
