<template>
	<div class="table-box">
		<div class="card table-search" style="overflow: hidden;display: flex;justify-content: space-between;">
			<el-form ref="formRef" :model="searchParam" :inline="true" label-width="auto">
				<el-form-item label="自动站：" prop="as_code">
					<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 class="header-button-ri">
				<slot name="toolButton">
					<img class="setting" style="margin-top: 5px;" src="@/assets/images/setting2.png"
						@click="handleSetting" />
				</slot>
			</div>
		</div>
		<div class="main_list">
			<el-row :gutter="15">
				<template v-if="array.length>0">
					<el-col :xs="24" :sm="12" :md="8" :lg="8">
					<div class="chart_item zhuti">
						<div style="font-weight: bold;" class="item_title">
							<span>2分钟平均风向 ( ° )/2分钟平均风速 ( m/s )</span>
						</div>
						<div class="mt5">
							<div ref="wind" class="ve-ring" style="height: 330px"></div>
						</div>
					</div>
				</el-col>
				<el-col :xs="24" :sm="12" :md="8" :lg="8" v-for="(item, index) in array" :key="item.data_id">
					<div class="chart_item zhuti">
						<div style="font-weight: bold;" class="item_title">
							<span>{{ item.data_name }} ( {{ item.data_unit ? item.data_unit : '' }} )</span>
						</div>
						<div class="mt5">
							<div :id="'Access' + index" class="ve-ring" style="height: 330px"></div>
						</div>
					</div>
				</el-col>

				</template>
				<el-col :span="24" v-else>
					<div class="chart_item zhuti">
						<el-empty description="暂无数据" />
					</div>
				</el-col>

			</el-row>
		</div>
		<!-- 添加或修改岗位对话框 -->
		<el-dialog :title="dialog.title" v-model="dialog.visible" width="1200px" append-to-body>
			<div style="height: 500px;display: flex">
				<el-tabs tab-position="left" class="demo-tabs" style="height: 100%">
					<el-tab-pane label="风">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '风'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
					<el-tab-pane label="温湿度">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '温湿度'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
					<el-tab-pane label="气压">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '气压'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
					<el-tab-pane label="降水">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '降水'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
					<el-tab-pane label="云">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '云'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
					<el-tab-pane label="能见度">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '能见度'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
					<el-tab-pane label="天气现象">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '天气现象'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
					<el-tab-pane label="积雪">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '积雪'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
					<el-tab-pane label="地面温度">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '地面温度'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
					<el-tab-pane label="大气电场">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '大气电场'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
					<el-tab-pane label="闪电">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '闪电'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
					<el-tab-pane label="日照">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '日照'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
					<el-tab-pane label="总辐射">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '总辐射'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
					<el-tab-pane label="日照文">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '日照文'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
					<el-tab-pane label="水文">
						<div class="container-tag">
							<template v-for="item in elementList" :key="item.id">
								<div v-if="item.data_type === '水文'"
									:class="item.isSelected ? 'item-tag-active' : 'item-tag'"
									@click="toggleSelection(item)">{{ item.data_name }}</div>
							</template>
						</div>
					</el-tab-pane>
				</el-tabs>
				<div class="selected-list-box">
					<div class="disposition-title" style="margin-top: 0px">已选要素</div>
					<div class="selected-list-c">
						<template v-for="(item, index) in copiedCustomizeColumns" :key="item.id">
							<div :class="selectedItemIndex === index ? 'selected-item-tag-active' : 'selected-item-tag'"
								@click="changeSelected(index)">{{ item.data_name }}</div>
						</template>
					</div>
					<div class="button-container">
						<el-button type="primary" plain class="top-left" @click="changeMoveUp">上移</el-button>
						<el-button type="primary" plain class="top-right" @click="changeMoveDown">下移</el-button>
						<el-button type="primary" plain class="bottom-left" @click="changeRemove">移除</el-button>
						<el-button type="primary" plain class="bottom-right" @click="changeCleared">清空</el-button>
					</div>
				</div>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submitForm">确 定</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="dataSynthesis">
