<route lang="json5" type="page">
	{
	layout: 'default',
	style: {
	navigationStyle: 'custom',
	navigationBarTitleText: '历史数据',
	},
	}
</route>
<template>
	<PageLayout navTitle="历史数据">
		<view class="stats-container">
			<uni-title v-if="type === 'trq'" :title="name.unit + '天然气---单位（万方）'" color="blue" type="h2"></uni-title>
			<uni-title v-if="type === 'yy'" :title="name.dw + '原油---单位（吨）'" color="blue" type="h2"></uni-title>
		</view>
		<view class="dateSelect">
			<cxc-szcx-dateRangeSelect :mode="'range'" v-model="dateRange"></cxc-szcx-dateRangeSelect>
		</view>
		<cxc-szcx-lineChart v-if="type === 'trq'" :dataList="dataList" x-field="rqDate" y-field="rq" legend-field="unit"
			:reference-value="0"></cxc-szcx-lineChart>

		<cxc-szcx-lineChart v-if="type === 'yy'" :dataList="dataList" x-field="scrq" y-field="rcwy" legend-field="dw"
			:reference-value="0"></cxc-szcx-lineChart>
		<view style="margin: 0 15px">
			<view class="stats-container">
				<view class="stats-item">最大值: {{ dataStats.max }}</view>
				<view class="stats-item">最小值: {{ dataStats.min }}</view>
				<view class="stats-item">平均值: {{ dataStats.average }}</view>
			</view>
			
			<wd-table :data="dataList" :height="800" v-if="type === 'trq'" :index="true">
				<wd-table-col prop="unit" label="名称" :width="screenWidth / 3" align="center"></wd-table-col>
				<wd-table-col prop="rqDate" label="日期" :width="screenWidth / 4" align="center"></wd-table-col>
				<wd-table-col prop="rq" label="日气量" :width="screenWidth / 5" align="center"></wd-table-col>
			</wd-table>

			<wd-table :data="dataList" :height="800" v-if="type === 'yy'" :index="true">
				<wd-table-col prop="dw" label="名称" :width="screenWidth / 3" align="center"></wd-table-col>
				<wd-table-col prop="scrq" label="日期" :width="screenWidth / 4" align="center"></wd-table-col>
				<wd-table-col prop="rcwy" label="日油量" :width="screenWidth / 5" align="center"></wd-table-col>
			</wd-table>

		</view>
	</PageLayout>
</template>

