<template>
	<u-popup :show="visible" mode="bottom" :round="20" :closeable="true" :close-on-click-overlay="false"
		@close="closePopup">
		<view class="internet-detail-container">
			<!-- 标题栏 -->
			<view class="popup-header">
				<text class="popup-title">设备详情</text>
			</view>

			<scroll-view scroll-y class="popup-body">
				<!-- 仪表盘区域 -->
				<view class="gauge-section">
					<view class="section-title">实时数据</view>
					<view class="gauge-grid">
						<view class="gauge-item" v-for="(item, index) in getGaugeData" :key="index">
							<view class="gauge-card" v-for="(listItem, j) in item.list" :key="j">
								<GaugeChart height="250px" :value="listItem.value" :min="listItem.min"
									:max="listItem.max" :title="listItem.name" :unit="listItem.unit"
									:colors="['#5470C6', '#91CC75', '#FAC858', '#EE6666']"
									:options="{ pointer: { itemStyle: { color: '#5470C6' } } }"
									:ref="'gaugeChartRef'" />
							</view>
						</view>
					</view>
				</view>

				<!-- 实时数据列表 -->
				<view class="data-section">
					<view class="section-title">运行状态</view>
					<view class="data-grid">
						<view class="data-item" v-for="(obj, key) in realData" :key="key">
							<view class="data-label">{{ obj.name }}：</view>
							<view class="data-value"
								v-if="obj.dataType&&(obj.dataType.type == 'enum' || obj.dataType.type == 'bool')">
								{{ obj.specs[obj.value] }}
							</view>
							<view class="data-value" v-else>
								{{ obj.value }} <text v-if="obj.unit" class="data-unit">{{ obj.unit }}</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 历史折线图 -->
				<view class="history-section">
					<view class="section-title">历史趋势</view>
					<view class="chart-card" v-for="(item, index) in historyData" :key="index">
						<view class="chart-header">
							<text class="chart-name">{{ item.name }}</text>
							<view class="chart-stats">
								<text class="stat-item">最高值<text class="stat-value">{{ item.maxValue }}
										{{ item.unit }}</text></text>
								<text class="stat-item">最低值<text class="stat-value">{{ item.minValue }}
										{{ item.unit }}</text></text>
								<text class="stat-item">平均值<text class="stat-value avg">{{ item.avgValue }}
										{{ item.unit }}</text></text>
							</view>
						</view>
						<view class="chart-tools">
							<dy-date-time-picker v-model="item.chartTime"
								:typeEnabled="{ date: item.timeType=='date', month:  item.timeType=='month', year:  item.timeType=='year', week:false }"
								placeholder="" />
							<view class="time-type">
								<text :class="{ active: item.timeType === 'date' }"
									@click="dateClick(item, 'date')">日</text>
								<text :class="{ active: item.timeType === 'month' }"
									@click="dateClick(item, 'month')">月</text>
								<text :class="{ active: item.timeType === 'year' }"
									@click="dateClick(item, 'year')">年</text>
							</view>
							<u-button type="primary" size="mini" @click="refreshSingleChart(item)">查询</u-button>
						</view>
						<LineChart :data="item.trendData" title="" xAxisName="时间" :yAxisName="item.unit" height="300px"
							:options="{}" />
					</view>
				</view>
			</scroll-view>
		</view>
	</u-popup>
</template>