import * as echarts from 'echarts';
import { ElMessage } from "element-plus";
import { useGlobalStore } from "@/stores/modules/global";
import { ref, computed, onMounted, reactive, watch, onDeactivated, onActivated, nextTick } 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";

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 limitTime = 1000 * 60 * 60 * 24 * 6

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 elementList = ref<any>([])
//自定义部分表头
let customizeColumns = ref<any>([
	{
		data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
		data_id: 2,
		data_type: "风",
		data_item: "ER_FEN_ZHONG_PING_JUN_FENG_XIANG",
		data_name: "2分钟风向",
		data_unit: "°",
		data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
		data_value: "",
		data_order: 0,
		data_condition: 0
	},
	{
		data_id: 1,
		data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
		data_type: "风",
		data_name: "2分钟风速",
		data_item: "ER_FEN_ZHONG_PING_JUN_FENG_SU",
		data_unit: "m/s",
		data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
		data_value: "",
		data_order: 0,
		data_condition: 0
	},
	{
		data_id: 4,
		data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
		data_type: "风",
		data_name: "10分钟风向",
		data_item: "SHI_FEN_ZHONG_PING_JUN_FENG_XIANG",
		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: 3,
		data_type: "风",
		data_item: "SHI_FEN_ZHONG_PING_JUN_FENG_SU",
		data_name: "10分钟风速",
		data_unit: "m/s",
		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: 501,
		data_type: "能见度",
		data_item: "YI_FEN_ZHONG_PING_JUN_NENG_JIAN_DU",
		data_name: "1分钟平均能见度",
		data_unit: "m",
		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_id: 201,
		data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
		data_type: "气压",
		data_name: "水汽压",
		data_item: "SHUI_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: 109,
		data_type: "温湿度",
		data_item: "LU_DIAN_WEN_DU",
		data_name: "露点温度",
		data_unit: "℃",
		data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
		data_value: "",
		data_order: 0,
		data_condition: 0
	},
	{
		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_id: 207,
		data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
		data_type: "气压",
		data_name: "海平面气压",
		data_item: "HAI_PING_MIAN_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: 312,
		data_type: "降水",
		data_item: "XIAO_SHI_LEI_JI_JIANG_SHUI_LIANG_CHENG_ZHONG",
		data_name: "小时累计降水量(称重)",
		data_unit: "mm",
		data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
		data_value: "",
		data_order: 0,
		data_condition: 0
	}
]);

const getAllRgDataList = async () => {
	const { data } = await getRgDataList();
	elementList.value = data.list
};
const copiedCustomizeColumns = ref<any>([...customizeColumns.value]);
const sensorList = ref<any>([])
// 被选中当条数据下标
const selectedItemIndex = ref(0)


const changeMoveUp = () => {
	//上移
	if (selectedItemIndex.value > 0) {
		const temp = copiedCustomizeColumns.value[selectedItemIndex.value - 1]
		copiedCustomizeColumns.value[selectedItemIndex.value - 1] = copiedCustomizeColumns.value[selectedItemIndex.value]
		copiedCustomizeColumns.value[selectedItemIndex.value] = temp
		selectedItemIndex.value--
	}
}

const changeMoveDown = () => {
	//下移
	if (selectedItemIndex.value < copiedCustomizeColumns.value.length - 1) {
		const temp = copiedCustomizeColumns.value[selectedItemIndex.value + 1]
		copiedCustomizeColumns.value[selectedItemIndex.value + 1] = copiedCustomizeColumns.value[selectedItemIndex.value]
		copiedCustomizeColumns.value[selectedItemIndex.value] = temp
		selectedItemIndex.value++
	}
}

