<template>
	<view class="page-container">
		<!-- 顶部总览横向展示 -->
		<scroll-view class="info-overview-scroll" scroll-x>
			<view class="info-overview-row">
				<view class="info-overview-card" v-for="(item,index) in runningHeadCards" :key="index+'head'">
					<view class="grid-item-box">
						<image :src="require('@/static/images/ems/pcs/'+item.img+'.jpg')" class="icon" alt="" />
						<view class="title">{{item.title}}</view>
						<view class="text">{{item.value | formatNumber}}</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 设备标签横向展示 -->
		<scroll-view class="pcs-tags-scroll" scroll-x>
			<view class="pcs-tags-row">
				<view
					class="pcs-tag-item"
					:class="{ active: !selectedPcsId }"
					@click="handleTagClick('')"
				>
					全部
				</view>
				<view
					v-for="(item, index) in pcsDeviceList"
					:key="index + 'pcsTag'"
					class="pcs-tag-item"
					:class="{ active: selectedPcsId === (item.deviceId || item.id || '') }"
					@click="handleTagClick(item.deviceId || item.id || '')"
				>
					{{ item.deviceName || item.deviceId || item.id || 'PCS' }}
				</view>
			</view>
		</scroll-view>

		<uni-collapse ref="collapse" accordion v-if="filteredList.length > 0">
			<uni-collapse-item v-for="(item,index) in filteredList" :key="index+'pcs'" :open="index===0"
				class="common-collapse-item" :class="handleCardClass(item)">

				<template v-slot:title>
					<view class='title-wrapper'>
						<view class="top">
							<view class="status">{{formatDictValue((PCSWorkStatusOptions || {}), item.workStatus, '暂无数据')}}</view>
							<text class="name">{{item.deviceName}}</text>
						</view>
					</view>
				</template>
				<view class='content'>
					<!-- 设备状态栏 -->
					<uni-group mode="card" class="status-card-group no-wrapper-padding">
						<view class="flex-container">
							<view class="flex-lists">
								<view class="grid-item-box">
									<view class="title">工作状态</view>
									<text
										class="text work-status-color">{{formatDictValue((PCSWorkStatusOptions || {}), item.workStatus)}}</text>
								</view>
							</view>
							<view class="flex-lists">
								<view class="grid-item-box">
									<view class="title">并网状态</view>
									<text class="text">{{formatDictValue((gridStatusOptions || {}), item.gridStatus)}}</text>
								</view>
							</view>
							<view class="flex-lists">
								<view class="grid-item-box">
									<view class="title">设备状态</view>
									<text class="text">{{formatDictValue((deviceStatusOptions || {}), item.deviceStatus)}}</text>
								</view>
							</view>
							<view class="flex-lists">
								<view class="grid-item-box">
									<view class="title">控制模式</view>
									<text class="text">{{formatDictValue((controlModeOptions || {}), item.controlMode)}}</text>
								</view>
							</view>
						</view>
					</uni-group>
					<!-- 设备数据 -->
					<uni-group mode="card" class="data-card-group"
						:style="{marginBottom:!item.pcsBranchInfoList || item.pcsBranchInfoList.length === 0 ?'25px' : ''}">
						<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>
					<!-- 支路 -->
					<uni-group class="branch-card-group" :title="`支路${pcsBranchIndex+1}`" mode="card"
						v-for="(pcsBranchItem,pcsBranchIndex) in item.pcsBranchInfoList"
						:key="pcsBranchIndex+'pcsBranchInfoList'">
						<view class="flex-container">
							<view class="flex-lists">
								<view class="grid-item-box">
									<view class="title">直流功率</view>
									<text class="text">{{pcsBranchItem.dcPower}}kW</text>
								</view>
							</view>
							<view class="flex-lists">
								<view class="grid-item-box">
									<view class="title">直流电压</view>
									<text class="text">{{pcsBranchItem.dcVoltage}}V</text>
								</view>
							</view>
							<view class="flex-lists">
								<view class="grid-item-box">
									<view class="title">直流电流</view>
									<text class="text">{{pcsBranchItem.dcCurrent}}A</text>
								</view>
							</view>
						</view>
					</uni-group>
				</view>
			</uni-collapse-item>
		</uni-collapse>
		<view class="no-data" v-else>
			暂无数据
		</view>
	</view>

</template>

