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

const route = useRoute()
const router = useRouter()

const targetId = route.params.targetId as string
const suite = (route.query.suite as string) || 'quick'

const target = ref<Target | null>(null)
const loading = ref(true)

// Run state
const runId = ref<string | null>(null)
const currentModule = ref('')
const progress = ref({ done: 0, total: 0 })
const modules = ref<Map<string, { status: 'pending' | 'running' | 'done'; info: string }>>(new Map())
const finished = ref(false)
const success = ref(false)
const reportId = ref<string | null>(null)
const summary = ref<ModuleSummary | null>(null)
const errorMsg = ref('')

// SSE connection
let sseConnection: { close: () => void } | null = null

// Load target info
async function loadTarget() {
  try {
    const res = await targetApi.getTargets()
    const t = (res.targets || []).find(t => t.id === targetId)
    if (t) {
      target.value = t
    } else {
      ElMessage.error('目标不存在')
      router.push({ name: 'MonitorIndex' })
    }
  } catch {
    ElMessage.error('加载目标信息失败')
  } finally {
    loading.value = false
  }
}

// Check existing run and start
async function checkAndStart() {
  try {
    const status = await reportApi.getRunStatus(targetId)
    if (status.running) {
      // Already running
      runId.value = status.run_id || null
      if (status.done !== undefined && status.total !== undefined) {
        progress.value = { done: status.done, total: status.total }
      }
      if (status.current) {
        currentModule.value = status.current
        modules.value.set(status.current, { status: 'running', info: '' })
      }
      errorMsg.value = `该目标已有巡检正在运行（${progress.value.done}/${progress.value.total}），可点击取消后重试`
      finished.value = true
      success.value = false
      return
    }
  } catch {
    // Ignore, proceed to start
  }
  startInspection()
}

// Start SSE inspection
function startInspection() {
  sseConnection = reportApi.runInspection(targetId, suite as 'quick' | 'full', {
    progress: (evt) => {
      runId.value = evt.run_id
      if (evt.done !== undefined && evt.total !== undefined) {
        progress.value = { done: evt.done, total: evt.total }
      }
      if (evt.current) {
        currentModule.value = evt.current
        // Mark module as running
        if (!modules.value.has(evt.current)) {
          modules.value.set(evt.current, { status: 'pending', info: '' })
        }
        modules.value.get(evt.current)!.status = 'running'
      }
    },
    module_done: (evt) => {
      if (evt.module) {
        const s = evt.summary as Record<string, number> | undefined
        let info = `${evt.items_count || 0}项`
        const parts: string[] = []
        if (s?.['正常']) parts.push(`<span style="color:#16a34a">✓${s['正常']}</span>`)
        if (s?.['警告']) parts.push(`<span style="color:#d97706">⚠${s['警告']}</span>`)
        if (s?.['严重']) parts.push(`<span style="color:#dc2626">✗${s['严重']}</span>`)
        info += ' ' + parts.join(' ')
        modules.value.set(evt.module, { status: 'done', info })
      }
    },
    finished: (evt) => {
      finished.value = true
      success.value = true
      reportId.value = evt.report_id || null
      summary.value = evt.summary || null
      closeSSE()
      // Auto redirect after 1.5s
      if (evt.report_id) {
        setTimeout(() => {
          router.push({ name: 'MonitorReportDetail', params: { reportId: evt.report_id } })
        }, 1500)
      }
    },
    error: (evt) => {
      finished.value = true
      success.value = false
      errorMsg.value = evt.message || '巡检失败'
      closeSSE()
    },
    cancelled: () => {
      finished.value = true
      success.value = false
      errorMsg.value = '巡检已取消'
      closeSSE()
    },
  }, () => {
    // SSE error
    finished.value = true
    success.value = false
    errorMsg.value = '连接中断'
  })
}

// Cancel run
async function cancelRun() {
  if (runId.value) {
    try {
      await reportApi.cancelRun(runId.value)
    } catch {
      // Ignore
    }
  }
  closeSSE()
  finished.value = true
  success.value = false
  errorMsg.value = '巡检已取消'
}

function closeSSE() {
  if (sseConnection) {
    sseConnection.close()
    sseConnection = null
  }
}

// Helpers
function progressPercent() {
  if (progress.value.total === 0) return 0
  return Math.round((progress.value.done / progress.value.total) * 100)
}

function formatProgress() {
  return `${progress.value.done} / ${progress.value.total}`
}

function suiteLabel() {
  return suite === 'quick' ? '⚡ 快速巡检' : '🔍 全量巡检'
}

function targetIcon() {
  return target.value?.type === 'local' ? '🖥️' : '🌐'
}

function moduleList() {
  return Array.from(modules.value.entries())
}

function viewReport() {
  if (reportId.value) {
    router.push({ name: 'MonitorReportDetail', params: { reportId: reportId.value } })
  }
}

onMounted(async () => {
  await loadTarget()
  if (target.value) {
    checkAndStart()
  }
})

onUnmounted(() => {
  closeSSE()
})
</script>

