<template>
	<div class="app-container app-container-bg">
		<el-card class="first-card" ref='firstCard' shadow="always">
			<el-form :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>
				<el-form-item label="开始时间">
					<el-date-picker v-model="queryParams.startTime" type="datetime" value-format="MM-DD" format="YYYY-MM-DD HH:mm:ss" placeholder="选择开始时间" :disabled-date="disabledStartDate">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="结束时间">
					<el-date-picker v-model="queryParams.endTime" type="datetime" value-format="MM-DD" format="YYYY-MM-DD HH:mm:ss" placeholder="选择结束时间" :disabled-date="disabledEndDate">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="年份区间">
					<el-date-picker class="picker-year" style="width:120px" v-model="yearstart" type="year" value-format="YYYY" placeholder="选择开始年">
					</el-date-picker>
                    <span class="pr10 pl10"> - </span>
					<el-date-picker class="picker-year" style="width:120px" v-model="yearend" type="year" value-format="YYYY" placeholder="选择结束年">
					</el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
				</el-form-item>
				<br />
				<el-form-item label="报表排列方式（按站点）">
					<el-radio-group v-model="direction" @change="getList">
						<el-radio label="zx">纵向</el-radio>
						<el-radio label="hx">横向</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
		</el-card>
		<splitpanes :horizontal="device === 'mobile'" class="el-card-p card-shadow carder-border mt10 pad10 default-theme container-box" :push-other-panes="false">
			<pane :size="firstSize" :min-size="SPLITPANES_CONFIG.MIN_SIZE" :max-size="SPLITPANES_CONFIG.MAX_SIZE" ref="firstPane" class="mr10">
				<e-tree ref="eTreeRef" :stationType="stationType" @stationChange="handleStationChange" @loadingChange="handleStationLoading"></e-tree>
			</pane>
			<pane :size="100 - firstSize" style="height: 100%;">
				<div class="main-table-header">
					<div class="table-title">{{tableTitle}}</div>
				</div>
				<el-table v-table-height v-loading="loading" :data="tableData" border :span-method="arraySpanMethod">
					<el-table-column :align="alignment" v-for="column in tableColumns" :key="column.prop" :prop="column.prop" :label="column.label" :min-width="column.width || 120">
					</el-table-column>
				</el-table>
			</pane>
		</splitpanes>

	</div>