const changeRemove = () => {
	//删除数据
	if (copiedCustomizeColumns.value.length > 0) {
		const custom = copiedCustomizeColumns.value[selectedItemIndex.value];
		const se_type = custom.se_type
		for (let i = 0; i < sensorList.value.length; i++) {
			if (sensorList.value[i].se_type === se_type) {
				sensorList.value[i].isSelected = false;
			}
		}
		copiedCustomizeColumns.value.splice(selectedItemIndex.value, 1)
		if (selectedItemIndex.value === copiedCustomizeColumns.value.length) {
			selectedItemIndex.value--
		}

	}
}

const changeCleared = () => {
	//清空所有数据
	selectedItemIndex.value = 0
	copiedCustomizeColumns.value = []
	for (let i = 0; i < sensorList.value.length; i++) {
		sensorList.value[i].isSelected = false;
	}
}

const changeSelected = (index) => {
	selectedItemIndex.value = index
}

// 要素的选中和取消
const toggleSelection = (item) => {
	item.isSelected = !item.isSelected
	if (item.isSelected) {
		//添加
		copiedCustomizeColumns.value.push(item)
	} else {
		//删除
		copiedCustomizeColumns.value = copiedCustomizeColumns.value.filter(column => column.data_id !== item.data_id);
	}

}
const handleSetting = () => {
	copiedCustomizeColumns.value = [...customizeColumns.value]
	elementList.value.forEach(element => {
		const column = copiedCustomizeColumns.value.find(col => col.data_id === element.data_id);
		if (column) {
			element.isSelected = true;
		} else {
			element.isSelected = false;
		}
	});

	dialog.title = "列表字段设置"
	dialog.visible = true;
}
const submitForm = () => {
	dialog.visible = false;
	customizeColumns.value = [...copiedCustomizeColumns.value]
	// updateColumns()
	// getList()
	// weatherInfo()
	getHistoryList()
	saveCustomizeColumns()
}

const cancel = () => {
	dialog.visible = false;
}




const formRef = ref()
const wind = ref()
const pressureLine = ref()
const radio = ref()
const radio2 = ref()


const searchParam = reactive({
	base: undefined,
	date: '',
	switch: true

})

const dialog = reactive<any>({
	visible: false,
	title: ''
});



