<template>
	<div class="table-box">
		<div class="card table-search" style="overflow: hidden;">
			<el-form ref="formRef" :model="pageable" :inline="true" label-width="auto">
				<el-form-item label="自动站：" prop="base">
					<el-select v-model="pageable.as_code" filterable placeholder="请搜索自动站" remote reserve-keyword
						clearable style="width: 200px" @change="changeStation">
						<el-option v-for="item in platformList" :key="item.as_code"
							:label="item.as_code + ' ' + item.as_name" :value="item.as_code" />
						<template #prefix>
							<el-icon class="el-input__icon">
								<search />
							</el-icon>
						</template>
					</el-select>
				</el-form-item>
				<el-form-item label="观测时间：" prop="base">
					<div>
						<el-switch v-model="value1" @change="changetype" class="ml-2" inline-prompt active-text="正点"
							inactive-text="分钟" style="margin-right: 10px;" />
						<el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm"
							:format="value1 ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm'"
							:type="value1 ? 'daterange' : 'datetimerange'" range-separator="-" start-placeholder="开始时间"
							end-placeholder="结束时间" :disabled-date="disabledDate" 
							:disabled-minutes="disabledMinutes" @focus="handleFocus" @calendar-change="handleChange"
							@change="handleDateChange"
							:default-time="[new Date(2000, 1, 1, 0, 0), new Date(2000, 1, 1, new Date().getHours(), 0)]"
							style="width: 300px;"></el-date-picker>
					</div>
				</el-form-item>
				<el-form-item>
					<div>
						<el-button type="primary" @click="getHistoryList">查询</el-button>
						<el-button plain @click="resetForm(formRef)">重置</el-button>
					</div>
				</el-form-item>
			</el-form>
		</div>
		<div class="main_list">
			<el-row :gutter="15">
				<el-col :span="24">
					<div class="chart_item zhuti">
						<div style="font-weight: bold;" class="item_title">
							<span>气温 ( ℃ ) / 相对湿度 ( % ) / 本站气压 ( hPa )</span>
						</div>
						<div class="mt5">
							<div ref="data" id="data" class="data_box"></div>
						</div>
					</div>
				</el-col>
			</el-row>
		</div>
	</div>
</template>

<script setup lang="ts" name="dataSynthesis">
import * as echarts from 'echarts';
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useGlobalStore } from "@/stores/modules/global";
import { ref, computed, onMounted, reactive, watch, onDeactivated, onActivated } from "vue";
import { getDataItemList, getPlatformList, getRgDataList, getTacRecordList } from "@/api/modules/allData";
import { Platform } from "@/api/interface";
import { parseTime } from '@/utils/index';
import { isToday, isWithinThirtyMinutes, getTimeStamp, getStamp, isDateFuture, isDateRangeWithinDays } from "@/utils/dateTime";
import { ElLoading } from "element-plus";

/* 全局请求 loading */
const loading = ref()

/**
 * @description 开启 Loading
 * */
const startFullLoading = () => {
	loading.value = ElLoading.service({
		fullscreen: true,
		lock: true,
		text: "Loading",
		background: "rgba(0, 0, 0, 0.7)"
	});
};

/**
 * @description 结束 Loading
 * */
const endFullLoading = () => {
	loading.value.close();
};
const value1 = ref(true)
const dateRange = ref<[any, any]>([parseTime(new Date(), '{y}-{m}-{d}') + ' 00:00', parseTime(new Date(), '{y}-{m}-{d} {h}:{i}')]);
const changetype = (e) => {
	if (!e) {
		dateRange.value = [parseTime(getTimeStamp(1), '{y}-{m}-{d} {h}:{i}'), parseTime(new Date(), '{y}-{m}-{d} {h}:{i}')]
	}
	getHistoryList()
}
const handleDateRangeChange = (newVal) => {
	const [startDate, endDate] = newVal;
	if (endDate && isToday(endDate)) {
		// 获取当前时间的整点  
		const currentHour = new Date().getHours();
		const roundedEndDate = new Date(endDate);
		roundedEndDate.setMinutes(0, 0, 0); // 设置分钟、秒、毫秒为0  
		const startZeroed = new Date(startDate);
		startZeroed.setHours(0, 0, 0, 0);
		dateRange.value = [parseTime(new Date(startZeroed)), parseTime(new Date(roundedEndDate))];
		console.log(dateRange.value, '今天');
	} else {
		const noTodayStart = new Date(startDate).setMinutes(0, 0, 0);
		const noTodayEnd = new Date(endDate).setHours(23, 0, 0, 0);
		dateRange.value = [parseTime(new Date(noTodayStart)), parseTime(new Date(noTodayEnd))];
		console.log(dateRange.value, '不是今天');
	}
};
const handleDateChange = async (e) => {
	if (isDateFuture(e[0]) ||isDateFuture(e[1])) {
		ElMessage.error("不得选择未来的时间");
	} else {
		if (!value1.value) {
			if (isWithinThirtyMinutes(e[0], e[1])) {
			// 获取参数
			getHistoryList()

		} else {
			ElMessage.error("分钟模式下时间间隔不能大于3小时");
		}
		} else {
			if (isDateRangeWithinDays(e[0], e[1], 7)) {
				await handleDateRangeChange(e)
				getHistoryList()
			} else {
				ElMessage.error("正点模式下时间间隔不能大于7天");
			}
		}
	}
}
const pickDay = ref()
const handleFocus = () => {
	pickDay.value = null
}