</template>
<script setup>
	import dayjs from 'dayjs';
	import {
		Splitpanes,
		Pane
	} from 'splitpanes'
	import 'splitpanes/dist/splitpanes.css'
	import ETree from '@/components/ETree/index.vue'
	import useAppStore from '@/store/modules/app'
	const device = computed(() => useAppStore().device);

	const props = defineProps({
	})
	const {
		proxy
	} = getCurrentInstance()
	const { update_type_options } = proxy.useDict("update_type_options")
	const stationType = 'A'
	const alignment = 'center'
	const firstSize = ref(proxy.SPLITPANES_CONFIG.DEFAULT_SIZE)
	const direction = ref('zx')
	const eTreeRef = ref(null)
	let stnmIdsList = []
	const handleStationLoading = (loadingState) => {
		loading.value = loadingState;
	}
	// 新增处理站点变化的函数
	const handleStationChange = (stnmIds) => {
		stnmIdsList = stnmIds
		queryParams.stnmIds = stnmIds.join(',')
		if (stnmIdsList.length == 0) {
			proxy.$modal.msgWarning("请选择站点后查询");
			return
		} else if (stnmIdsList.length > 50) {
			proxy.$modal.msg("站点最多可选择50个");
			return
		} else {
			getList()

		}
	}
	const yearstart = ref(dayjs().subtract(1, 'year').format('YYYY'))
	const yearend = ref(dayjs().format('YYYY'))
	const queryParams = reactive({
		startTime: dayjs().subtract(7, 'day').format('MM-DD'),
		endTime: dayjs().format('MM-DD'),
		years: `${yearstart.value}-${yearend.value}`,
		stnmIds: '',
	});

	// 禁用开始时间选择器中大于当前时间和结束时间的日期
	const disabledStartDate = (time) => {
		const endTime = queryParams.endTime ? dayjs(queryParams.endTime) : null;
		return dayjs(time).isAfter(dayjs()) ||
			(endTime && dayjs(time).isAfter(endTime));
	};

	// 禁用结束时间选择器中大于当前时间和小于开始时间的日期
	const disabledEndDate = (time) => {
		const startTime = queryParams.startTime ? dayjs(queryParams.startTime) : null;
		return dayjs(time).isAfter(dayjs()) ||
			(startTime && dayjs(time).isBefore(startTime));
	};

	const tableTitle = computed(() => {
		const startFormatted = dayjs(queryParams.startTime, 'MM-DD').format('MM月DD日');
		const endFormatted = dayjs(queryParams.endTime, 'MM-DD').format('MM月DD日');
		return `${startFormatted}~${endFormatted}历史同期降水量表(mm)`;
	});
	const tableColumns = ref([])
	const tableData = ref([])
	const loading = ref(false)

	// 修改 getList 函数来处理动态列和数据
	const getList = async () => {
		loading.value = true;
		try {
			let res = await proxy.axiosPost2('/report/rainhistorycount', queryParams)
			if (res.code == 0) {
				if (direction.value == 'zx') {
					getZXTableData(res)
				} else {
					getHXTableData(res)
				}

			}
		} catch (error) {
			tableColumns.value = [];
			tableData.value = [];
		} finally {
			loading.value = false
		}
	}
	const getZXTableData = (res) => {
		let { year, list, name, max, min } = res.data;
		let columns = [
			{
				prop: "station",
				label: "站点"
			},
			{
				prop: "type",
				label: ""
			}
		]
		// 添加站点列
		year.forEach(item => {
			columns.push({
				prop: item,
				label: item
			});
		});
		tableColumns.value = columns
		// 处理数据部分 - 构造两行合并的数据结构
		const processedData = [];

		list.forEach((item, index) => {
			// 第一行：显示站点名称和"雨量"
			const row1 = {
				station: name[index],
				type: "平均水位"
			};
			year.forEach(y => {
				row1[y] = item[0].value ? item[0].value.toFixed(1) : '-';
			});
			// const row2 = {
			// 	station: name[index],
			// 	type: "最高水位"
			// };
			// year.forEach(y => {
			// 	row2[y] = item[0].value ? item[0].value.toFixed(1) : '-';
			// });
			// const row3 = {
			// 	station: name[index],
			// 	type: "时间"
			// };
			// year.forEach(y => {
			// 	row3[y] = item[0].tm ? item[0].tm : '-';
			// });
			// const row4 = {
			// 	station: name[index],
			// 	type: "最高水位"
			// };
			// year.forEach(y => {
			// 	row4[y] = item[0].value ? item[0].value.toFixed(1) : '-';
			// });
			// const row5 = {
			// 	station: name[index],
			// 	type: "时间"
			// };
			// year.forEach(y => {
			// 	row5[y] = item[0].tm ? item[0].tm : '-';
			// });
			processedData.push(row1);
			// processedData.push(row2);
			// processedData.push(row3);
			// processedData.push(row4);
			// processedData.push(row5);
		});
		console.log(processedData, 'processedData')
		tableData.value = processedData;
	}
	const getHXTableData = (res) => {
		const { year, list, name, max, min } = res.data;

		if (!year || !list || !name || !max || !min) {
			console.error('数据缺失:', { year, list, name, max, min });
			tableData.value = [];
			return;
		}

		const columns = name.map(stationName => ({
			prop: stationName,
			label: stationName
		}));

		tableColumns.value = columns;
		console.log(columns, 'tableColumns')
		const processedData = [];

		// 添加年份行
		year.forEach(y => {
			const row = { time: y };
			name.forEach((stationName, idx) => {
				const stationIndex = name.indexOf(stationName);
				const stationList = list[stationIndex];
				if (!stationList || stationList.length === 0) {
					row[stationName] = { rain: '-', tm: '-' };
					return;
				}
				const valueItem = stationList[0]; // 假设只有一个记录
				row['rain' + idx] = valueItem.value ? valueItem.value.toFixed(1) : '-'
				row['tm' + idx] = valueItem.tm ? valueItem.tm.slice(5) : '-'
			});
			processedData.push(row);
		});
		// 添加最大值行
		processedData.push({
			time: '最大值',
			...name.reduce((acc, stationName, index) => {
				acc['rain' + index] = max[index]?.value ? max[index]?.value.toFixed(1) : '-';
				acc['tm' + index] = max[index]?.tm ? max[index].tm : '-';
				return acc;
			}, {})
		});

		// 添加最小值行
		processedData.push({
			time: '最小值',
			...name.reduce((acc, stationName, index) => {
				acc['rain' + index] = min[index]?.value ? min[index]?.value.toFixed(1) : '-';
				acc['tm' + index] = min[index]?.tm ? min[index].tm : '-';
				return acc;
			}, {})
		});

		tableData.value = processedData;
	};

	// 查询
	const handleQuery = async () => {
		getList()
	}
	// 行列合并

	const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
		// 获取总列数
		const columnCount = tableColumns.value.length;

		// 如果是最后一列（最大值/最小值列），不进行合并
		if (columnIndex === columnCount - 1 || columnIndex === columnCount - 2) {
			return [1, 1];
		}

		// 第一列（站点名称列）的合并逻辑
		if (columnIndex === 0) {
			// 每两行合并一次
			if (rowIndex % 2 === 0) {
				// 偶数行显示，奇数行隐藏
				return [2, 1];
			} else {
				// 隐藏奇数行
				return [0, 0];
			}
		}

		// 其他数据列的合并逻辑
		if (rowIndex % 2 === 0) {
			// 偶数行显示，奇数行隐藏
			return [2, 1];
		} else {
			// 隐藏奇数行
			return [0, 0];
		}
	}

</script>
<style lang="scss" scoped>
</style>