<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-cascader v-model="defaultOption" placeholder="请选择站点" :options="selectOptions" style="width: 250px;" filterable clearable></el-cascader>
				</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">
					</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" placeholder="选择结束时间" :disabled-date="disabledEndDate">
					</el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-checkbox v-model="queryParams.xindao" @change='handleQuery' :true-label="1" :false-label="0">遥测数据</el-checkbox>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
					<el-switch class="ml20" v-model="staticType" size="large" inline-prompt style="--el-switch-on-color: #13ce66; --el-switch-off-color: #1890FF" active-text="逐日显示" inactive-text="逐时显示" />

				</el-form-item>
				<br />
				<el-form-item label="对比站点">
					<el-cascader v-model="defaultOption2" placeholder="请选择对比站" :options="selectOptions2" :props="{multiple: true, }" :show-all-levels="false" collapse-tags filterable clearable></el-cascader>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="compareQuery" icon="Search">对比查询</el-button>
					<el-button type="success" plain icon="Edit" @click="updateData">数据修改</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">
				<el-collapse v-model="activeName" accordion @change="handleChangeCollapse">
					<el-collapse-item title="预处理数据" name="1">
						<el-row :gutter="10" class="mb8">
							<el-col :span="1.5">
								<el-button type="warning" plain icon="Download" @click="yclExport">导出 </el-button>
							</el-col>
							<el-col :span="1.5">
								<el-button type="success" plain icon="RefreshRight" @click="yclUpdate"> 整编 </el-button>
							</el-col>
						</el-row>
						<!-- <el-table v-loading="loading" :data="tableData1" height="450" border style="width:100%">
                            <el-table-column prop="tm" label="时间" width="170">
                            </el-table-column>
                            <el-table-column prop="value" label="数值">
                                <template #default="scope">
                                    <el-input type="text" v-model="scope.row.value" />
                                </template>
                            </el-table-column>
                        </el-table> -->
						<vxe-grid v-bind="gridOptions1"></vxe-grid>
					</el-collapse-item>
					<el-collapse-item :title="stationType==='A'?'小时数据':'摘录数据'" name="2">
						<el-row :gutter="10" class="mb8">
							<el-col :span="1.5">
								<el-button type="warning" plain icon="Download" @click="hourExport">导出 </el-button>
							</el-col>
						</el-row>
						<!-- <el-table v-loading="loading" :data="tableData1" height="450" border style="width:100%">
                            <el-table-column prop="tm" label="时间" width="170">
                            </el-table-column>
                            <el-table-column prop="value" label="数值">
                                <template #default="scope">
                                    <el-input type="text" v-model="scope.row.value" />
                                </template>
                            </el-table-column>
                        </el-table> -->
						<vxe-grid v-bind="gridOptions2"></vxe-grid>
					</el-collapse-item>
					<el-collapse-item title="遥测数据" name="3">
						<!-- <el-table :data="tableData3" height="450" border>
                            <el-table-column width="180" :prop="item.prop" :label="item.label" v-for="(item, index) in tableHead" :key="index">
                            </el-table-column>
                        </el-table> -->
						<vxe-grid v-bind="gridOptions3"></vxe-grid>
					</el-collapse-item>
				</el-collapse>
			</pane>
			<pane :size="100 - firstSize">
				<div v-table-height='{bottom:0}' style="width:100%;">
					<TimeBarChart v-loading="echartsLoading" :legendData='legendData' :xAxisData="xAxisData" :seriesData="seriesData" :textTitle="textTitle" :unit="unit" :echartType="echartType" />
				</div>
			</pane>
		</splitpanes>
		<el-dialog class="custom-dialog" title="数据修改" v-model="open" width="500px" append-to-body>
			<el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
				<el-form-item label="修改方式" prop="updateType">
					<el-select v-model="form.updateType" placeholder="请选择修改方式">
						<el-option v-for="dict in update_type_options" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="开始时间" v-if="form.updateType!='2'&&form.updateType!=null">
					<el-date-picker v-model="form.startTime" type="datetime" placeholder="选择开始时间" value-format="yyyy-MM-dd HH:mm:ss" class="w320">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="结束时间" v-if="form.updateType!='2'&&form.updateType!=null">
					<el-date-picker v-model="form.endTime" type="datetime" placeholder="选择结束时间" value-format="yyyy-MM-dd HH:mm:ss" class="w320">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="替换值" v-if="form.updateType=='1'">
					<el-input v-model="form.value1" placeholder="请输入替换值" style="width:220px" />
				</el-form-item>
				<div style="width:80%;margin: 0 auto;" v-if="form.updateType=='2'">
					<el-upload class="upload-demo" drag action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" multiple>
						<el-icon class="el-icon--upload"><upload-filled /></el-icon>
						<div class="el-upload__text">
							将文件拖到此处，或<em>点击上传</em>
						</div>
					</el-upload>
				</div>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm(formRef)" v-loading='btnLoading'>确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script setup>
	import dayjs from 'dayjs';
	import {
		Splitpanes,
		Pane
	} from 'splitpanes'
	import 'splitpanes/dist/splitpanes.css'
	import TimeBarChart from '@/components/ChartsTimeBar/index.vue'

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

	const props = defineProps({
		stationType: {
			type: String,
			default: 'A'
		},
		requestPrefix: {
			type: String,
			default: '/ycraindata'
		},
		fixed: {
			type: Number,
			default: 1
		}
	})
	const {
		proxy
	} = getCurrentInstance()
	const { update_type_options } = proxy.useDict("update_type_options")

	const textTitle = computed(() => {
		switch (props.stationType) {
			case 'A':
				return '雨量过程线';
			case 'B':
				return '水位过程线';
			case 'C':
				return '水位过程线';
			case 'D':
				return '潮位过程线';
			case 'E':
				return '流量过程线';
		}
	});
	const unit = computed(() => {
		switch (props.stationType) {
			case 'A':
				return 'mm';
			case 'B':
				return 'm';
			case 'C':
				return 'm';
			case 'D':
				return 'm';
			case 'E':
				return 'm³/s';
		}
	});
	const echartType = computed(() => {
		switch (props.stationType) {
			case 'A':
				return 'bar';
			case 'B':
				return 'line';
			case 'C':
				return 'line';
			case 'D':
				return 'line';
			case 'E':
				return 'line';
		}
	});
	const staticType = ref(0)
	const queryParams = reactive({
		startTime: dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
		endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
		xindao: 1,
		stnmId: null,
		dataType: staticType.value,
		chartType: echartType.value
	});

	// 禁用开始时间选择器中大于当前时间和结束时间的日期
	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 selectOptions = ref([]);
	const selectOptions2 = ref([]);
	const defaultOption = ref([])
	const defaultOption2 = ref([])
	const getSingleStation = async () => {
		let res = await proxy.axiosGet('/basic/stype/getTreeStation2New/' + props.stationType);
		if (res.code === 0) {
			selectOptions.value = res.data;
			defaultOption.value = res.defaultOption
			queryParams.stnmId = defaultOption.value.length > 0 ? parseInt(defaultOption.value[2]) : null
			queryParams.stnmIds = queryParams.stnmId
			try {
				await Promise.all([
					drawTable1(),
					drawTable2(),
					drawTable3(),
					getEchartsData()

				]);
			} catch (error) {
				console.error('请求执行出错:', error);
			}
		}
	}


	const firstSize = ref(proxy.SPLITPANES_CONFIG.DEFAULT_SIZE)

	const activeName = ref('1')

	const tableData1 = ref([])
	const tableData2 = ref([])
	const tableData3 = ref([])
	// 折叠面板事件
	const handleChangeCollapse = (val) => { }
	// 基础共享配置
	const baseGridOptions = {
		border: true,
		loading: false,
		showOverflow: false,
		height: 450,
		columnConfig: {
			resizable: true
		},
		virtualYConfig: {
			enabled: true,
			gt: 0
		}
	}
	// 预处理数据表格配置
	const gridOptions1 = reactive({
		...baseGridOptions,
		columns: [{
			title: '时间',
			field: 'tm',
			width: 160,
			align: "center"
		},
		{
			title: '数值',
			field: 'value',
			align: "center"
		}
		],
		data: []
	})


	// 获取预处理数据
	const drawTable1 = async () => {
		gridOptions1.loading = true
		try {
			let url = props.requestPrefix + '/originaldata'
			let res = await proxy.axiosPost2(url, queryParams);
			if (res.code === 0) {
				let data = res.data;
				for (var i = 0; i < data.length; i++) {
					data[i].value = data[i].value.toFixed(proxy.fixed)
				}
				gridOptions1.data = data
				// selectOptions.value = res.data;
			}

		} catch (error) {
		} finally {
			gridOptions1.loading = false
		}
	}
	// 小时/摘录数据表格配置
	const gridOptions2 = reactive({
		...baseGridOptions,
		columns: [{
			title: '时间',
			field: 'tm',
			width: 160,
			align: "center"
		},
		{
			title: '数值',
			field: 'value',
			align: "center"
		}
		],
		data: []
	})
	// 获取小时数居
	const drawTable2 = async () => {
		gridOptions2.loading = true
		try {
			let url = props.requestPrefix + '/countdata'
			let res = await proxy.axiosPost2(url, queryParams);
			if (res.code === 0) {
				let data = res.data;
				gridOptions2.data = data
			}
			gridOptions2.loading = false
		} catch (error) {
			gridOptions2.loading = false
		}
	}
	// 遥测数据表格配置
	const gridOptions3 = reactive({
		...baseGridOptions,
		columns: [],
		data: []
	})
	// 获取遥测数居
	const drawTable3 = async () => {
		gridOptions3.loading = true
		try {
			let url = props.requestPrefix + '/xindaodaydata'
			let res = await proxy.axiosPost2(url, queryParams);
			if (res.code === 0) {
				let data = res.data;
				let header = data[0];
				let tableColumn = []
				tableColumn.push({
					field: 'tm',
					title: '时间',
					width: 160,
					align: "center"
				});
				for (let k in header) {
					if (k != 'tm' && k != 'avg') {
						tableColumn.push({
							field: k,
							title: k,
							width: 100,
							align: "center"
						});
					}
				}
				gridOptions3.columns = tableColumn;
				gridOptions3.data = data
			}
			gridOptions3.loading = false
		} catch (error) {
			gridOptions3.loading = false
		}
	}
	// 获取echarts数据
	const legendData = ref([])
	const xAxisData = ref([])
	const seriesData = ref([])
	const echartsLoading = ref(false)
	const getEchartsData = async () => {
		echartsLoading.value = true
		let baseUrl = '/chartdata'
		if (staticType.value == 1) {
			baseUrl = "/chartdatabyday";
		}
		try {
			let url = props.requestPrefix + baseUrl
			let res = await proxy.axiosPost2(url, queryParams);
			if (res.code === 0) {
				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) {
			console.log(error)
		} finally {
			echartsLoading.value = false
		}
	};


	// 预处理数据导出
	const yclExport = () => {

	}
	// 预处理数据整编
	const yclUpdate = () => {

	}


	// 小时数居导出
	const hourExport = () => { }

	// 查询
	const handleQuery = async () => {
		try {
			await Promise.all([
				drawTable1(),
				drawTable2(),
				drawTable3(),
				getEchartsData()

			]);
		} catch (error) {
			console.error('请求执行出错:', error);
		}
	}

	// 对比查询
	const compareQuery = () => {

	}
	let open = ref(false)
	const form = reactive({
		updateType: null
	});
	// 数据修改
	const updateData = () => {
		open.value = true
	}
	/****************************************************    数据修改弹窗    ******************************************************/
	let formRef = ref(null)
	// 取消按钮
	const cancel = () => {
		open.value = false;
		reset();
	}
	const reset = () => {
		Object.assign(form, {});
		proxy.resetForm("formRef");
	}
	/** 提交按钮 */
	const submitForm = async (formEl) => {
		if (!formEl) return
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				try {
					// let res = await proxy.axiosPost('/riverBasin', form);
					// if (res.code === 0) {
					// 	proxy.$modal.msgSuccess("修改成功");
					// 	open.value = false;
					// 	getList();
					// }
				} catch (error) { }
			}
		})
	}

	onMounted(() => {
		getSingleStation();
	})
</script>
<style lang="scss" scoped>
	:deep(.el-collapse) {
		border-top: none !important;
	}
</style>