<script>
	import GaugeChart from './GaugeChart.vue';
	import LineChart from './LineChart.vue';
	import {
		getRealData,
		getHistoryData,
		getPhysicalModel
	} from '@/api/ledgerAssets/equipment.js';
	import {
		getMonday
	} from '@/utils/utils.js';
	import {
		getAssetInfo
	} from '@/api/repair';
	import dayjs from 'dayjs'
	export default {
		name: 'InternetDetail',
		components: {
			GaugeChart,
			LineChart
		},
		props: {},
		data() {
			return {
				visible: false,
				loading: false,
				realData: [],
				iotDashboardPoint: [],
				info: null,
				dict: {
					chartTime: {
						date: 3,
						month: 2,
						year: 1
					}
				},
				gaugeData: [],
				historyData: [],
				id: null,
			};
		},
		computed: {
			getGaugeData() {
				let list = [];
				let gaugeData = this.iotDashboardPoint.length ?
					this.gaugeData.filter((item) => this.iotDashboardPoint.find((Point) => Point.identifier == item
						.identifier && Point.checked)) :
					this.gaugeData.filter((item, index) => index < 6);
				const perRow = 1;
				for (let i = 0; i < gaugeData.length; i += perRow) {
					list.push({
						list: gaugeData.slice(i, i + perRow)
					});
				}
				// this.$nextTick(() => {
				// 	console.log(this.$refs,'dadas')
				// 	// return
				// 	gaugeData.forEach((item, index) => {

				// 		if (this.$refs.gaugeChartRef[index]) {
				// 			this.$refs.gaugeChartRef[index].handleResize();
				// 		}
				// 	});
				// });
				return list;
			},
		},
		methods: {
			closePopup() {
				this.visible = false;
			},
			async open(id) {
				this.id = id;
				const {
					iotDashboardPoint
				} = await getAssetInfo(id);
				this.iotDashboardPoint = iotDashboardPoint;
				this.info = await getPhysicalModel(id);
				await this.getRealData();
				this.visible = true;
			},
			async getRealData() {
				this.loading = true;
				try {
					const res = await getRealData(this.id);
					this.realData = res;
					const tempData = this.info.properties || [];
					this.realData.forEach((item) => {
						tempData?.forEach((property) => {
							if (property.identifier == item.identifier) {
								item.max = property.dataType.specs.max;
								item.min = property.dataType.specs.min;
								item.propertyUnit = property.dataType.specs.unit;
								item.unitName = property.dataType.specs.unitName;
								item.specs = property.dataType.specs;
								item.dataType = property.dataType;
								item.propertyName = property.name;
								item.accessMode = property.accessMode;
								item.saveHistory = property.saveHistory;
								item.required = property.required;
								item.chartTime = dayjs(new Date()).format('YYYY-MM');
								// item.chartTime =dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss') ;
								item.timeType = 'month';
							}
						});
					});
					const gaugeData = this.realData.filter((item) => item.max !== undefined && item.min !== undefined);
					this.gaugeData = gaugeData;
					const historyPromises = this.gaugeData.map((item) => item.saveHistory ? this.getDefaultHistoryData(
						item) : null);
					this.historyData = await Promise.all(historyPromises);
				} catch (error) {
					console.error('获取数据失败:', error);
				} finally {
					this.loading = false;
				}
			},
			async getDefaultHistoryData(item) {
				const chartTime = item.chartTime
				const timeType = item.timeType || 'month';
				let time = this.getTimeList(chartTime, timeType);
				// if (!time || !time.startTime || !time.endTime) {
				// 	const defaultDate = new Date().toISOString().split('T')[0];
				// 	time = {
				// 		startTime: defaultDate + ' 00:00:00',
				// 		endTime: defaultDate + ' 23:59:59'
				// 	};
				// }
				return {
					identifier: item.identifier || '',
					name: item.name || '',
					unit: item.unit || '',
					unitName: item.unitName || '',
					chartTime,
					timeType,
					trendData: {
						xAxis: [],
						series: [{
							name: '',
							data: [],
							color: '#5470C6'
						}]
					},
					timeHistoryList: []
				};
			},
			async getHistoryDatas(item) {
				try {
					const chartTime = item.chartTime
					const timeType = item.timeType || 'month';
					let time = this.getTimeList(chartTime, timeType);
					// if (!time || !time.startTime || !time.endTime) {
					// 	const defaultDate = new Date().toISOString().split('T')[0];
					// 	time = {
					// 		startTime: defaultDate + ' 00:00:00',
					// 		endTime: defaultDate + ' 23:59:59'
					// 	};
					// }
					// const apiTimeType = this.dict?.chartTime?.[timeType] || 'month';
					const res = await getHistoryData({
						startTime: time.startTime,
						endTime: time.endTime,
						property: item.identifier,
						substanceId: this.id,
						timeType: this.dict.chartTime[timeType]
					});
					const response = res || {};
					const trendData = {
						xAxis: [],
						series: [{
							name: response.name || item.name,
							data: [],
							color: '#5470C6'
						}]
					};
					const timeHistoryList = Array.isArray(response.timeHistoryList) ? response.timeHistoryList : [];
					timeHistoryList.forEach((i) => {
						if (i && i.time !== undefined && i.value !== undefined) {
							trendData.xAxis.push(i.time);
							trendData.series[0].data.push(i.value);
						}
					});
					return {
						...response,
						identifier: item.identifier || '',
						name: item.name || '',
						unit: item.unit || '',
						unitName: item.unitName || '',
						chartTime,
						timeType,
						trendData,
						timeHistoryList
					};
				} catch (error) {
					console.error(`获取属性 ${item.name || item.identifier} 的历史数据失败:`, error);
					return {
						identifier: item.identifier || '',
						name: item.name || '',
						unit: item.unit || '',
						unitName: item.unitName || '',
						chartTime: item.chartTime || new Date(),
						timeType: item.timeType || 'month',
						trendData: {
							xAxis: [],
							series: [{
								name: item.name || '',
								data: [],
								color: '#5470C6'
							}]
						},
						timeHistoryList: []
					};
				}
			},
			async refreshSingleChart(item) {
				try {
					const updatedData = await this.getHistoryDatas(item);
					const index = this.historyData.findIndex((d) => d.identifier === item.identifier);
					if (index !== -1) {
						this.$set(this.historyData, index, updatedData);
					}
				} catch (error) {
					console.error(`刷新图表 ${item.name || item.identifier} 数据失败:`, error);
				}
			},
			dateClick(item, dateType) {
				switch (dateType) {
					case 'date':
						item.chartTime = dayjs(new Date()).format('YYYY-MM-DD');
						break;
					case 'month':
						item.chartTime = dayjs(new Date()).format('YYYY-MM');
						break;
					case 'year':
						item.chartTime = dayjs(new Date()).format('YYYY');
						break;
					default:
						break;
				}

				item.timeType = dateType;
			},
			getTimeList(date, timeType) {
				console.log(date,'date')
				// const fnNum = (num) => num < 10 ? '0' + num : num;
				let startTime, endTime;
				// const ndate = date ? new Date(date) : new Date();
				// const year = ndate.getFullYear();
				// const month = ndate.getMonth() + 1;
				// const day = ndate.getDate();
				switch (timeType) {
					case 'date':

						startTime = date.date|| date + ' 00:00:00';
						endTime = date.date|| date + ' 23:59:59';
						break;
					case 'month':
						const mon = getMonday(date.month || date);
						startTime = mon[0] + ' 00:00:00';
						endTime = mon[1] + ' 23:59:59';
						break;
					case 'year':
						startTime = date.year|| date + '-01-01 00:00:00';
						endTime = date.year|| date + '-12-31 23:59:59';
						break;
					default:
						break;
				}
				return {
					startTime,
					endTime
				};
			},
		},
	};
