<template>
  <div class="status-page mg-content">
    <el-card shadow="never" class="status-card" v-loading="loading">
      <template #header>
        <span>服务状态</span>
        <el-tag v-if="health" type="success" effect="dark" style="margin-left: 8px">在线</el-tag>
        <el-tag v-else-if="!loading" type="danger" effect="dark" style="margin-left: 8px">不可达</el-tag>
      </template>

      <el-descriptions :column="2" border title="MiGu.Server">
        <el-descriptions-item label="状态">
          <el-tag :type="health ? 'success' : 'danger'" size="small">{{ health ? 'ok' : 'unreachable' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="启动时间">{{ serverStartTime || '—' }}</el-descriptions-item>
        <el-descriptions-item label="运行时长" :span="2">{{ serverUptime || '—' }}</el-descriptions-item>
      </el-descriptions>

      <el-descriptions v-if="sl" :column="2" border title="SimpleLite" class="status-block">
        <el-descriptions-item label="托管启用">
          <el-tag :type="sl.enabled ? 'success' : 'info'" size="small">{{ sl.enabled ? '是' : '否' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="进程运行中">
          <el-tag :type="sl.isRunning ? 'success' : 'info'" size="small">{{ sl.isRunning ? '是' : '否（或外部启动）' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="启动模式">{{ sl.lastLaunchMode || '—' }}</el-descriptions-item>
        <el-descriptions-item :label="`投影端口 :${sl.projectionPort}`">
          <el-tag :type="sl.projectionPortReachable ? 'success' : 'danger'" size="small">
            {{ sl.projectionPortReachable ? '可达' : '不可达' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="前往站点 API">
          <el-tag :type="gotoSiteTagType" size="small">{{ gotoSiteLabel }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="可执行文件">
          <el-tag :type="sl.executableExists ? 'success' : 'warning'" size="small">
            {{ sl.executableExists ? '已找到' : '未找到' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="sl.deployHint" label="部署提示" :span="2">
          {{ sl.deployHint }}
        </el-descriptions-item>
      </el-descriptions>

      <el-alert v-if="error" :title="error" type="warning" :closable="false" class="status-block" />

      <div v-if="canControlSimpleLite" class="status-block sl-control">
        <div class="sl-control-title">SimpleLite 操作</div>
        <div class="sl-control-actions">
          <el-button
            type="warning"
            :loading="actionLoading === 'restart'"
            :disabled="!!actionLoading"
            @click="onRestart">
            重启 SimpleLite
          </el-button>
          <el-button
            type="danger"
            plain
            :loading="actionLoading === 'stop'"
            :disabled="!!actionLoading"
            @click="onStop">
            关闭 SimpleLite
          </el-button>
        </div>
        <p class="sl-control-hint">将终止本机全部 SimpleLite 进程；重启后按当前启动模式重新拉起。</p>
      </div>

      <div class="status-actions">
        <el-button :loading="loading" @click="refresh">刷新</el-button>
        <el-button @click="back">返回</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getHealth,
  getSimpleLiteDiagnostics,
  restartSimpleLite,
  resolveRestartLaunchMode,
  stopSimpleLite,
  type HealthInfo,
  type SimpleLiteDiagnostics
} from '@/api/health'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const auth = useAuthStore()

const loading = ref(false)
const actionLoading = ref<'stop' | 'restart' | null>(null)
const health = ref<HealthInfo | null>(null)
const sl = ref<SimpleLiteDiagnostics | null>(null)
const error = ref('')

const canControlSimpleLite = computed(() => auth.token && auth.scope === 'Platform')

let timer: number | undefined

const serverStartTime = computed(() =>
  health.value ? new Date(health.value.startTime).toLocaleString('zh-CN') : ''
)

const serverUptime = computed(() => {
  if (!health.value) return ''
  const s = Math.max(0, Math.floor(health.value.uptimeSec))
  const h = String(Math.floor(s / 3600)).padStart(2, '0')
  const m = String(Math.floor((s % 3600) / 60)).padStart(2, '0')
  const ss = String(s % 60).padStart(2, '0')
  return `${h}:${m}:${ss}`
})

const gotoSiteLabel = computed(() => {
  const v = sl.value?.gotoSiteApiAvailable
  if (v === true) return '可用'
  if (v === false) return '缺失（旧版 DLL）'
  return '未知'
})

const gotoSiteTagType = computed(() => {
  const v = sl.value?.gotoSiteApiAvailable
  if (v === true) return 'success'
  if (v === false) return 'warning'
  return 'info'
})

async function refresh() {
  loading.value = true
  error.value = ''
  try {
    // /status 是 public 页：未登录只拉匿名 /health，不调需登录的 simplelite 诊断
    // （401 会触发全局拦截器强制跳转登录页）。
    const [h, d] = await Promise.allSettled([
      getHealth(),
      auth.token ? getSimpleLiteDiagnostics() : Promise.reject(new Error('skipped'))
    ])
    health.value = h.status === 'fulfilled' ? h.value.data : null
    sl.value = d.status === 'fulfilled' ? d.value.data : null
    if (h.status === 'rejected') error.value = '无法连接 MiGu.Server（/api/health）'
    else if (auth.token && d.status === 'rejected') error.value = 'SimpleLite 诊断获取失败（/api/health/simplelite）'
  } finally {
    loading.value = false
  }
}

async function onStop() {
  try {
    await ElMessageBox.confirm(
      '将终止本机全部 SimpleLite 进程，地图监控与 /api/sl/* 功能将不可用，直到重新登录或手动重启。',
      '关闭 SimpleLite',
      { type: 'warning', confirmButtonText: '关闭', cancelButtonText: '取消' }
    )
  } catch {
    return
  }

  actionLoading.value = 'stop'
  try {
    const { data } = await stopSimpleLite()
    sl.value = data.diagnostics
    ElMessage.success(data.killed > 0 ? `已关闭 ${data.killed} 个 SimpleLite 进程` : '当前没有运行中的 SimpleLite 进程')
  } catch (e) {
    ElMessage.error(e instanceof Error ? e.message : '关闭 SimpleLite 失败')
  } finally {
    actionLoading.value = null
  }
}

async function onRestart() {
  const launchMode = resolveRestartLaunchMode(sl.value?.lastLaunchMode, auth.runMode)
  const modeLabel = launchMode === 'WebOnly' ? '仅 Web' : '本地 + Web'

  try {
    await ElMessageBox.confirm(
      `将关闭本机全部 SimpleLite 并按「${modeLabel}」模式重新拉起，期间 /api/sl/* 可能短暂不可用。`,
      '重启 SimpleLite',
      { type: 'warning', confirmButtonText: '重启', cancelButtonText: '取消' }
    )
  } catch {
    return
  }

  actionLoading.value = 'restart'
  try {
    const { data } = await restartSimpleLite(launchMode)
    sl.value = data.diagnostics
    const r = data.restart
    if (r.warning) ElMessage.warning(r.warning)
    else if (r.started) ElMessage.success('SimpleLite 已重新拉起')
    else ElMessage.error(`重启未完成：${r.status}`)
  } catch (e) {
    ElMessage.error(e instanceof Error ? e.message : '重启 SimpleLite 失败')
  } finally {
    actionLoading.value = null
    void refresh()
  }
}

onMounted(() => {
  void refresh()
  // 10s 轮询：服务端对 goto-site 探测有 60s 缓存，此频率不会对 SimpleLite 产生压力。
  timer = window.setInterval(() => void refresh(), 10_000)
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
})

function back() { router.back() }
</script>

<style scoped>
.status-page { min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 24px; }
.status-card { width: 720px; }
.status-block { margin-top: 16px; }
.sl-control-title { font-weight: 600; margin-bottom: 8px; }
.sl-control-actions { display: flex; flex-wrap: wrap; gap: 8px; }
.sl-control-hint { margin: 8px 0 0; font-size: 12px; color: var(--el-text-color-secondary); }
.status-actions { display: flex; gap: 8px; margin-top: 16px; justify-content: flex-end; }
</style>