const disabledDate = (time: Date) => {
	return time.getTime() > Date.now() - 8.64e6
}
const handleChange = (val: Date[]) => {
	const [pointDay] = val
	pickDay.value = pointDay
}


const disabledHours = () => {
	const a: number[] = [];
	for (let i = 0; i < 24; i++) {
		if (new Date().getHours() >= i) continue;
		a.push(i);
	}
	return a;
};

const disabledMinutes = () => {
	const a: number[] = [];
	// for (let i = 0; i < 60; i++) {
	// 	if (new Date().getMinutes() >= i) continue;
	// 	a.push(i);
	// }
	return a;
};



const pageable = ref({
	data_type: true,
	time_order: 1,
	as_code: undefined,
	data_items: [],
	pageNum: 1,
	pageSize: 20,
	total: 0
});
let historyColumns = [
	{
		data_id: 202,
		data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
		data_type: "气压",
		data_name: "本站气压",
		data_item: "BEN_ZHAN_QI_YA",
		data_unit: "hPa",
		data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
		data_value: "",
		data_order: 0,
		data_condition: 0
	},
	{
		data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
		data_id: 101,
		data_type: "温湿度",
		data_item: "QI_WEN",
		data_name: "气温",
		data_unit: "℃",
		data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
		data_value: "",
		data_order: 0,
		data_condition: 0
	},
	{
		data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
		data_id: 106,
		data_type: "温湿度",
		data_item: "XIANG_DUI_SHI_DU",
		data_name: "相对湿度",
		data_unit: "％",
		data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
		data_value: "",
		data_order: 0,
		data_condition: 0,
		isSelected: true
	},
]

// 查询自动站列表
const queryas = ref<Platform>({
	pageSize: 5000,
	pageNum: 1,
	currentpage: 1
})


const platformList = ref<any>([])
const selectPlatform = ref()

const getPlatforms = async () => {
	startFullLoading()

	const { data } = await getPlatformList(queryas.value);
	platformList.value = data.list
	pageable.value.as_code = data.list[0].as_code
	selectPlatform.value = data.list[0]
	getHistoryList()
	endFullLoading()

};

const changeStation = () => {
	getHistoryList()
}

//时间戳转换为指定格式的日期字符串
function formatDate(timestamp, type) {
	const date = new Date(timestamp * 1000); // 将时间戳转换为毫秒
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	const hours = String(date.getHours()).padStart(2, '0');
	const minutes = String(date.getMinutes()).padStart(2, '0');
	if (type === 1) {
		return `${month}/${day} ${hours}:${minutes}`;
	} else {
		return `${year}-${month}-${day} ${hours}:${minutes}`;
	}
}


const timeArr = ref()
const tempLineArr = ref()
const humidityLineArr = ref()
const pressureLineArr = ref()
const getHistoryList = async () => {

	if (isDateFuture(dateRange.value[0]) ||isDateFuture(dateRange.value[1])) {
		ElMessage.error("不得选择未来的时间");
		return false;
	}
	const { data } = await getDataItemList({ ...pageable.value, pageSize: 99, as_code_list: [pageable.value.as_code], data_items: historyColumns, data_type: false, time_space: value1.value ? 60 : 1, end_time: getStamp(dateRange.value[1]), begin_time: getStamp(dateRange.value[0]) });
	timeArr.value = data.list?.map(item => {
		return formatDate(item.data_time_i, 1)
	})
	tempLineArr.value = data.list?.map(item => {
		return item[101]
	})
	humidityLineArr.value = data.list?.map(item => {
		return item[106]
	})
	pressureLineArr.value = data.list?.map(item => {
		return item[202]
	})
	console.log(pressureLineArr.value, 555555);
	showData()
};


