<route lang="json5" type="page">
	{
	layout: 'default',
	style: {
	navigationStyle: 'custom',
	navigationBarTitleText: '历史数据图表',
	},
	}
</route>

<template>
	<PageLayout :navbarShow="false" class="page-layout">
		<view style="color: blue;font-size:18px;text-align: center;margin: 10px;width: 100%;">
			<wd-text :text="jldData.jldname+ '实时趋势'" style="color: blue;font-size:18px;"></wd-text>
		</view>
		<view>
			<uni-datetime-picker type="datetimerange" v-model="lssjTimeRange" @change="getTime" start-placeholder="开始时间"
				end-placeholder="结束时间" />
		</view>
		<view style="text-align: center;padding: 5px;">

			<wd-button custom-class="custom-value" size="small" plain clickable @click="handleForward">前一天</wd-button>
			<wd-button custom-class="custom-value" size="small" plain clickable @click="handleNext">后一天</wd-button>
			<wd-button custom-class="custom-value" size="small" plain clickable @click="handleQuery">查询数据</wd-button>
			<wd-button custom-class="custom-value" size="small" plain clickable @click="handleDrawLine">生成曲线</wd-button>


		</view>
		<view>
			<scroll-view direction="vertical" style="height: 200px;">
				<wd-table :data="chartData" height="200px">
					<wd-table-col prop="createTime" label="日期" align="center"></wd-table-col>
					<wd-table-col prop="jldName" label="计量点名称" align="center"></wd-table-col>
					<wd-table-col prop="yl" label="压力(MPa)" align="center"></wd-table-col>
					<wd-table-col prop="wd" label="温度(℃)" align="center"></wd-table-col>
					<wd-table-col prop="yc" label="差压(kPa)" align="center"></wd-table-col>
					<wd-table-col prop="ssll" label="瞬时流量(m³/d)" align="center">
					</wd-table-col>
					<wd-table-col prop="jrl" label="今日流量(m³)" align="center">
					</wd-table-col>
				</wd-table>
			</scroll-view>
		</view>
		<view v-if="drawLineFlag">
			<cxc-szcx-multiLineChart :data-list="chartData" time-field="createTime" :fields="lineFields"
				title="文增伴生气外输数据趋势" height="300"></cxc-szcx-multiLineChart>
		</view>

	</PageLayout>
</template>

<script setup>
	import {
		queryJldDataByJldID
	} from '@/api/production'
	import {
		formatDate
	} from '@/utils/dateTime.ts';
	import {
		ref,
		onMounted,
		computed,
		nextTick,
		watchEffect,
		onUnmounted,
	} from 'vue';

	const lineFields = ref([{
			field: 'yl',
			name: '压力',
			referenceValue: 0.73
		},
		{
			field: 'wd',
			name: '温度',
			color: '#ff6347'
		},
		{
			field: 'yc',
			name: '压力差'
		},
		{
			field: 'ssll',
			name: '瞬时流量'
		},
		{
			field: 'jrl',
			name: '累计流量'
		}
	])

	const props = defineProps({
		jldData: {
			type: Object,
			default: () => {}
		}
	})
	const chartData = ref([])
	const drawLineFlag = ref(false)

	function handleQuery() {

		const jldid = props.jldData.id;
		queryJldDataByJldID({
			jldId: jldid,
			startTime: startTime.value,
			endTime: endTime.value
		}).then(res => {
			chartData.value = JSON.parse(res.result)

			chartData.value.forEach(item => {
				item.createTime = formatDate(item.createTime, "YYYY-MM-DD HH:mm ss")
			})
			console.log(123, chartData.value)
		})


	}

	function handleDrawLine() {
		drawLineFlag.value = true
	}
	// 前一天 - 以当前选择的起始日期为基准计算
	function handleForward() {
		// 使用当前选择的开始时间作为基准，而不是系统当前时间
		lssjTimeRange.value = getDefaultTimeRange(-1);
	}

	// 后一天
	function handleNext() {
		// 获取当前选择的开始时间
		const currentStart = new Date(startTime.value);
		// 获取今天8点的时间对象
		const today8AM = new Date();
		today8AM.setHours(8, 0, 0, 0);

		// 允许切换到今天及之前的日期范围
		if (currentStart < today8AM || isSameDay(currentStart, today8AM)) {
			lssjTimeRange.value = getDefaultTimeRange(1);
		} else {
			// 可添加提示：已经是最新数据
			uni.showToast({
				title: '已是最新数据',
				icon: 'none',
				duration: 1500
			});
		}
	}

	// 获取指定日期偏移的时间范围（每天8:00至次日7:59）
	const getDefaultTimeRange = (days) => {
		// 防止原日期对象被污染，使用当前选择的开始时间作为基准
		var baseDate;
		if (startTime.value && new Date(startTime.value).toString() !== 'Invalid Date') {
			baseDate = new Date(startTime.value);
		} else {
			// 如果选择的时间无效，则使用当前时间作为 fallback
			baseDate = new Date();
		}

		// 计算目标日期（基础日期 + 偏移天数）
		const targetDate = new Date(baseDate);
		targetDate.setDate(baseDate.getDate() + days);

		// 构建开始时间：目标日期的8:00:00
		const start = new Date(targetDate);
		start.setHours(8, 0, 0, 0);

		// 构建结束时间：目标日期+1天的7:59:59
		const end = new Date(targetDate);
		end.setDate(targetDate.getDate() + 1);
		end.setHours(7, 59, 59, 0);

		// 格式化时间字符串
		const formattedStart = formatDate(start, 'YYYY-MM-DD HH:mm:ss');
		const formattedEnd = formatDate(end, 'YYYY-MM-DD HH:mm:ss');

		// 更新响应式变量
		startTime.value = formattedStart;
		endTime.value = formattedEnd;

		return [formattedStart, formattedEnd];
	};

	// 辅助函数：判断两个日期是否是同一天
	const isSameDay = (date1, date2) => {
		return date1.getFullYear() === date2.getFullYear() &&
			date1.getMonth() === date2.getMonth() &&
			date1.getDate() === date2.getDate();
	};

	onMounted(() => {
		// 设置默认时间范围  需要延时等控件渲染好
		setTimeout(() => {
			lssjTimeRange.value = getDefaultTimeRange(0)
		}, 500)

		console.log(lssjTimeRange.value);
	})
	const startTime = ref('')
	const endTime = ref('')
	const lssjTimeRange = ref([])


	// 时间选择变化
	const getTime = (e) => {
		if (e && e.length === 2) {
			startTime.value = formatDate(e[0], 'YYYY-MM-DD HH:mm:ss')
			endTime.value = formatDate(e[1], 'YYYY-MM-DD HH:mm:ss')
			// updateChart()
		}
	}
</script>

<style scoped>

</style>