<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { targetApi, reportApi } from '@/api/service-monitor'
import { useUserStore } from '@/stores/user'
import type { Target, ReportSummary } from '@/types/service-monitor'

const router = useRouter()
const userStore = useUserStore()

const targets = ref<Target[]>([])
const recentReports = ref<ReportSummary[]>([])
const loading = ref(false)
const runChecking = ref<string | null>(null)

const isAdmin = computed(() => userStore.isAdmin)

async function loadData() {
  loading.value = true
  try {
    const [targetsRes, reportsRes] = await Promise.all([
      targetApi.getTargets(),
      reportApi.getReports(),
    ])
    targets.value = targetsRes.targets || []
    recentReports.value = (reportsRes.reports || []).slice(0, 5)
  } catch (e) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

async function startInspection(target: Target, suite: 'quick' | 'full') {
  runChecking.value = target.id
  try {
    const status = await reportApi.getRunStatus(target.id)
    if (status.running) {
      ElMessage.warning(`该目标已有巡检正在运行（${status.done}/${status.total}），请等待完成或取消后再试`)
      return
    }
    router.push({
      name: 'MonitorRun',
      params: { targetId: target.id },
      query: { suite },
    })
  } catch (e) {
    router.push({
      name: 'MonitorRun',
      params: { targetId: target.id },
      query: { suite },
    })
  } finally {
    runChecking.value = null
  }
}

function formatTime(timeStr: string | undefined) {
  if (!timeStr) return '-'
  return timeStr.slice(0, 16).replace('T', ' ')
}

function suiteLabel(suite: string) {
  return suite === 'quick' ? '快速' : '全量'
}

onMounted(loadData)
</script>

<template>
  <div class="page-index">
    <div class="section-head">
      <h1 class="section-title">监测目标</h1>
      <el-button v-if="isAdmin" type="primary" @click="$router.push('/service-monitor/targets')">
        + 目标管理
      </el-button>
    </div>

    <div v-loading="loading" class="content">
      <div v-if="targets.length > 0" class="target-grid">
        <div
          v-for="t in targets"
          :key="t.id"
          class="target-card"
        >
          <div class="target-card-head">
            <span class="target-icon">{{ t.type === 'local' ? '🖥️' : '🌐' }}</span>
            <span class="target-name">{{ t.name }}</span>
            <el-tag v-if="t.built_in" size="small" class="target-badge">内置</el-tag>
          </div>
          <div class="target-meta">
            {{ t.type === 'local' ? '本机容器' : `${t.host}:${t.port}  ${t.username}` }}
          </div>
          <div class="target-actions">
            <el-button
              size="small"
              :loading="runChecking === t.id"
              @click="startInspection(t, 'quick')"
              class="btn-quick"
            >
              ⚡ 快速巡检
            </el-button>
            <el-button
              size="small"
              :loading="runChecking === t.id"
              @click="startInspection(t, 'full')"
              class="btn-full"
            >
              🔍 全量巡检
            </el-button>
          </div>
        </div>
      </div>
      <el-empty v-else-if="!loading" description="暂无监测目标" />

      <!-- Recent reports -->
      <div v-if="recentReports.length > 0" class="recent-section">
        <h2 class="recent-title">最近报告</h2>
        <div class="report-list">
          <div
            v-for="r in recentReports"
            :key="r.id"
            class="report-row"
            @click="$router.push({ name: 'MonitorReportDetail', params: { reportId: r.id } })"
          >
            <span class="report-target">{{ r.target_name }}</span>
            <span class="report-suite">{{ suiteLabel(r.suite) }}</span>
            <span class="report-summary">
              <span class="sm-ok">正常{{ r.summary?.正常 || 0 }}</span>
              <span class="sm-warn">警告{{ r.summary?.警告 || 0 }}</span>
              <span class="sm-crit">严重{{ r.summary?.严重 || 0 }}</span>
            </span>
            <span class="report-time">{{ formatTime(r.started_at) }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.page-index {
  padding: 0 0 40px;
}

.section-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.section-title {
  font-size: 18px;
  font-weight: 700;
  color: $gray-900;
}

.target-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 36px;
}

.target-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid $gray-200;
}

.target-card-head {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 12px;
}

.target-icon {
  font-size: 28px;
}

.target-name {
  font-size: 16px;
  font-weight: 700;
  color: $gray-900;
}

.target-badge {
  margin-left: auto;
}

.target-meta {
  font-size: 13px;
  color: $gray-500;
  margin-bottom: 14px;
}

.target-actions {
  display: flex;
  gap: 8px;

  :deep(.el-button) {
    flex: 1;
  }
}

.btn-quick {
  background: $gray-100;
  color: $gray-700;
  border: none;

  &:hover {
    background: $gray-200;
  }
}

.btn-full {
  background: #eef2ff;
  color: $primary;
  border: none;

  &:hover {
    background: #e0e7ff;
  }
}

.recent-section {
  margin-top: 24px;
}

.recent-title {
  font-size: 16px;
  font-weight: 700;
  color: $gray-900;
  margin-bottom: 12px;
}

.report-list {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid $gray-200;
  overflow: hidden;
}

.report-row {
  display: grid;
  grid-template-columns: 2fr 1fr 2fr 1.5fr;
  gap: 12px;
  align-items: center;
  padding: 14px 18px;
  border-bottom: 1px solid $gray-100;
  cursor: pointer;

  &:last-child {
    border-bottom: none;
  }

  &:hover {
    background: $gray-50;
  }
}

.report-target {
  font-weight: 600;
  color: $gray-900;
}

.report-suite {
  font-size: 13px;
  color: $gray-500;
}

.report-summary {
  font-size: 13px;
}

.sm-ok { color: $green; margin-right: 6px; }
.sm-warn { color: $yellow; margin-right: 6px; }
.sm-crit { color: $red; margin-right: 6px; }

.report-time {
  font-size: 13px;
  color: $gray-500;
}

@media screen and (max-width: 1024px) {
  .target-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media screen and (max-width: 768px) {
  .target-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .target-card {
    padding: 16px;
  }

  .target-actions {
    flex-direction: column;
  }

  .report-row {
    grid-template-columns: 1fr 1fr;
    gap: 8px;
    padding: 12px 14px;
  }

  .report-summary, .report-time {
    display: none;
  }

  .section-head {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

@media screen and (max-width: 480px) {
  .target-card {
    padding: 14px;
  }
}
</style>