<template>
  <div class="page-run" v-loading="loading">
    <div class="run-card">
      <!-- Header -->
      <div class="run-head">
        <div class="run-title">
          {{ targetIcon() }} {{ target?.name || '加载中...' }}
          <span class="suite-tag">{{ suiteLabel() }}</span>
        </div>
        <el-button
          v-if="!finished"
          class="btn-cancel"
          @click="cancelRun"
        >
          取消
        </el-button>
      </div>

      <!-- Progress bar -->
      <div class="progress-wrap">
        <el-progress
          :percentage="progressPercent()"
          :stroke-width="12"
          :show-text="false"
        />
        <div class="progress-text">
          <span id="progress-current">{{ currentModule || '准备中...' }}</span>
          <span id="progress-count">{{ formatProgress() }}</span>
        </div>
      </div>

      <!-- Module list -->
      <div class="module-list">
        <div
          v-for="[name, mod] in moduleList()"
          :key="name"
          class="module-item"
          :class="'st-' + mod.status"
        >
          <span class="module-status">
            <template v-if="mod.status === 'done'">✓</template>
            <template v-else-if="mod.status === 'running'">
              <span class="spinner"></span>
            </template>
            <template v-else>○</template>
          </span>
          <span class="module-name">{{ name }}</span>
          <span class="module-info" v-html="mod.info"></span>
        </div>
      </div>

      <!-- Done banner -->
      <div v-if="finished" class="done-banner" :class="success ? 'done-ok' : 'done-err'">
        <div class="done-text">
          <template v-if="success">
            ✅ 巡检完成：正常 {{ summary?.['正常'] || 0 }}，警告 {{ summary?.['警告'] || 0 }}，严重 {{ summary?.['严重'] || 0 }}
          </template>
          <template v-else>
            ❌ {{ errorMsg }}
          </template>
        </div>
        <el-button
          v-if="reportId"
          type="primary"
          class="btn-report"
          @click="viewReport"
        >
          查看报告 →
        </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.page-run {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.run-card {
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid $gray-200;
  padding: 26px;
  max-width: 720px;
  width: 100%;
}

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

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

.suite-tag {
  font-size: 13px;
  font-weight: 600;
  padding: 3px 10px;
  border-radius: 6px;
  margin-left: 8px;
  background: #eef2ff;
  color: $primary;
}

.btn-cancel {
  background: #fee2e2;
  color: $red;
  border: none;
}

/* Progress bar */
.progress-wrap {
  margin-bottom: 6px;
}

.progress-text {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: $gray-500;
  margin-top: 8px;
}

/* Module list */
.module-list {
  margin-top: 20px;
}

.module-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid $gray-100;

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

.module-status {
  font-size: 18px;
  width: 24px;
  text-align: center;
}

.module-name {
  flex: 1;
  font-size: 15px;
  color: $gray-700;
}

.module-info {
  font-size: 13px;
  color: $gray-500;
}

.st-pending .module-name {
  color: $gray-400;
}

.st-running .module-name {
  color: $primary;
  font-weight: 600;
}

.st-done .module-name {
  color: $gray-900;
}

.spinner {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid $gray-200;
  border-top-color: $primary;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.done-banner {
  text-align: center;
  padding: 20px;
  margin-top: 10px;
  border-radius: 10px;
}

.done-ok {
  background: #dcfce7;
  color: #15803d;
}

.done-err {
  background: #fee2e2;
  color: $red;
}

.done-text {
  font-size: 15px;
  font-weight: 600;
}

.btn-report {
  margin-top: 12px;
}

@media screen and (max-width: 768px) {
  .page-run {
    padding: 12px;
  }

  .run-card {
    padding: 16px;
    border-radius: 12px;
  }

  .run-head {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .run-title {
    font-size: 15px;
  }

  .suite-tag {
    font-size: 12px;
    padding: 2px 8px;
  }

  .btn-cancel {
    width: 100%;
    padding: 8px;
  }

  .progress-text {
    flex-direction: column;
    gap: 2px;
    font-size: 12px;
  }

  .module-item {
    gap: 8px;
    padding: 10px 0;
  }

  .module-status {
    font-size: 16px;
    width: 20px;
  }

  .module-name {
    font-size: 13px;
  }

  .module-info {
    font-size: 11px;
  }

  .btn-report {
    padding: 8px 18px;
    font-size: 13px;
  }
}

@media screen and (max-width: 480px) {
  .run-card {
    padding: 14px;
    border-radius: 10px;
  }

  .run-title {
    font-size: 14px;
  }

  .suite-tag {
    font-size: 11px;
    padding: 2px 6px;
    margin-left: 6px;
  }

  .module-item {
    gap: 6px;
    padding: 8px 0;
  }

  .module-status {
    font-size: 14px;
    width: 18px;
  }

  .module-name {
    font-size: 12px;
  }

  .module-info {
    font-size: 10px;
  }

  .btn-report {
    padding: 7px 16px;
    font-size: 12px;
  }

  .done-banner {
    padding: 16px;
    font-size: 13px;
  }
}
</style>