<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">
					<el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm" format="YYYY-MM-DD"
						type="daterange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间"
						:disabled-date="disabledDate" @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>
				</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>风向风速玫瑰图</span>
						</div>
						<div class="mt5">
							<el-row :gutter="10">
								<el-col :span="12"><div ref="data" class="data_box"></div></el-col>
								<el-col :span="12"><div ref="wind" class="data_box"></div></el-col>
							</el-row>
						</div>
					</div>
				</el-col>
			</el-row>
		</div>
	</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 } 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, isWithin24Hours, isDateFuture, isDateRangeWithinDays } from "@/utils/dateTime";

const dateRange = ref<[any, any]>([parseTime(new Date(getTimeStamp(5)), '{y}-{m}-{d}') + ' 00:00', parseTime(new Date(), '{y}-{m}-{d} {h}') + ':00']);
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))];
	} else {
		const noTodayStart = new Date(startDate).setHours(0, 0, 0, 0);
		const noTodayEnd = new Date(endDate).setHours(23, 0, 0, 0);
		dateRange.value = [parseTime(new Date(noTodayStart)), parseTime(new Date(noTodayEnd))];
	}
};
const handleDateChange = async (e) => {
	if (isDateRangeWithinDays(e[0], e[1], 30)) {
		await handleDateRangeChange(e)
		getHistoryList()
	} else {
		ElMessage.error("时间间隔不能大于30天");
	}
}
const pickDay = ref()
const handleFocus = () => {
	pickDay.value = null
}
const limitTime = 1000 * 60 * 60 * 24 * 30

const disabledDate = (time: Date) => {
	return time.getTime() > Date.now() - 8.64e6

}
const handleChange = (val: Date[]) => {
	const [pointDay] = val
	pickDay.value = pointDay
}


const pageable = ref({
	data_type: true,
	time_order: 0,
	as_code: undefined,
	data_items: [],
	pageNum: 1,
	pageSize: 20,
	total: 0
});
let historyColumns = [
	{
		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
	},
]