<script>
	import {
		getProjectDisplayData,
		getPcsNameList
	} from '@/api/ems/site.js'
	import {
		mapState
	} from 'vuex'
	export default {
		computed: {
			...mapState({
				PCSWorkStatusOptions: (state) =>
					state.ems.PCSWorkStatusOptions,
				communicationStatusOptions: (state) =>
					state.ems.communicationStatusOptions,
				deviceStatusOptions: (state) =>
					state.ems.deviceStatusOptions,
				gridStatusOptions: (state) =>
					state.ems.gridStatusOptions,
				controlModeOptions: (state) =>
					state.ems.controlModeOptions,
			}),
			runningHeadCards() {
				const sectionData = (this.runningDisplayData || []).filter(item => item.sectionName === '运行概览')
				return sectionData.map((item, index) => ({
					title: item.fieldName,
					value: item.fieldValue,
					img: this.getHeadCardImg(item, index)
				}))
			},
			filteredList() {
				if (!this.selectedPcsId) {
					return this.list || []
				}
				return (this.list || []).filter(item => (item.deviceId || '') === this.selectedPcsId)
			}
		},
		data() {
			return {
				runningDisplayData: [],
				pcsDeviceList: [],
				selectedPcsId: '',
				list: [],
				siteId: '',
				infoData: [{
						label: "总交流有功功率",
						attr: "totalActivePower",
						unit: "kW",
						pointName: "总交流有功功率",
					},
					{
						label: "总交流无功功率",
						attr: "totalReactivePower",
						unit: "kVar",
						pointName: "总交流无功功率",
					},
					{
						label: "当天交流充电量",
						attr: "dailyAcChargeEnergy",
						unit: "kWh",
						pointName: "当天交流充电量 (kWh)",
					},
					{
						label: "当天交流放电量",
						attr: "dailyAcDischargeEnergy",
						unit: "kWh",
						pointName: "当天交流放电量 (kWh)",
					},
					{
						label: "A相电压",
						attr: "aPhaseVoltage",
						unit: "V",
						pointName: ""
					},
					{
						label: "A相电流",
						attr: "aPhaseCurrent",
						unit: "A",
						pointName: "A相电流",
					},

					{
						label: "B相电压",
						attr: "bPhaseVoltage",
						unit: "V",
						pointName: ""
					},
					{
						label: "B相电流",
						attr: "bPhaseCurrent",
						unit: "A",
						pointName: "B相电流",
					},
					{
						label: "总交流视在功率",
						attr: "totalApparentPower",
						unit: "kVA",
						pointName: "总交流视在功率",
					},
					{
						label: "总交流功率因数",
						attr: "totalPowerFactor",
						unit: "",
						pointName: "总交流功率因数",
					},
					{
						label: "PCS模块温度",
						attr: "pcsModuleTemperature",
						unit: "&#8451;",
						pointName: "",
					},
					{
						label: "PCS环境温度",
						attr: "pcsEnvironmentTemperature",
						unit: "&#8451;",
						pointName: "",
					},
					{
						label: "C相电压",
						attr: "cPhaseVoltage",
						unit: "V",
						pointName: ""
					},
					{
						label: "C相电流",
						attr: "cPhaseCurrent",
						unit: "A",
						pointName: "C相电流",
					},

					{
						label: "交流频率",
						attr: "acFrequency",
						unit: "Hz",
						pointName: "交流频率",
					},
				]
			}
		},
		methods: {
			normalizeDictKey(value) {
				const raw = String(value == null ? '' : value).trim()
				if (!raw) return ''
				if (/^-?\d+(\.0+)?$/.test(raw)) {
					return String(parseInt(raw, 10))
				}
				return raw
			},
			formatDictValue(options, value, emptyText = '-') {
				const dict = (options && typeof options === 'object') ? options : {}
				const key = this.normalizeDictKey(value)
				if (!key) return emptyText
				return dict[key] || key
			},
			normalizeDeviceId(value) {
				return String(value == null ? '' : value).trim().toUpperCase()
			},
			getModuleRows(menuCode, sectionName) {
				return (this.runningDisplayData || []).filter(item => item.menuCode === menuCode && item.sectionName === sectionName)
			},
			getFieldName(fieldCode) {
				if (!fieldCode) {
					return ''
				}
				const index = fieldCode.lastIndexOf('__')
				return index >= 0 ? fieldCode.slice(index + 2) : fieldCode
			},
			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] === undefined || map[fieldName] === null || map[fieldName] === '') {
						map[fieldName] = item
					}
				})
				return map
			},
			getFieldMap(rows = [], deviceId = '') {
				const rowMap = this.getFieldRowMap(rows, deviceId)
				return Object.keys(rowMap).reduce((acc, fieldName) => {
					const row = rowMap[fieldName] || {}
					acc[fieldName] = row.fieldValue
					return acc
				}, {})
			},
			getLatestTime(menuCode) {
				const times = (this.runningDisplayData || [])
					.filter(item => item.menuCode === menuCode && item.valueTime)
					.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())}`
			},
			getPcsDeviceList() {
				return getPcsNameList(this.siteId).then((response) => {
					this.pcsDeviceList = response?.data || []
				}).catch(() => {
					this.pcsDeviceList = []
				})
			},
			buildPcsList() {
				const devices = this.pcsDeviceList || []
				this.list = devices.map((device) => ({
					...this.getFieldMap(this.getModuleRows('SBJK_PCS', '电参量'), device.deviceId || device.id || ''),
					deviceId: device.deviceId || device.id || '',
					deviceName: device.deviceName || device.name || device.deviceId || device.id || 'PCS',
					...this.getFieldMap(this.getModuleRows('SBJK_PCS', '状态'), device.deviceId || device.id || ''),
					dataUpdateTime: this.getLatestTime('SBJK_PCS'),
					alarmNum: 0,
					pcsBranchInfoList: [],
				}))
			},
			getHeadCardImg(item, index) {
				const imgMap = {
					totalActivePower: 'ssyggl',
					totalReactivePower: 'sswggl',
					soc: 'soc',
					soh: 'soh',
					dayChargedCap: 'jrcdl',
					dayChargedCap_rt: 'jrcdl',
					dayDisChargedCap: 'jrfdl',
					dayDisChargedCap_rt: 'jrfdl'
				}
				const defaultImgs = ['ssyggl', 'sswggl', 'soc', 'soh', 'jrcdl', 'jrfdl']
				return imgMap[item.fieldCode] || defaultImgs[index % defaultImgs.length]
			},
			handleCardClass(item) {
				const workStatus = this.normalizeDictKey((item && item.workStatus) || '')
				const statusOptions = (this.PCSWorkStatusOptions && typeof this.PCSWorkStatusOptions === 'object')
					? this.PCSWorkStatusOptions
					: {}
				const hasStatus = Object.prototype.hasOwnProperty.call(statusOptions, workStatus)
				return workStatus === '1' || !hasStatus
					? "timing-collapse-item"
					: workStatus === '2'
						? 'warning-collapse-item'
						: 'running-collapse-item'
			},
			handleTagClick(deviceId) {
				this.selectedPcsId = deviceId || ''
			},
		},
		onLoad(options) {
			uni.showLoading()
			this.siteId = options.siteId || ''
			Promise.all([
				getProjectDisplayData(this.siteId),
				this.getPcsDeviceList()
			]).then(([displayResponse]) => {
				this.runningDisplayData = displayResponse?.data || []
				this.buildPcsList()
				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>
	.info-overview-scroll {
		background: #fff;
		padding: 0 20rpx;
		white-space: nowrap;
	}

	.info-overview-row {
		display: inline-flex;
		gap: 20rpx;
		padding: 20rpx 0;
	}

	.info-overview-card {
		width: 280rpx;
		flex: 0 0 auto;
	}

	.grid-item-box {
		box-shadow: 0 0 5px 1px rgba(0, 0, 0, 0.08);
		border-radius: 20rpx;
		padding: 20rpx;
		background: #fff;
	}

	.grid-item-box .title {
		color: #333;
		margin-top: 10rpx;
	}

	.grid-item-box .text {
		color: #000;
		white-space: nowrap;
		text-overflow: ellipsis;
		width: 100%;
		overflow-x: hidden;
		text-align: center;
	}

	.icon {
		height: 100rpx;
		width: 100rpx;
		display: block;
		border-radius: 20rpx;
	}

	.pcs-tags-scroll {
		background: #fff;
		padding: 0 20rpx 20rpx;
		white-space: nowrap;
	}

	.pcs-tags-row {
		display: inline-flex;
		gap: 16rpx;
	}

	.pcs-tag-item {
		flex: 0 0 auto;
		padding: 8rpx 22rpx;
		border-radius: 999rpx;
		border: 1px solid #dcdfe6;
		color: #606266;
		font-size: 24rpx;
		line-height: 1.4;
		background: #fff;
	}

	.pcs-tag-item.active {
		color: #fff;
		background: #007aff;
		border-color: #007aff;
	}
</style>