const pageable = ref({
	data_type: false,
	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: 2,
		data_type: "风",
		data_item: "ER_FEN_ZHONG_PING_JUN_FENG_XIANG",
		data_name: "2分钟风向",
		data_unit: "°",
		data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
		data_value: "",
		data_order: 0,
		data_condition: 0
	},
	{
		data_id: 1,
		data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
		data_type: "风",
		data_name: "2分钟风速",
		data_item: "ER_FEN_ZHONG_PING_JUN_FENG_SU",
		data_unit: "m/s",
		data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
		data_value: "",
		data_order: 0,
		data_condition: 0
	},
	{
		data_id: 1203,
		data_r_table: "SHI_SHI_FU_SHE_SHU_JU",
		data_type: "总辐射",
		data_name: "总辐射曝辐量",
		data_item: "ZONG_FU_SHE_BAO_FU_LIANG",
		data_unit: "MJ/m²",
		data_h_table: "LI_SHI_FU_SHE_SHU_JU",
		data_value: "",
		data_order: 0,
		data_condition: 0,
		isSelected: true
	},
	{
		data_id: 1202,
		data_r_table: "SHI_SHI_FU_SHE_SHU_JU",
		data_type: "总辐射",
		data_name: "总辐射辐照度",
		data_item: "ZONG_FU_SHE_FU_ZHAO_DU",
		data_unit: "W/m²",
		data_h_table: "LI_SHI_FU_SHE_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 () => {
	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()

};

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 array = ref<any>([])
const Access = () => {

	array.value?.forEach((item, i) => {
		// 获取最大值方法
		function calMax(arr) {
			let max = Math.max.apply(null, arr); // 获取最大值方法
			let maxint = Math.ceil(max / 5); // 向上以5的倍数取整
			let maxval = maxint * 5; // 最终设置的最大值
			return maxval; // 输出最大值
		}
		// 获取最小值方法
		function calMin(arr) {
			let min = Math.min.apply(null, arr); // 获取最小值方法
			return min
		}
		// 调用方法，获取数据的最大值&最小值
		let maxData1 = calMax(item.value);
		let minData1 = calMin(item.value);

		let chartDom = document.getElementById("Access" + i);

		if (chartDom) {
			let myChart = echarts.init(chartDom);
			let option;
			option = {

				grid: {
					left: '10',
					right: '10',
					bottom: '3%',
					top: 20,
					containLabel: true
				},

				// X轴
				xAxis: {
					type: 'category',
					splitLine: {
						show: false
					},
					// boundaryGap: false,
					axisTick: {
						alignWithLabel: true, // true：标签位于刻度线正下方；false：标签位于2个刻度线中间
					},
					data: timeArr.value,
					axisLabel: {
						formatter: function (value) {
							return value.replace(/ /g, '\n');
						},
					},
				},
				yAxis: {
					min: minData1,
					max: maxData1,
					type: 'value'
				},
				// 鼠标悬浮提示
				tooltip: {
					trigger: "axis",
				},
				// 数据
				series: [
					{
						data: item.value,
						name: item.data_name,
						type: "line",
						smooth: true,
						lineStyle: {
							color: '#157aea',
							width: 1,
						},
						itemStyle: {
							normal: {
								color: '#157aea'

							},

						}
					},

				]
			};
			myChart.setOption(option)
			window.addEventListener("resize", function () {
				myChart.resize();
			});
		}

		// option && myChart.setOption(option);


	})
};
const timeArr = ref()
const windLineArr = ref() // 2分钟风速风向
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 arr = [...customizeColumns.value, ...historyColumns].reduce((acc, item) => {
		if (!acc.some(existingItem => existingItem.data_id === item.data_id)) {
			acc.push(item);
		}
		return acc;
	}, []);
	const { data } = await getDataItemList({ ...pageable.value, pageSize: 999, as_code_list: [pageable.value.as_code], data_items: arr, 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)
	})


	// 初始化一个空对象来存储归类后的数据  
	const resultMap = {};

	// 遍历原数组  
	data.list?.forEach(obj => {
		obj.data_list.forEach(item => {
			// 将data_value转换为数字  
			const value = parseFloat(item.data_value);

			// 初始化或更新resultMap中的对应项  
			if (!resultMap[item.data_id]) {
				resultMap[item.data_id] = {
					data_id: item.data_id,
					data_name: item.data_name,
					data_unit: item.data_unit,
					value: [value]
				};
			} else {
				resultMap[item.data_id].value.push(value);
			}
		});
	});
	array.value = Object.values(resultMap);
	nextTick(() => {
		if (array.value.length>0) Access();
	});
	// console.log(array.value, 'array');



	windLineArr.value = data.list?.map(item => {
		return {
			value: item[1],
			symbolRotate: adjustValue(item[2]),
			symbolRotateStr: item[2] === 'C' ? 0 : item[2]
		}
	})
	nextTick(()=>{
		if (array.value.length>0) showWind()
	})
};
function adjustValue(value) {
	if (value === 'C') {
		return 0
	} else if (value <= 180) {
		return '-' + value;
	} else {
		return 360 - value;
	}
}
const globalStore = useGlobalStore();
const isDark = computed(() => globalStore.isDark);

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

