<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="item.deviceId+'bmszl'" :open="index===0"
				class="common-collapse-item" :class="handleCardClass(item,index)">

				<template v-slot:title>
					<view class='title-wrapper'>
						<view class="top">
							<view class="status">{{STACKWorkStatusOptions[item.workStatus] || '暂无数据'}}</view>
							<text class="name">{{item.deviceName}}</text>
						</view>
					</view>
				</template>
				<view class='content'>
					<!-- 设备状态栏 -->
					<uni-group mode="card" class="status-card-group">
						<view class="flex-container">
							<view class="flex-lists">
								<view class="grid-item-box">
									<view class="title">工作状态</view>
									<text
										class="text work-status-color">{{STACKWorkStatusOptions[item.workStatus] || '-'}}</text>
								</view>
							</view>
							<view class="flex-lists">
								<view class="grid-item-box">
									<view class="title">与PCS通信</view>
									<text
										class="text">{{communicationStatusOptions[item.pcsCommunicationStatus] || '-'}}</text>
								</view>
							</view>
							<view class="flex-lists">
								<view class="grid-item-box">
									<view class="title">与EMS通信</view>
									<text
										class="text">{{communicationStatusOptions[item.emsCommunicationStatus] || '-'}}</text>
								</view>
							</view>
						</view>
					</uni-group>
					<!-- 设备数据 -->
					<uni-group mode="card" class="data-card-group">
						<uni-row v-for="(infoDataItem,infoDataIndex) in infoData" :key="infoDataIndex+'infoData'"
							class="data-row">
							<uni-col :span="8">
								<view class="title">{{infoDataItem.label}}</view>
							</uni-col>
							<uni-col :span="16">
								<view class="value">{{item[infoDataItem.attr] | formatNumber}}
									<text v-if="infoDataItem.unit" v-html="infoDataItem.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,
		getStackNameList
	} from '@/api/ems/site.js'
	import {
		mapState
	} from 'vuex'
	export default {
		computed: {
			...mapState({
				STACKWorkStatusOptions: (state) =>
					state.ems.STACKWorkStatusOptions,
				communicationStatusOptions: (state) =>
					state.ems.communicationStatusOptions,
			})
		},
		data() {
			return {
				displayData: [],
				stackDeviceList: [],
				list: [],
				siteId: '',
				infoData: [{
						label: '电池堆总电压',
						attr: 'stackVoltage',
						unit: 'V',
						pointName: '电池堆电压'
					},
					{
						label: '可充电量',
						attr: 'availableChargeCapacity',
						unit: 'kWh',
						pointName: '可充电量'
					},
					{
						label: '累计充电量',
						attr: 'totalChargeCapacity',
						unit: 'kWh',
						pointName: '累计充电量'
					},
					{
						label: '电池堆总电流',
						attr: 'stackCurrent',
						unit: 'A',
						pointName: '电池堆总电流'
					},
					{
						label: '可放电量',
						attr: 'availableDischargeCapacity',
						unit: 'kWh',
						pointName: '可放电量'
					},
					{
						label: '累计放电量',
						attr: 'totalDischargeCapacity',
						unit: 'kWh',
						pointName: '累计放电量'
					},
					{
						label: 'SOH',
						attr: 'stackSoh',
						unit: '%',
						pointName: 'SOH'
					},
					{
						label: '平均温度',
						attr: 'operatingTemp',
						unit: '&#8451;',
						pointName: '平均温度'
					},
					{
						label: '绝缘电阻',
						attr: 'stackInsulationResistance',
						unit: '&Omega;',
						pointName: '绝缘电阻'
					},
					{
						label: '当前SOC',
						attr: 'stackSoc',
						unit: '%',
						pointName: '当前SOC'
					},
				]

			}
		},
		methods: {
			getModuleRows(menuCode, sectionName) {
				return (this.displayData || []).filter(item => item.menuCode === menuCode && item.sectionName === sectionName)
			},
			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
			},
			getFieldMap(rowMap = {}) {
				const map = {}
				Object.keys(rowMap || {}).forEach((fieldName) => {
					map[fieldName] = rowMap[fieldName]?.fieldValue
				})
				return map
			},
			buildBaseInfoList() {
				const devices = (this.stackDeviceList && this.stackDeviceList.length > 0) ? this.stackDeviceList : [{
					deviceId: this.siteId,
					deviceName: 'BMS总览'
				}]
				this.list = devices.map(device => {
					const id = device.deviceId || device.id || this.siteId
					const infoRowMap = this.getFieldRowMap(this.getModuleRows('SBJK_BMSZL', '堆信息'), id)
					const statusRowMap = this.getFieldRowMap(this.getModuleRows('SBJK_BMSZL', '状态'), id)
					const infoMap = this.getFieldMap(infoRowMap)
					const statusMap = this.getFieldMap(statusRowMap)
					return {
						...infoMap,
						workStatus: statusMap.workStatus,
						pcsCommunicationStatus: statusMap.pcsCommunicationStatus,
						emsCommunicationStatus: statusMap.emsCommunicationStatus,
						siteId: this.siteId,
						deviceId: id,
						deviceName: device.deviceName || device.name || device.deviceId || device.id || 'BMS总览',
						batteryDataList: []
					}
				})
			},
			handleCardClass(item) {
				const {
					workStatus = ''
				} = item
				return !Object.keys(this.STACKWorkStatusOptions).find(i => i === workStatus) ? "timing-collapse-item" :
					workStatus === '9' ? 'warning-collapse-item' : 'running-collapse-item'
			},
			updateData() {
				return Promise.all([
					getProjectDisplayData(this.siteId),
					getStackNameList(this.siteId)
				]).then(([displayResponse, stackResponse]) => {
					this.displayData = displayResponse?.data || []
					this.stackDeviceList = stackResponse?.data || []
					this.buildBaseInfoList()
				}).catch(() => {
					this.displayData = []
					this.stackDeviceList = []
					this.list = []
				})
			}
		},
		onLoad(options) {
			uni.showLoading()
			this.siteId = options.siteId || ''
			this.updateData().then(() => {
				if (this.list.length === 0) {
					uni.hideLoading()
					return
				}
				this.$nextTick(() => {
					setTimeout(() => {
						this.$refs.collapse && this.$refs.collapse.resize()
						uni.hideLoading()
					}, 100)
				})
			}).catch(() => {
				uni.hideLoading()
			})
		}
	}
</script>
