<template>
  <v-dialog
    :model-value="modelValue"
    max-width="560"
    scrollable
    @update:model-value="emit('update:modelValue', $event)"
  >
    <v-card border>
      <v-card-title class="d-flex align-center">
        {{ title }}
        <v-spacer />
        <v-btn
          icon="mdi-close"
          variant="text"
          size="small"
          :disabled="loading"
          @click="emit('update:modelValue', false)"
        />
      </v-card-title>
      <v-divider />
      <v-card-text class="pt-4">
        <v-progress-linear v-if="loading" indeterminate color="primary" class="mb-2" />
        <p v-if="loading" class="text-body-2 text-medium-emphasis mb-0">正在加载结果…</p>
        <template v-else-if="results.length">
          <p class="text-body-2 mb-3">
            成功 <span class="text-success font-weight-medium">{{ okCount }}</span> 台，
            失败 <span class="text-error font-weight-medium">{{ failCount }}</span> 台
          </p>
          <v-list density="compact" class="rounded border">
            <v-list-item v-for="row in results" :key="row.server_id" class="py-1">
              <template #prepend>
                <v-icon :color="row.success ? 'success' : 'error'" size="18">
                  {{ row.success ? 'mdi-check-circle' : 'mdi-close-circle' }}
                </v-icon>
              </template>
              <v-list-item-title class="text-body-2">
                {{ row.server_name?.trim() || '未知服务器' }}
              </v-list-item-title>
              <v-list-item-subtitle
                v-if="row.success && row.stdout"
                class="text-caption text-medium-emphasis"
              >
                {{ row.stdout }}
              </v-list-item-subtitle>
              <v-list-item-subtitle
                v-else-if="!row.success && row.error"
                class="text-caption text-error"
              >
                {{ row.error }}
              </v-list-item-subtitle>
            </v-list-item>
          </v-list>
        </template>
        <p v-else class="text-medium-emphasis mb-0">无结果</p>
      </v-card-text>
      <v-divider />
      <v-card-actions class="pa-4">
        <v-spacer />
        <v-btn color="primary" variant="flat" :disabled="loading" @click="emit('update:modelValue', false)">
          关闭
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import type { BatchAgentResultItem } from '@/utils/serverSelection'

const props = defineProps<{
  modelValue: boolean
  title: string
  loading: boolean
  results: BatchAgentResultItem[]
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>()

const okCount = computed(() => props.results.filter(r => r.success).length)
const failCount = computed(() => props.results.length - okCount.value)
</script>
