<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-select v-model="queryParams.dataType" placeholder="请选择时间维度" class="w150" @change="changeDataType">
						<el-option v-for="item in dataTypes" :key="item.value" :label="item.label" :value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="开始时间">
					<el-date-picker v-model="queryParams.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" placeholder="选择开始时间" :disabled-date="disabledStartDate" @change="(val)=>changeTime(val,'start')">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="结束时间">
					<el-date-picker v-model="queryParams.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" placeholder="选择结束时间" :disabled-date="disabledEndDate" @change="(val)=>changeTime(val,'end')">
					</el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
				</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"></e-tree>
			</pane>
			<pane :size="100 - firstSize">
				<splitpanes horizontal class="default-theme" :push-other-panes="false">
					<pane size="50">
						<BarChart v-loading="echartsLoading" :legendData='legendData' :xAxisData="xAxisData" :seriesData="seriesData" :echartType="echartType" :grid="grid" :BarFormatter="false" />
						<!-- <el-tabs v-model="activeName" class="demo-tabs" @tab-change="changeTabs">
							<el-tab-pane label="统计图" name="first" style="height:100%">
								<BarChart v-loading="echartsLoading" :legendData='legendData' :xAxisData="xAxisData" :seriesData="seriesData" :echartType="echartType" />
							</el-tab-pane>
							<el-tab-pane label="趋势图" name="second" style="height:90%">
								<TimeBarChart v-loading="echartsLoading" :legendData='legendData' :xAxisData="xAxisData" :seriesData="seriesData" :echartType="echartType" :timeType="timeType" />
							</el-tab-pane>
						</el-tabs> -->
					</pane>
					<pane size="50" class="mr10">
						<div class="main-table-header">
							<div class="table-title">{{tableTitle}}</div>
							<div class="table-time mb5">
								<div>
									<span>时间: </span><span id="title1">{{ tableTime}}</span>
								</div>
								<div>
									<span>单位: </span><span id="title2">mm</span>
								</div>
							</div>
						</div>
						<el-table class="scrollable-table" v-loading="loading" ref="myTable" :data="tableData" v-table-height="{bottom:90}" border>
							<el-table-column :align="alignment" :width="item.label == '时间' ? '180': '' " :prop="item.prop" :label="item.label" v-for="(item, index) in tableHead" :key="index"></el-table-column>
						</el-table>
					</pane>
				</splitpanes>
			</pane>
		</splitpanes>
	</div>
