<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" 
							@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="handleDateChange(dateRange)">查询</el-button>
						<el-button plain @click="resetForm">重置</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">
							<div ref="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 { 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";
import {useUserStore} from "@/stores/modules/user";
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}')]
	} else {
		dateRange.value = [parseTime(new Date(), '{y}-{m}-{d}') + ' 00:00', parseTime(new Date(), '{y}-{m}-{d} {h}:{i}')]
	}
}
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).setMinutes(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 (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 pageable = ref({
	data_type: true,
	time_order: 1,
	as_code: undefined,
	data_items: [],
	pageNum: 1,

});
let historyColumns = [
	{
		data_id: 1003,
		data_r_table: "SHI_SHI_DA_QI_DIAN_CHANG_SHAN_DIAN_SHU_JU",
		data_type: "闪电",
		data_name: "1分钟最强闪电的强度",
		data_item: "YI_FEN_ZHONG_ZUI_QIANG_SHAN_DIAN_DE_QIANG_DU",
		data_unit: "V/m",
		data_h_table: "LI_SHI_DA_QI_DIAN_CHANG_SHAN_DIAN_SHU_JU",
		data_value: "",
		data_order: 0,
		data_condition: 0
	},
	{
		data_id: 1010,
		data_r_table: "SHI_SHI_DA_QI_DIAN_CHANG_SHAN_DIAN_SHU_JU",
		data_type: "闪电",
		data_name: "1分钟最强闪电的距离",
		data_item: "YI_FEN_ZHONG_ZUI_QIANG_SHAN_DIAN_DE_JU_LI",
		data_unit: "km",
		data_h_table: "LI_SHI_DA_QI_DIAN_CHANG_SHAN_DIAN_SHU_JU",
		data_value: "",
		data_order: 0,
		data_condition: 0
	},
	{
		data_id: 1011,
		data_r_table: "SHI_SHI_DA_QI_DIAN_CHANG_SHAN_DIAN_SHU_JU",
		data_type: "闪电",
		data_name: "1分钟最强闪电的方位角",
		data_item: "YI_FEN_ZHONG_ZUI_QIANG_SHAN_DIAN_DE_FANG_WEI_JIAO",
		data_unit: "°",
		data_h_table: "LI_SHI_DA_QI_DIAN_CHANG_SHAN_DIAN_SHU_JU",
		data_value: "",
		data_order: 0,
		data_condition: 0
	},
]

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


const userStore = useUserStore();
const platformList =ref<any>(computed(() => userStore.stations))
const selectPlatform = ref()

const getPlatforms = async () => {
	pageable.value.as_code = platformList.value[0].as_code
	selectPlatform.value = platformList.value[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 series = ref<any>([])

const getHistoryList = async () => {
	
	const { data } = await getDataItemList({ ...pageable.value, pageSize: 9999, 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)
	})

	data.list?.forEach((item, index) => {
		// 初始化一个空数组来存储生成的对象  
		let resultArray = <any>[];

		// 初始化起始角度和结束角度  
		let startAngle = 359.50;
		let endAngle = 0.00; // 注意，这个值实际上是开区间 (0, 360] 的起点前一个值，所以设置为0 - 0.5的极限情况  
		let step = -0.50;

		// 循环生成对象  
		for (let angle = startAngle; angle >= endAngle; angle += step) {
			if (item[1001] != '--') {
				if (angle == 0 && (Number(item[1011]) >= 359.75 || Number(item[1011]) < 0.25)) {
					resultArray.push(Number(item[1010]))
				} else if (Number(item[1011]) >= angle - 0.25 && Number(item[1011]) < angle + 0.25) {
					resultArray.push(Number(item[1010]))
				} else {
					resultArray.push(null)
				}

			}
			// if (item[1011] != '--' && Number(item[1011]) == angle) {
			// 	resultArray.push(Number(item[1010]))
			// 	console.log(resultArray, 'resultArray');

			// } else {
			// 	resultArray.push(0)
			// }
			// resultArray.push(obj);
		}
		series.value.push({
			name: 'No.' + index,
			type: 'radar',
			itemStyle: {
				borderWidth: 10,
				borderColor: 'transparent'
			},
			data: [
				{
					value: resultArray,
					name: item.data_time,
					info: item,
					lineStyle: {
						normal: {
							color: 'transparent'
						}
					},
					itemStyle: { // 单个拐点标志的样式设置。
						normal: {
							color: '#5470c6'
						}
					},
				},

			]
		})
	})
	nextTick(()=>{
		showData()
	})
};


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

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

// resetForm
const resetForm = () => {
	dateRange.value =[parseTime(new Date(), '{y}-{m}-{d}') + ' 00:00', parseTime(new Date(), '{y}-{m}-{d} {h}:{i}')]
	value1.value = true
	pageable.value.as_code = platformList.value[0].as_code
	getHistoryList()
};

const clickNum=ref(0)
const showData = () => {
	// 初始化一个空数组来存储生成的对象  
	let resultArray = <any>[];

	// 初始化起始角度和结束角度  
	let startAngle = 360;
	let endAngle = 0; // 注意，这个值实际上是开区间 (0, 360] 的起点前一个值，所以设置为0 - 0.5的极限情况  
	let step = -0.5;

	// 循环生成对象  
	for (let angle = startAngle; angle > endAngle; angle += step) {
		let obj = {
			name: (angle === 360 || angle % 45 === 0) ? angle.toFixed(1) + '°' : '',
			max: 200,
			// alignTicks: false,
			color: isDark.value ? '#fff' : "#000",
			axisLabel: angle === 360 ? {
				show: angle === 360,
				formatter: '{value}km', color: "#000", showMinLabel: false
			} : {},
			axisLine: {
				show: angle === 360 || angle % 22.5 === 0
			}
		};
		resultArray.push(obj);
	}

	let mychart = echarts.init(data.value);
	let option = {
		tooltip: {
			show: true,
			triggerOn: 'click',
			formatter: function (params) {
				return `一分钟最强闪电的强度：${params.data.info[1003]}V/m <br />时间：${formatDate(params.data.info.data_time_i, 2)}`
			}
		},
		radar: {
			shape: 'circle',
			// radius: 320, // 大小
			name: { // (圆外的标签)雷达图每个指示器名称的配置项。
				formatter: '{value}',
				textStyle: {
					fontSize: 15,
					color: isDark.value ? '#fff' : "#000"
				}
			},
			nameGap: 5,
			// 指示器名称和指示器轴的距离。[ default: 15 ]
			splitNumber: 5,
			splitLine: { // (这里是指所有圆环)坐标轴在 grid 区域中的分隔线。
				lineStyle: {
					color: '#bbbbbb',
					// 分隔线颜色
					width: 1,
					// 分隔线线宽
				}
			},
			splitArea: { // 坐标轴在 grid 区域中的分隔区域，默认不显示。
				show: true,
				areaStyle: { // 分隔区域的样式设置。
					color: [isDark.value ? '#000' : "#fff", isDark.value ? '#000' : "#fff"],
					// 分隔区域颜色。分隔区域会按数组中颜色的顺序依次循环设置颜色。默认是一个深浅的间隔色。
				}
			},
			indicator: resultArray
		},
		series: series.value
	};

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

watch(isDark, () => {
	showData()
});
onMounted(() => {
	getPlatforms()
})

</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>