// 查询自动站列表
const queryas = ref<Platform>({
	pageSize: 50,
	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 timeArr = ref()
const windD = ref<any>([])
const windS = ref<any>([])
const windInfo = ref<any>({
	max: 6,
	speedMax:6
})
const getHistoryList = async () => {
	if (!isDateRangeWithinDays(dateRange.value[0], dateRange.value[1], 30)) {
		ElMessage.error("时间间隔不能大于30天");
		return false
	}
	const { data } = await getDataItemList({ ...pageable.value, pageSize: 999, as_code_list: [pageable.value.as_code], data_items: historyColumns, data_type: false, time_space: 60, 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)
	})
	let arr1 = new Array(16).fill(0);
	let arr2 = new Array(16).fill([]);
	let num = 0

	data.list?.forEach((item, index) => {
		if (new Date(item.data_time_i * 1000).getHours() % 3 == 2) {
			num++
			if (item[2] >= 348.75 || item[2] < 11.25) {
				arr1[0]++;
				arr2[0] = [...arr2[0], item[1]];
			} else if (item[2] >= 326.25 && item[2] < 348.75) {
				arr1[1]++;
				arr2[1] = [...arr2[1], item[1]];
			} else if (item[2] >= 303.75 && item[2] < 326.25) {
				arr1[2]++;
				arr2[2] = [...arr2[2], item[1]];
			} else if (item[2] >= 281.25 && item[2] < 303.75) {
				arr1[3]++;
				arr2[3] = [...arr2[3], item[1]];
			} else if (item[2] >= 258.75 && item[2] < 281.25) {
				arr1[4]++;
				arr2[4] = [...arr2[4], item[1]];
			} else if (item[2] >= 236.25 && item[2] < 258.75) {
				arr1[5]++;
				arr2[5] = [...arr2[5], item[1]];
			} else if (item[2] >= 213.75 && item[2] < 236.25) {
				arr1[6]++;
				arr2[6] = [...arr2[6], item[1]];
			} else if (item[2] >= 191.25 && item[2] < 213.75) {
				arr1[7]++;
				arr2[7] = [...arr2[7], item[1]];
			} else if (item[2] >= 168.75 && item[2] < 191.25) {
				arr1[8]++;
				arr2[8] = [...arr2[8], item[1]];
			} else if (item[2] >= 146.25 && item[2] < 168.75) {
				arr1[9]++;
				arr2[9] = [...arr2[9], item[1]];
			} else if (item[2] >= 123.75 && item[2] < 146.25) {
				arr1[10]++;
				arr2[10] = [...arr2[10], item[1]];
			} else if (item[2] >= 101.25 && item[2] < 123.75) {
				arr1[11]++;
				arr2[11] = [...arr2[11], item[1]];
			} else if (item[2] >= 78.75 && item[2] < 101.25) {
				arr1[12]++;
				arr2[12] = [...arr2[12], item[1]];
			} else if (item[2] >= 56.25 && item[2] < 78.75) {
				arr1[13]++;
				arr2[13] = [...arr2[13], item[1]];
			} else if (item[2] >= 33.75 && item[2] < 56.25) {
				arr1[14]++;
				arr2[14] = [...arr2[14], item[1]];
			} else if (item[2] >= 11.25 && item[2] < 33.75) {
				arr1[15]++;
				arr2[15] = [...arr2[15], item[1]];
			}

		}
	});

	const arr3 = arr2.map(subArr => {
		const sum = subArr.reduce((a, b) => Number(a) + Number(b), 0);
		const avg = sum / subArr.length;
		return isNaN(avg) ? 0 : avg.toFixed(2);
	})
	
	windD.value = arr1.map((item) => {
		return  isNaN(item / (num/100)) ? 0 :item / (num/100)
	})
	windInfo.value.max = calMax(windD.value)
	windInfo.value.speedMax = calMax(arr3)
	windS.value = arr3
	showData()
	showWind()
};
// 获取时间戳的小时
function getHourFromTimestamp(timestamp) {
	const date = new Date(timestamp * 1000); // 将秒时间戳转换为毫秒时间戳
	return date.getHours();
}


// 获取传入日期相差时间
function getHoursDifference(date1, date2) {
	const d1 = new Date(date1);
	const d2 = new Date(date2);
	const diffInMs = Math.abs(d2.getTime() - d1.getTime());
	return Math.floor(diffInMs / (1000 * 60 * 60)) / 100;
}
// 获取最大值
function calMax(arr) {
	let max = Math.max.apply(null, arr); // 获取最大值方法
	let maxint = Math.ceil(max / 6) * 6; // 向上以6的倍数取整
	return maxint === 0 ? 6 : maxint; // 输出最大值+6
}


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 = () => {
	let mychart = echarts.init(data.value);
	let option = {

		legend: {
			// data: ['Allocated Budget', 'Actual Spending']
			textStyle: {//图例文字的样式
				color: isDark.value ? '#fff' : "#000",
			}
		},
		radar: {
			shape: 'circle',
			name: { // (圆外的标签)雷达图每个指示器名称的配置项。
				formatter: '{value}',
				textStyle: {
					fontSize: 15,
					color: isDark.value ? '#fff' : "#000",
				}
			},
			nameGap: 5,
			// 指示器名称和指示器轴的距离。[ default: 15 ]
			splitNumber: 6,
			splitLine: { // (这里是指所有圆环)坐标轴在 grid 区域中的分隔线。
				lineStyle: {
					color: '#bbbbbb',
					// 分隔线颜色
					width: 1,
					// 分隔线线宽
				}
			},
			splitArea: { // 坐标轴在 grid 区域中的分隔区域，默认不显示。
				show: true,
				areaStyle: { // 分隔区域的样式设置。
					color: [isDark.value ? '#000' : "#fff", isDark.value ? '#000' : "#fff"],
					// 分隔区域颜色。分隔区域会按数组中颜色的顺序依次循环设置颜色。默认是一个深浅的间隔色。
				}
			},
			indicator: [
				{
					name: 'N', max: windInfo.value.max, axisLabel: {
						show: true, color: isDark.value ? '#fff' : "#000", formatter: function (params) {
							return params.toFixed();
						},
					},
				},
				{ name: 'NNW', max: windInfo.value.max },
				{ name: 'NW°', max: windInfo.value.max },
				{ name: 'WNW', max: windInfo.value.max },
				{ name: 'W°', max: windInfo.value.max },
				{ name: 'WSW', max: windInfo.value.max },
				{ name: 'WS°', max: windInfo.value.max },
				{ name: 'SSW', max: windInfo.value.max },
				{ name: 'S', max: windInfo.value.max },
				{ name: 'SSE', max: windInfo.value.max },
				{ name: 'SE', max: windInfo.value.max },
				{ name: 'ESE', max: windInfo.value.max },
				{ name: 'E', max: windInfo.value.max },
				{ name: 'ENE', max: windInfo.value.max },
				{ name: 'NE', max: windInfo.value.max },
				{ name: 'NNE', max: windInfo.value.max },
			]
		},
		series: [
			{
				name: 'Budget vs spending',
				type: 'radar',
				symbolSize: 0,//拐点大小
				data: [
					{
						value: windD.value,
						name: '风向',
						itemStyle: { // 单个拐点标志的样式设置。
							normal: {

								// color:'#d1d6dd'
							}
						},
					}
				]
			}
		]
	};
	mychart.setOption(option)
	window.addEventListener("resize", function () {
		mychart.resize();
	});
}
// 风速
const wind=ref()
const showWind = () => {
	let mychart = echarts.init(wind.value);
	let option = {

		legend: {
			// data: ['Allocated Budget', 'Actual Spending']
			textStyle: {//图例文字的样式
				color: isDark.value ? '#fff' : "#000",
			}
		},
		radar: {
			shape: 'circle',
			name: { // (圆外的标签)雷达图每个指示器名称的配置项。
				formatter: '{value}',
				textStyle: {
					fontSize: 15,
					color: isDark.value ? '#fff' : "#000",
				}
			},
			nameGap: 5,
			// 指示器名称和指示器轴的距离。[ default: 15 ]
			splitNumber: 6,
			splitLine: { // (这里是指所有圆环)坐标轴在 grid 区域中的分隔线。
				lineStyle: {
					color: '#bbbbbb',
					// 分隔线颜色
					width: 1,
					// 分隔线线宽
				}
			},
			splitArea: { // 坐标轴在 grid 区域中的分隔区域，默认不显示。
				show: true,
				areaStyle: { // 分隔区域的样式设置。
					color: [isDark.value ? '#000' : "#fff", isDark.value ? '#000' : "#fff"],
					// 分隔区域颜色。分隔区域会按数组中颜色的顺序依次循环设置颜色。默认是一个深浅的间隔色。
				}
			},
			indicator: [
				{
					name: 'N', max: windInfo.value.speedMax, axisLabel: {
						show: true, color: isDark.value ? '#fff' : "#000", formatter: function (params) {
							return params.toFixed();
						},
					},
				},
				{ name: 'NNW', max: windInfo.value.speedMax },
				{ name: 'NW°', max: windInfo.value.speedMax },
				{ name: 'WNW', max: windInfo.value.speedMax },
				{ name: 'W°', max: windInfo.value.speedMax },
				{ name: 'WSW', max: windInfo.value.speedMax },
				{ name: 'WS°', max: windInfo.value.speedMax },
				{ name: 'SSW', max: windInfo.value.speedMax },
				{ name: 'S', max: windInfo.value.speedMax },
				{ name: 'SSE', max: windInfo.value.speedMax },
				{ name: 'SE', max: windInfo.value.speedMax },
				{ name: 'ESE', max: windInfo.value.speedMax },
				{ name: 'E', max: windInfo.value.speedMax },
				{ name: 'ENE', max: windInfo.value.speedMax },
				{ name: 'NE', max: windInfo.value.speedMax },
				{ name: 'NNE', max: windInfo.value.speedMax },
			]
		},
		series: [
			{
				name: 'windspeed',
				type: 'radar',
				symbolSize: 0,//拐点大小
				data: [
					{
						value: windS.value,
						name: '风速 (m/s)',
						itemStyle: { // 单个拐点标志的样式设置。
							normal: {

								color:'#91cc75'
							}
						},
					}
				]
			}
		]
	};
	mychart.setOption(option)
	window.addEventListener("resize", function () {
		mychart.resize();
	});
}
watch(isDark, () => {
	showData()
	showWind()

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