</template>
<script setup>
	import dayjs from 'dayjs';
	import {
		Splitpanes,
		Pane
	} from 'splitpanes'
	import 'splitpanes/dist/splitpanes.css'
	import BarChart from '@/components/ChartsBar/index.vue'
	import TimeBarChart from '@/components/ChartsDataZoom/index.vue'
	import ETree from '@/components/ETree/index.vue'

	import useAppStore from '@/store/modules/app'
	const device = computed(() => useAppStore().device);

	const props = defineProps({
		tableTitle: {
			type: String,
			default: '时段降雨量'
		},
	})
	const { proxy } = getCurrentInstance()
	const stationType = 'A'
	const alignment = 'center'
	const eTreeRef = ref(null)
	let stnmIdsList = []
	// 新增处理站点变化的函数
	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()
			getEchartsData()
		}
	}
	const queryParams = reactive({
		startTime: dayjs().subtract(7, 'day').format('YYYY-MM-DD 08:00:00'),
		endTime: dayjs().format('YYYY-MM-DD 08:00:00'),
		dataType: '0',
	});

	// 禁用开始时间选择器中大于当前时间和结束时间的日期
	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 tableTime = ref(queryParams.startTime.substring(0, 16) + " 至 " + queryParams.endTime.substring(0, 16))
	const timeType = ref('day')
	// 改变时间纬度
	const changeDataType = (val) => {
		queryParams.dataType = val
		if (val == 0) {
			tableTime.value = queryParams.startTime.substring(0, 16) + " 至 " + queryParams.endTime.substring(0, 16);
		} else {
			tableTime.value = queryParams.startTime.substring(0, 10) + " 至 " + queryParams.endTime.substring(0, 10);
		}
		getList()
	}
	// 改变时间
	const changeTime = (val, type = 'start') => {
		if (type == 'start') {
			queryParams.startTime = dayjs(val).format('YYYY-MM-DD HH:mm:ss')
		} else {
			queryParams.endTime = dayjs(val).format('YYYY-MM-DD HH:mm:ss')
		}
	}
	console.log(proxy, '--------')
	console.log(proxy.SPLITPANES_CONFIG, '--------')
	const firstSize = ref(proxy.SPLITPANES_CONFIG.DEFAULT_SIZE)
	const activeName = ref('first')
	const loading = ref(false)
	const tableData = ref([])
	const tableHead = ref([])
	const getList = async () => {
		loading.value = true;
		try {
			let res = await proxy.axiosPost2('/ycraindata/gettabledataopen', queryParams)
			if (res.code == 0) {
				tableHead.value = handleTableHead(res.data)
				let data = res.data.slice(1)
				if (queryParams.dataType == 0) {
					data.map(item => { item.tm = item.tm.slice(0, 16) })
				} else {
					data.map(item => { item.tm = item.tm.slice(0, 10) })
				}
				tableData.value = data
			}
		} catch (error) {
			tableHead.value = [];
			tableData.value = [];
		} finally {
			loading.value = false
		}
	}
	// 假设 res.data 是从接口返回的数据
	const handleTableHead = (data) => {
		if (!data || data.length === 0) return [];

		const firstRow = data[0]; // 第一条数据，包含所有字段名
		const head = [];

		// 添加 "时间" 列
		head.push({ prop: 'tm', label: '时间' });

		// 遍历 firstRow 的 key-value，提取站点名称作为列名
		Object.keys(firstRow).forEach(key => {
			if (key !== 'avg' && key !== 'tm') {
				head.push({ prop: key, label: firstRow[key] });
			}
		});

		// 添加 "平均" 列
		head.push({ prop: 'avg', label: '平均' });

		return head;
	};
	const legendData = ref([])
	const xAxisData = ref([])
	const seriesData = ref([])
	const echartsLoading = ref(false)
	const getEchartsData = async () => {
		echartsLoading.value = true
		let url = '/ycraindata/getrainsumdataopen'
		if (activeName.value == 'second') {
			url = '/ycraindata/getRainYearDayChartOption'
		}
		try {
			let res = await proxy.axiosPost2(url, queryParams);
			if (res.code === 0) {
				if (activeName.value == 'first') {
					xAxisData.value = res.data.x
					seriesData.value = res.data.y
				}
				if (activeName.value == 'second') {
					legendData.value = res.data.legend
					// 提取每个series中data的第一个元素并格式化时间
					if (res.data.series && res.data.series.length > 0) {
						// 假设第一个series的data包含完整的时间点
						xAxisData.value = res.data.series[0].data.map(item => {
							// 如果item是对象且包含时间字段
							if (typeof item === 'object' && item !== null) {
								// 假设时间字段可能是tm, time, or the first element
								const timeValue = item.tm || item.time || item[0];
								return dayjs(timeValue).format('YYYY-MM-DD HH:mm');
							} else {
								// 如果item直接就是时间值
								return dayjs(item).format('YYYY-MM-DD HH:mm');
							}
						});
					}
					seriesData.value = res.data.series
				}
			}
		} catch (error) {

		} finally {
			echartsLoading.value = false
		}
	};
	const echartType = ref('bar')
	const changeTabs = (val) => {
		activeName.value = val
		echartType.value = val == 'first' ? 'bar' : 'line'
		getEchartsData()
	}
	const handleQuery = () => {
		getList()
		getEchartsData()
	}
	const dataTypes = ref([
		{ label: '小时', value: '0' },
		{ label: '日', value: '1' }
	])
	const grid = {
		left: "5%",
		right: "5%",
		bottom: "10%",
		top: "10%",
		containLabel: true,
	}
</script>
<style lang="scss" scoped>
	:deep(.el-tabs),
	:deep(.el-tabs .el-tabs__content) {
		height: 100%;
	}
</style>