const formRef = ref()
const data = ref()

const globalStore = useGlobalStore();
const isDark = computed(() => globalStore.isDark);

// resetForm
const resetForm = (formEl) => {
	if (!formEl) return;
	formEl.resetFields();
};

const showData = () => {
	function getMaxAndAdd50(arr) {
		console.log(arr);
		
		if (!arr||arr.length === 0) {
			return
		} else {
			const maxValue = Math.max(...arr);
		// 将最大值加 50  
		const result = maxValue + 50;
		return result;
		}
		
	}
	function getMaxAndMinus50(arr) {
		if (!arr||arr.length === 0) {
			return
		} else {
			const maxValue = Math.min(...arr);
		// 将最大值加 50  
		const result = maxValue - 50;
		return result>=0 ? result : 0;
		}
		
	}

	const colors = ['#5470C6', '#59A073', '#FFB652'];
	var dom = document.getElementById("data");
    // var myChart = echarts.init(dom);
	let mychart = echarts.init(dom);
	let option = {
		color: colors,
		title: {
			text: '暂无数据',
			show: !timeArr.value ? true : false,
			x: 'center',
			y: 'center',
			textStyle: {
				fontSize: 14,
				fontWeight: 'normal',
			}
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross'
			}
		},
		grid: {
			left: '80',
			right: '130',
			bottom: '40',
		},

		legend: {
			data: ['气温', '相对湿度', '本站气压'],
			textStyle: {//图例文字的样式
				color: isDark.value ? '#fff' : "#000",
			}
		},
		xAxis: [
			{
				type: 'category',
				axisTick: {
					alignWithLabel: true
				},
				// prettier-ignore
				data: timeArr.value
			}
		],
		yAxis: [
			{
				type: 'value',
				name: '气温',
				position: 'right',
				alignTicks: true,
				axisLine: {
					show: true,
					lineStyle: {
						color: colors[0]
					}
				},
				axisLabel: {
					formatter: '{value} °C'
				}
			},
			{
				type: 'value',
				name: '相对湿度',
				position: 'right',
				max: 100,
				offset: 80,
				axisLine: {
					show: true,
					lineStyle: {
						color: colors[1]
					}
				},
				axisLabel: {
					formatter: '{value} %'
				}
			},
			{
				type: 'value',
				name: '本站气压',

				min: getMaxAndMinus50(pressureLineArr.value),
				max: getMaxAndAdd50(pressureLineArr.value),
				position: 'left',
				axisLine: {
					show: true,
					lineStyle: {
						color: colors[2
						]
					}
				},
				axisLabel: {
					formatter: '{value} hPa'
				}
			}
		],
		series: [
			{
				name: '气温',
				smooth: true, // 添加此行
				type: 'line',

				data: tempLineArr.value
			},
			{
				name: '相对湿度',
				type: 'line',
				smooth: true, // 添加此行
				yAxisIndex: 1,
				data: humidityLineArr.value
			},
			{
				name: '本站气压',
				type: 'line',
				smooth: true, // 添加此行
				yAxisIndex: 2,
				data: pressureLineArr.value
			}
		]
	};
	 //单击后执行操作
	 mychart.on('click',(param) => {
        console.log(param)
    });
	mychart.setOption(option)
	window.addEventListener("resize", function () {
		mychart.resize();
	});
}

watch(isDark, () => {
	showData()


});

onMounted(() => {
	getPlatforms()
	// showData()
})

</script>
<style scoped lang="scss">
.main_list {
	background: transparent !important;
	box-shadow: none !important;
	padding: 0 !important;
	height: calc(100vh - 150px);
	margin-bottom: 10px;
	overflow-y: scroll;
	overflow-x: hidden;


	.chart_item {
		border-radius: 10px;
		padding: 10px;
		background-color: #fff;
		// height: 100%;
		// margin-bottom: 15px;


		.item_title {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.FTP_box {
			padding: 0 50px;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.FTP_item {
				flex: 1;
				flex-shrink: 0;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				img {
					width: 56px;
					margin-bottom: 20px;
				}
			}

		}
	}

	.info_box {
		.info_title {
			color: #999999;
			font-size: 16px;
		}

		.info_content {
			height: 40px;
			font-weight: bold;
			color: #000;
			font-size: 26px;
		}
	}

}

.data_box {
	height: calc(100vh - 215px);
	// height: 100%;
}
</style>
