<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 class="picker-year" v-model="queryParams.startTime" type="year" value-format="YYYY" placeholder="选择开始年">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="结束时间">
					<el-date-picker class="picker-year" v-model="queryParams.endTime" type="year" value-format="YYYY" placeholder="选择结束年">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="月份">
					<el-select v-model="queryParams.month" placeholder="请选择月份" class="w150" @change="changeMonth">
						<el-option v-for="dict in interval_options" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
					</el-select>
				</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-if="direction == 'zx'" 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>
				<el-table  v-if="direction == 'hx'" v-table-height v-loading="loading" :data="tableData" border :span-method="arraySpanMethod">
					<el-table-column v-for="column in tableColumns" :key="column.prop" :prop="column.prop" :label="column.label" :min-width="column.width || 120" align="center">
					</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(1, 'year').format('YYYY'),
		endTime: dayjs().format('YYYY'),
		stnmIds: '',
		month: dayjs().month() + 1,
	});


	const tableTitle = computed(() => {
		return queryParams.month == 'all' ? '全年历史降水量表' : queryParams.month + '月份历史降水量表';
	});
	const tableColumns = ref([])
	const tableData = ref([])

	const loading = ref(false)

	// 修改 getList 函数来处理动态列和数据
	const getList = async () => {
		loading.value = true;
		try {
			let res = await proxy.axiosPost2('/report/rainmonthhistory', 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) => {
		const { ys, list } = res.data;

		// 构建表头列
		let columns = [
			{
				prop: "name",
				label: "站点名称",
			}
		];

		// 分离年份数据和统计项数据
		const yearItems = list.filter(item => !['均值', '最大值', '最小值'].includes(item.year));
		const statItems = list.filter(item => ['均值', '最大值', '最小值'].includes(item.year));

		// 添加年份列
		yearItems.forEach(item => {
			columns.push({
				prop: item.year,
				label: item.year
			});
		});

		// 添加统计列
		const statPropMap = {
			'均值': 'avg',
			'最大值': 'max',
			'最小值': 'min'
		};

		statItems.forEach(item => {
			const prop = statPropMap[item.year];
			if (prop) {
				columns.push({
					prop: prop,
					label: item.year
				});
			}
		});

		tableColumns.value = columns;

		// 处理表格数据
		const processedData = [];

		// 处理站点数据
		ys.forEach((station) => {
			const stationId = station.stnmId;
			// 创建数据行和年份行
			const dataRow = { name: station.stnm };
			const yearRow = { name: station.stnm };

			// 填充年份数据
			yearItems.forEach(yearItem => {
				const value = yearItem[stationId] || '';
				dataRow[yearItem.year] = value;
				yearRow[yearItem.year] = '';
			});

			// 填充统计值（分离数值和年份）
			statItems.forEach(statItem => {
				const prop = statPropMap[statItem.year];
				if (prop) {
					const value = statItem[stationId] || '';
					if (value && value.includes('/')) {
						const [yearPart, valuePart] = value.split('/');
						dataRow[prop] = valuePart;
						yearRow[prop] = yearPart;
					} else {
						dataRow[prop] = value;
						yearRow[prop] = '';
					}
				}
			});

			processedData.push(dataRow);
			processedData.push(yearRow);
		});

		// 计算并添加平均行
		if (ys.length > 0) {
			const avgDataRow = { name: '平均' };
			const avgYearRow = { name: '平均' };

			// 计算年份列的平均值
			yearItems.forEach(yearItem => {
				const values = ys.map(station => {
					const stationId = station.stnmId;
					return parseFloat(yearItem[stationId]) || 0;
				});
				const avg = values.reduce((sum, val) => sum + val, 0) / values.length;
				avgDataRow[yearItem.year] = avg.toFixed(1);
				avgYearRow[yearItem.year] = '';
			});

			// 处理统计项的平均值
			statItems.forEach(statItem => {
				const prop = statPropMap[statItem.year];
				if (prop) {
					const value = statItem.avg || '';
					if (value && value.includes('/')) {
						const [yearPart, valuePart] = value.split('/');
						avgDataRow[prop] = valuePart;
						avgYearRow[prop] = yearPart;
					} else {
						avgDataRow[prop] = value;
						avgYearRow[prop] = '';
					}
				}
			});

			processedData.push(avgDataRow);
			processedData.push(avgYearRow);
		}

		tableData.value = processedData;
	}
	const getHxTableData = (res) => {
		const { ys, list } = res.data;

		// 构建表头列
		const columns = [
			{
				prop: 'year',
				label: '年份',
			},
		];

		ys.forEach(station => {
			columns.push({
				prop: station.stnmId,
				label: station.stnm,
			});
		});

		columns.push({
			prop: 'avg',
			label: '平均',
		});

		tableColumns.value = columns;

		const processedData = [];

		// 分离年份和统计项
		const yearItems = list.filter(item => !['均值', '最大值', '最小值'].includes(item.year));
		const statItems = list.filter(item => ['均值', '最大值', '最小值'].includes(item.year));

		// 添加年份行
		yearItems.forEach(item => {
			const row = { year: item.year };
			ys.forEach(station => {
				row[station.stnmId] = item[station.stnmId];
			});
			row.avg = item.avg;
			processedData.push(row);
		});
		// 添加统计项行（均值、最大值、最小值）
		statItems.forEach(statItem => {
			const statName = statItem.year;
			const valueRow = { year: statName };
			// 只有当存在年份信息时，才添加年份行
			const yearRow = { year: '' };

			// 填充数值行
			ys.forEach(station => {
				const value = statItem[station.stnmId];
				if (value && value.includes('/')) {
					const [yearPart, valPart] = value.split('/');
					valueRow[station.stnmId] = valPart;
				} else {
					valueRow[station.stnmId] = value;
				}
			});

			// 填充平均值
			if (statItem.avg && statItem.avg.includes('/')) {
				const [yearPart, valuePart] = statItem.avg.split('/');
				valueRow.avg = valuePart;
				yearRow.avg = yearPart;
			} else {
				valueRow.avg = statItem.avg;
				yearRow.avg = '';
			}
			processedData.push(valueRow);

			ys.forEach(station => {
				const value = statItem[station.stnmId];
				if (value && value.includes('/')) {
					const [yearPart, _] = value.split('/');
					yearRow[station.stnmId] = yearPart;
				} else {
					yearRow[station.stnmId] = '';
				}
			});

			// 如果所有站点都没有年份信息，则不添加该行
			if (!Object.values(yearRow).some(v => v)) {
				return; // 跳过空行
			}

			processedData.push(yearRow);
		});

		tableData.value = processedData;
	};
	// 查询
	const handleQuery = async () => {
		getList()
	}
	const changeMonth = (val) => {
		queryParams.month = val
		handleQuery()
	}
	// 行列合并
	const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
		if (direction.value == 'zx') {
			// 获取总列数
			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];
			}
		} else if (direction.value == 'hx') {
			// 新增 hx 模式下的合并逻辑：基于内容判断
			if (columnIndex === 0) {
				const currentRow = row.year;
				const nextRow = tableData.value[rowIndex + 1]?.year;

				// 如果当前行是“最大值”或“最小值”，且下一行为空（即年份行），则合并两行
				if ((currentRow === '最大值' || currentRow === '最小值') && !nextRow) {
					return [2, 1]; // 合并两行
				}
				// 如果当前行是空行（即年份行），且上一行是“最大值”或“最小值”，则隐藏当前行
				if (!currentRow && (tableData.value[rowIndex - 1]?.year === '最大值' || tableData.value[rowIndex - 1]?.year === '最小值')) {
					return [0, 0]; // 隐藏当前行
				}
			}
		}
		return [1, 1]; // 默认不合并
	}

	const interval_options = ref([
		{ value: "01", label: "1月" },
		{ value: "02", label: "2月" },
		{ value: "03", label: "3月" },
		{ value: "04", label: "4月" },
		{ value: "05", label: "5月" },
		{ value: "06", label: "6月" },
		{ value: "07", label: "7月" },
		{ value: "08", label: "8月" },
		{ value: "09", label: "9月" },
		{ value: "10", label: "10月" },
		{ value: "11", label: "11月" },
		{ value: "12", label: "12月" },
		{ value: "all", label: "全年" },
	])
</script>