<template>
	<div class="server-detail">
		<div v-if="isLoading && !snapshotView" class="loading-wrap">
			<t-loading text="加载系统详情..." />
		</div>
		<template v-else-if="snapshotView">
			<t-cell-group title="系统" theme="card">
				<t-cell title="服务器时间" :note="Time.toDateTime(snapshotView.serverTime)" />
				<t-cell title="采样周期" :note="`${snapshotView.sampleRateMs} ms`" />
				<t-cell title="操作系统" :note="os?.name" />
				<t-cell title="启动时间" :note="Time.toPassedDateTime(os?.bootAt)" />
			</t-cell-group>
			<t-cell-group title="硬件信息" theme="card">
				<t-cell title="主板厂商" :note="hardware?.baseboard?.manufacturer" />
				<t-cell title="主板型号" :note="hardware?.baseboard?.model" />
				<t-cell title="主板版本" :note="hardware?.baseboard?.version" />
				<t-cell title="主板序列号" :note="hardware?.baseboard?.serialNumber" />
				<t-cell title="固件厂商" :note="hardware?.firmware?.manufacturer" />
				<t-cell title="固件名称" :note="hardware?.firmware?.name" />
				<t-cell-info label="固件描述" :value="hardware?.firmware?.description" />
				<t-cell title="固件版本" :note="hardware?.firmware?.version" />
				<t-cell title="固件发布日期" :note="hardware?.firmware?.releaseDate" />
			</t-cell-group>
		</template>
		<t-empty v-else description="暂无系统详情数据" />
	</div>
</template>

<script setup lang="ts">
import { Toast } from "tdesign-mobile-vue";
import SystemAPI from "@/api/SystemAPI";
import type { SystemStatusSnapshotView } from "@/types/System";
import { Time } from "timi-web";

defineOptions({
	name: "ServerDetail"
});

const isLoading = ref(false);
const snapshotView = ref<SystemStatusSnapshotView | null>(null);
const refreshIntervalMs = 3000;
let refreshTimer: ReturnType<typeof setInterval> | null = null;

const os = computed(() => snapshotView.value?.snapshot?.os);
const hardware = computed(() => snapshotView.value?.snapshot?.hardware);

onMounted(() => {
	void refreshDetail();
	refreshTimer = setInterval(() => {
		void refreshDetail();
	}, refreshIntervalMs);
});

onUnmounted(() => {
	if (!refreshTimer) {
		return;
	}
	clearInterval(refreshTimer);
	refreshTimer = null;
});

async function refreshDetail(): Promise<void> {
	if (isLoading.value) {
		return;
	}
	isLoading.value = true;
	try {
		snapshotView.value = await SystemAPI.getStatus("os,hardware");
	} catch (error) {
		Toast({
			theme: "error",
			message: error instanceof Error ? error.message : "请求失败，请稍后重试"
		});
	} finally {
		isLoading.value = false;
	}
}
</script>

<style scoped lang="less">
.server-detail {
	padding: var(--app-nav-offset) 0 1rem 0;

	.loading-wrap {
		display: flex;
		min-height: 4rem;
		align-items: center;
		justify-content: center;
	}
}
</style>