const showWind = () => {
	// 数据格式
	let winArr = [{
		value: 4.1, //风速--数值大小--变量名不可变
		symbolRotate: -45, //风向---旋转角度--变量名不可变
		symbolRotateStr: '西南风' //风向中文--变量名可变（tooltip 提示随之修改）
	}, {
		value: 4.5,
		symbolRotate: 45,
		symbolRotateStr: '东南风'
	}, {
		value: 4.5,
		symbolRotate: 90,
		symbolRotateStr: '东风'
	}, {
		value: 5.0,
		symbolRotate: -180,
		symbolRotateStr: '南风'
	}, {
		value: 4.3,
		symbolRotate: -45,
		symbolRotateStr: '西南风'
	}, {
		value: 4.5,
		symbolRotate: -90,
		symbolRotateStr: '西风'
	}, {
		value: 4.5,
		symbolRotate: -45,
		symbolRotateStr: '西南风'
	}, {
		value: 4.5,
		symbolRotate: -90,
		symbolRotateStr: '西风'
	}, {
		value: 4.1, //风速--数值大小--变量名不可变
		symbolRotate: -45, //风向---旋转角度--变量名不可变
		symbolRotateStr: '西南风' //风向中文--变量名可变（tooltip 提示随之修改）

	}, {
		value: 4.5,
		symbolRotate: 45,
		symbolRotateStr: '东南风'
	}, {
		value: 4.5,
		symbolRotate: 90,
		symbolRotateStr: '东风'
	}, {
		value: 5.0,
		symbolRotate: -180,
		symbolRotateStr: '南风'
	}, {
		value: 4.3,
		symbolRotate: -45,
		symbolRotateStr: '西南风'
	}, {
		value: 4.5,
		symbolRotate: -90,
		symbolRotateStr: '西风'
	}, {
		value: 4.5,
		symbolRotate: -45,
		symbolRotateStr: '西南风'
	}, {
		value: 4.5,
		symbolRotate: -90,
		symbolRotateStr: '西风'
	}, {
		value: 4.1, //风速--数值大小--变量名不可变
		symbolRotate: -45, //风向---旋转角度--变量名不可变
		symbolRotateStr: '西南风' //风向中文--变量名可变（tooltip 提示随之修改）

	}, {
		value: 4.5,
		symbolRotate: 45,
		symbolRotateStr: '东南风'
	}, {
		value: 4.5,
		symbolRotate: 90,
		symbolRotateStr: '东风'
	}, {
		value: 5.0,
		symbolRotate: -180,
		symbolRotateStr: '南风'
	}, {
		value: 4.3,
		symbolRotate: -45,
		symbolRotateStr: '西南风'
	}, {
		value: 4.5,
		symbolRotate: -90,
		symbolRotateStr: '西风'
	}, {
		value: 4.5,
		symbolRotate: -45,
		symbolRotateStr: '西南风'
	}, {
		value: 4.5,
		symbolRotate: -90,
		symbolRotateStr: '西风'
	},]
	let mychart = echarts.init(wind.value);
	let option = {
		title: {
			text: '暂无数据',
			show: !timeArr.value ? true : false,
			x: 'center',
			y: 'center',
			textStyle: {
				fontSize: 14,
				fontWeight: 'normal',
			}
		},

		grid: {
			left: '10',
			right: '10',
			bottom: '3%',
			top: 20,
			containLabel: true
		},
		// X轴
		xAxis: {
			type: 'category',
			splitLine: {
				show: false
			},
			boundaryGap: true,
			axisTick: {
				alignWithLabel: true, // true：标签位于刻度线正下方；false：标签位于2个刻度线中间
			},
			data: timeArr.value,
			axisLabel: {
				// interval: 4,
				formatter: function (value) {
					// if (value.index % 4 === 0) {
					// 	return value.replace(/ /g, '\n');
					// } else {
					// 	return '';
					// }
					return value.replace(/ /g, '\n');
				},

			},
		},
		// Y轴
		// yAxis: {
		// 	type: 'value',
		// 	// name: "风速(m/s)",
		// },
		yAxis: {
			min: 0,
			max: 10,
			type: 'value'
		},
		// 鼠标悬浮提示
		tooltip: {
			trigger: "axis",
			formatter(params) {
				let tip =
					"时间:" +
					params[0].axisValue +
					"<br/>风速:" +
					(params[0].value ? params[0].value : "--") +
					"m/s<br/>风向:" +
					(params[0].data ? params[0].data.symbolRotateStr + '°' : "--")
				return tip;
			},
		},
		// 数据
		series: [{
			data: windLineArr.value,
			type: 'line',
			smooth: true, //这句就是让曲线变平滑的
			symbol: 'path://M4.866,0,0,15.193l4.866-4.449L9.738,15.2Z',
			symbolSize: 11,
			//折线样式
			lineStyle: {
				color: '#a5cfff',
				width: 1,
			},
			// label: {
			// 	normal: {
			// 		formatter: '{c}',
			// 		show: false,
			// 		position: 'top',
			// 		distance: 15
			// 	}
			// },
			itemStyle: {
				normal: {

				},
			},
		}]
	};

	mychart.setOption(option)
	window.addEventListener("resize", function () {
		mychart.resize();
	});
}