<script setup>
	import {
		queryJinriShengchansj,
		queryJinriYuanyouShengchansj
	} from '@/api/production';
	import {
		formatDate,
		getDateAfterDays,
		getDateAfterMonths
	} from '@/utils/dateTime';
	const name = ref({});
	const type = ref('');
	const dateRange = ref([]);
	const dataList = ref([]);
	const endDate = ref('');
	const startDate = ref('');
	const dataStats = ref({
		min: 0,
		max: 0,
		avg: 0
	});
	const screenWidth = ref(0)
	const calculateTableHeight = () => {
		const systemInfo = uni.getSystemInfoSync();
		screenWidth.value = systemInfo.screenWidth;
	}
	const getJinriShengchansj = (tempDateRange) => {
		// console.log(tempDateRange);
		// 添加日期有效性检查
		if (!tempDateRange || tempDateRange.some((date) => !convertToDate(date))) {
			console.error('收到无效日期范围:', tempDateRange);
			return;
		}
		let queryParms = {};
		dataList.value = [];
		queryParms.gas = name.value.gas;
		queryParms.unit = name.value.unit;
		queryParms.rqDate_begin = formatDate(tempDateRange[0]);
		queryParms.rqDate_end = formatDate(tempDateRange[1]);
		queryParms.pageSize = 500;

		// 添加参数有效性检查
		if (!queryParms.rqDate_begin || !queryParms.rqDate_end) {
			console.error('参数格式化失败:', queryParms);
			return;
		}
		// console.log(queryParms);
		queryJinriShengchansj(queryParms).then((res) => {
			if (res.success) {
				// console.log(res);
				dataList.value = res.result.records;
				dataStats.value = calculateStats(dataList.value, 'rq');
			}
		});
	};

	const getJinriYuanyouShengchansj = (tempDateRange) => {
		console.log(tempDateRange);
		// 添加日期有效性检查
		if (!tempDateRange || tempDateRange.some((date) => !convertToDate(date))) {
			console.error('收到无效日期范围:', tempDateRange);
			return;
		}
		let queryParms = {};
		dataList.value = [];
		queryParms.dw = name.value.dw;
		queryParms.scrq_begin = formatDate(tempDateRange[0]);
		queryParms.scrq_end = formatDate(tempDateRange[1]);
		queryParms.pageSize = 500;

		// 添加参数有效性检查
		if (!queryParms.scrq_begin || !queryParms.scrq_end) {
			console.error('参数格式化失败:', queryParms);
			return;
		}
		console.log(queryParms);
		queryJinriYuanyouShengchansj(queryParms).then((res) => {
			if (res.success) {
				console.log(res);
				dataList.value = res.result.records;
				dataStats.value = calculateStats(dataList.value, 'rcwy').reverse();
			}
		});
	};

	function calculateStats(data, field) {
		// 过滤掉 field 字段值为 null 或 undefined 的数据
		const validData = data.filter((item) => item[field] !== null && item[field] !== undefined);
		if (validData.length === 0) {
			return {
				max: null,
				min: null,
				average: null
			};
		}
		// 初始化最大值、最小值和总和
		let max = validData[0][field];
		let min = validData[0][field];
		let sum = 0;

		// 遍历有效数据
		for (let i = 0; i < validData.length; i++) {
			const value = validData[i][field];
			// 更新最大值
			if (value > max) {
				max = value;
			}
			// 更新最小值
			if (value < min) {
				min = value;
			}
			// 累加值到总和
			sum += value;
		}
		// 计算平均值
		const average = (sum / validData.length).toFixed(4);

		return {
			max: max,
			min: min,
			average: average
		};
	}

	function convertToDate(str) {
		try {
			const date = new Date(str);
			// 判断日期是否有效
			if (isNaN(date.getTime())) {
				return false;
			}
			return true;
		} catch (error) {
			return false;
			//TODO handle the exception
		}
	}
	// 修改后（正确）
	watch(
		[() => type.value, dateRange], // 监听 type 和 dateRange
		([newType, newDateRange]) => {
			if (!newDateRange || !convertToDate(newDateRange[0]) || !convertToDate(newDateRange[1])) {
				// console.error('无效的日期范围:', newDateRange);
				return;
			}
			// console.log(newType, newDateRange);

			switch (
				newType // 直接使用 newType
			) {
				case 'trq':
					getJinriShengchansj(newDateRange);
					break;
				case 'yy':
					getJinriYuanyouShengchansj(newDateRange);
					break;
				default:
					console.warn('未知类型:', newType);
			}
		}, {
			immediate: true,
			deep: true
		}
	);
	onMounted(() => {
		// nextTick();
		// getJinriShengchansj(dateRange.value);
		calculateTableHeight();
		// 监听屏幕旋转变化
		uni.onWindowResize(() => {
			calculateTableHeight();
		});
	});

	onLoad((options) => {
		name.value = JSON.parse(options.data);
		type.value = options.type;
		// console.log(name.value, type.value);
		const now = new Date();

		if (now.getHours() < 11) {
			endDate.value = getDateAfterDays(now, -1); //11点之前  头一天的数据
			startDate.value = getDateAfterMonths(endDate.value, -1); //11点之前  头一天的数据
		} else {
			endDate.value = now;
			startDate.value = getDateAfterMonths(endDate.value, -1); //11点之前  头一天的数据
		}
		dateRange.value = [startDate.value, endDate.value];
		// console.log(1111, dateRange.value);
	});
</script>

<style scoped>
	.stats-container {
		display: flex;
		justify-content: space-around;
		align-items: center;
		text-align: center;
		background-color: #f5f5f5;
		border-radius: 4px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		padding: 10px;
		margin: 15 15px;
	}

	.dateSelect {
		display: flex;
		justify-content: space-around;
		align-items: center;
		text-align: center;
		background-color: #f5f5f5;
		border-radius: 8px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		padding: 5px;
		margin: 10px;
	}

	.stats-item {
		font-size: 12px;
		color: #00aa00;
		font-weight: bold;
	}

	.stats-item+.stats-item {
		border-left: 1px solid #ccc;
		padding-left: 16px;
	}
</style>