</script>

<style scoped lang="scss">
	.internet-detail-container {
		// display: flex;
		// flex-direction: column;
		height: calc(100vh - 100rpx);
		background: #f5f7fa;
	}

	.popup-header {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 30rpx 0;
		background: #fff;
		border-bottom: 1rpx solid #eee;

		.popup-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}
	}

	.popup-body {
		flex: 1;
		padding: 20rpx;
		height: 100%;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #303133;
		margin-bottom: 20rpx;
		padding-left: 20rpx;
		border-left: 8rpx solid #1890ff;
	}

	.gauge-section {
		margin-bottom: 30rpx;
	}

	.gauge-grid {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.gauge-item {
		display: flex;
		gap: 20rpx;
		width: 100%;
	}

	.gauge-card {
		flex: 1;
		min-width: 200rpx;
		background: #fff;
		border-radius: 20rpx;
		padding: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	}

	.data-section {
		margin-bottom: 30rpx;
	}

	.data-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 20rpx;
	}

	.data-item {
		display: flex;
		align-items: center;
		background: #fff;
		padding: 24rpx;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.data-label {
		font-size: 28rpx;
		color: #666;
		margin-right: 10rpx;
	}

	.data-value {
		font-size: 30rpx;
		color: #333;
		font-weight: bold;
	}

	.data-unit {
		font-size: 24rpx;
		color: #999;
	}

	.history-section {
		margin-bottom: 30rpx;
	}

	.chart-card {
		background: #fff;
		border-radius: 20rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	}

	.chart-header {
		margin-bottom: 20rpx;
	}

	.chart-name {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 16rpx;
	}

	.chart-stats {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.stat-item {
		font-size: 26rpx;
		color: #666;
	}

	.stat-value {
		font-weight: bold;
		color: #ff3e52;
		margin-left: 8rpx;

		&.avg {
			color: #0840d5;
		}
	}

	.chart-tools {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		gap: 16rpx;
		margin-bottom: 20rpx;
	}

	.time-type {
		display: flex;
		gap: 16rpx;

		text {
			font-size: 28rpx;
			color: #666;
			padding: 8rpx 20rpx;
			border-radius: 8rpx;
			background: #f0f0f0;

			&.active {
				background: #1890ff;
				color: #fff;
			}
		}
	}
</style>