const data3 = ref([1004, 1004, 1004, 1004, 1004, 1005, 1005, 1005, 1005, 1004.5, 1004.6, 1004.8]);
const showPressureLine = () => {
	// 获取最大值方法
	function calMax(arr) {
		let max = Math.max.apply(null, arr); // 获取最大值方法
		let maxint = Math.ceil(max / 5); // 向上以5的倍数取整
		let maxval = maxint * 5 + 5; // 最终设置的最大值
		return maxval; // 输出最大值
	}
	// 获取最小值方法
	function calMin(arr) {
		let min = Math.min.apply(null, arr); // 获取最小值方法
		let minint = Math.floor(min / 1); // 向下以1的倍数取整
		let minval = minint * 1 - 5; // 最终设置的最小值
		return minval; // 输出最小值
	}
	// 调用方法，获取数据的最大值&最小值
	let maxData1 = calMax(data3.value);
	let minData1 = calMin(data3.value);


	let mychart = echarts.init(pressureLine.value);
	let option = {

		grid: {
			left: '10',
			right: '10',
			bottom: '3%',
			top: 20,
			containLabel: true
		},

		// X轴
		xAxis: {
			type: 'category',
			splitLine: {
				show: false
			},
			// boundaryGap: false,
			axisTick: {
				alignWithLabel: true, // true：标签位于刻度线正下方；false：标签位于2个刻度线中间
			},
			data: ['06/12 08:00', '06/12 09:00', '06/12 10:00', '06/12 11:00', '06/12 12:00', '06/12 13:00', '06/12 14:00', '06/12 15:00', '06/12 16:00', '06/12 17:00', '06/12 18:00', '06/12 19:00'],
			axisLabel: {
				interval: 1,
				formatter: function (value) {
					return value.replace(/ /g, '\n');
				},
			},
		},
		yAxis: {
			min: minData1,
			max: maxData1,
			type: 'value'
		},

		// 鼠标悬浮提示
		tooltip: {
			trigger: "axis",
		},
		// 数据
		series: [
			{
				data: data3.value,

				name: "气压",
				type: "line",
				smooth: true,
				lineStyle: {
					color: '#157aea',
					width: 1,
				},
				itemStyle: {
					normal: {
						color: '#157aea'

					},

				}
			},

		]
	};

	mychart.setOption(option)
	window.addEventListener("resize", function () {
		mychart.resize();
	});
}
const data4 = ref([0.4, 0.5, 0.45, 0.5, 0.4, 0.5, 0.6, 0.55, 0.5, 0.5, 0.6, 0.55]);
const showRadio = () => {
	let mychart = echarts.init(radio.value);
	let option = {
		grid: {
			left: '10',
			right: '10',
			bottom: '3%',
			top: 20,
			containLabel: true
		},

		// X轴
		xAxis: {
			type: 'category',
			splitLine: {
				show: false
			},
			// boundaryGap: false,
			axisTick: {
				alignWithLabel: true, // true：标签位于刻度线正下方；false：标签位于2个刻度线中间
			},
			data: ['06/12 08:00', '06/12 09:00', '06/12 10:00', '06/12 11:00', '06/12 12:00', '06/12 13:00', '06/12 14:00', '06/12 15:00', '06/12 16:00', '06/12 17:00', '06/12 18:00', '06/12 19:00'],
			axisLabel: {
				interval: 1,
				formatter: function (value) {
					return value.replace(/ /g, '\n');
				},
			},
		},
		yAxis: {
			min: 0,
			max: 1,
			interval: 0.2,
			type: 'value'
		},

		// 鼠标悬浮提示
		tooltip: {
			trigger: "axis",
		},
		// 数据
		series: [
			{
				name: "曝辐量",
				type: "line",
				smooth: true,
				data: data4.value,
				lineStyle: {
					color: '#157aea',
					width: 1,
				},
				itemStyle: {
					normal: {
						color: '#157aea'

					},

				}
			},

		]
	};

	mychart.setOption(option)
	window.addEventListener("resize", function () {
		mychart.resize();
	});
}
const data5 = ref([800, 810, 800, 820, 800, 850, 800, 830, 800, 850, 800, 820]);
const showRadio2 = () => {
	let mychart = echarts.init(radio2.value);
	let option = {
		grid: {
			left: '10',
			right: '10',
			bottom: '3%',
			top: 20,
			containLabel: true
		},

		// X轴
		xAxis: {
			type: 'category',
			splitLine: {
				show: false
			},
			// boundaryGap: false,
			axisTick: {
				alignWithLabel: true, // true：标签位于刻度线正下方；false：标签位于2个刻度线中间
			},
			data: ['06/12 08:00', '06/12 09:00', '06/12 10:00', '06/12 11:00', '06/12 12:00', '06/12 13:00', '06/12 14:00', '06/12 15:00', '06/12 16:00', '06/12 17:00', '06/12 18:00', '06/12 19:00'],
			axisLabel: {
				interval: 0,
				formatter: function (value) {
					return value.replace(/ /g, '\n');
				},
			},
		},
		yAxis: {
			min: 0,
			max: 1200,
			interval: 200,
			type: 'value'
		},

		// 鼠标悬浮提示
		tooltip: {
			trigger: "axis",
		},
		// 数据
		series: [
			{
				name: "辐照度",
				type: "line",
				smooth: true,
				data: data5.value,
				lineStyle: {
					color: '#157aea',
					width: 1,
				},
				itemStyle: {
					normal: {
						color: '#157aea'

					},

				}
			},

		]
	};

	mychart.setOption(option)
	window.addEventListener("resize", function () {
		mychart.resize();
	});
}


// 保存customizeColumns数组到localStorage
function saveCustomizeColumns() {
	const jsonString = JSON.stringify(customizeColumns.value);
	localStorage.setItem('customizeColumns', jsonString);
}

// 从localStorage中获取customizeColumns数组
function loadCustomizeColumns() {
	const jsonString = localStorage.getItem('customizeColumns');
	if (jsonString) {
		customizeColumns.value = JSON.parse(jsonString);
	}
}
let intervalId;

onMounted(() => {
	loadCustomizeColumns()

	getAllRgDataList()

	getPlatforms()
	nextTick(() => {
		Access();
	});
	// showWind()
	// showPressureLine()
	// showRadio()
	// showRadio2()

})
onActivated(() => {
	intervalId = setInterval(() => {
		// getList();
		// weatherInfo()
		getHistoryList()
	}, 60 * 1000);
});

</script>
<style scoped lang="scss">
.el-row .el-col {
	margin-bottom: 15px;
}


.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;
		}
	}

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

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

}

.el-button.is-link {
	height: 32px;
}
</style>