<template>
  <v-card v-if="items.length > 0" class="mb-4" elevation="0" border rounded="lg">
    <v-card-title class="d-flex align-center text-subtitle-1">
      推送进度
      <v-spacer />
      <v-btn
        v-if="failedRetryCount > 0 && !pushing"
        size="small"
        variant="tonal"
        color="warning"
        class="mr-2"
        prepend-icon="mdi-refresh"
        :loading="retryingAll"
        @click="$emit('retry-all')"
      >
        重试全部失败 ({{ failedRetryCount }})
      </v-btn>
      <v-btn
        v-if="batchId && items.some(s => s.status === 'running' || s.status === 'pending') && pushing"
        size="small"
        variant="tonal"
        color="error"
        class="mr-2"
        :loading="cancelling"
        @click="$emit('cancel')"
      >
        取消推送
      </v-btn>
      <v-chip size="small" variant="tonal" color="primary">
        {{ items.filter(s => s.status === 'success').length }}/{{ items.length }} 完成
      </v-chip>
    </v-card-title>
    <v-divider />
    <v-card-text>
      <v-progress-linear
        v-if="pushing || totalProgress > 0"
        :model-value="totalProgress"
        color="primary"
        height="8"
        rounded
        class="mb-3"
      />
      <div v-if="items.length" class="text-caption text-medium-emphasis mb-2">
        {{ doneCount }} / {{ items.length }} 台已结束
        <span v-if="items.some(s => s.status === 'failed')">
          · {{ items.filter(s => s.status === 'failed').length }} 失败
        </span>
      </div>
      <v-list density="compact">
        <v-list-item v-for="s in items" :key="s.id">
          <template #title>
            <span class="push-progress-name" :title="s.name">{{ s.name }}</span>
          </template>
          <template #append>
            <v-icon v-if="s.status === 'pending'" color="grey">mdi-clock-outline</v-icon>
            <v-icon v-else-if="s.status === 'running'" color="blue" class="mdi-spin">mdi-loading</v-icon>
            <v-icon v-else-if="s.status === 'success'" color="green">mdi-check-circle</v-icon>
            <v-icon v-else-if="s.status === 'cancelled'" color="grey">mdi-cancel</v-icon>
            <v-icon v-else color="red">mdi-alert-circle</v-icon>
          </template>
          <template v-if="s.detail" #subtitle>
            <span
              :class="s.status === 'failed' ? 'text-error' : 'text-medium-emphasis'"
            >{{ s.detail }}</span>
          </template>
        </v-list-item>
      </v-list>
    </v-card-text>
  </v-card>
</template>

<script setup lang="ts">
import type { ServerProgress } from '@/composables/push/types'

defineProps<{
  items: ServerProgress[]
  batchId: string
  pushing: boolean
  cancelling: boolean
  retryingAll: boolean
  failedRetryCount: number
  doneCount: number
  totalProgress: number
}>()

defineEmits<{
  cancel: []
  'retry-all': []
}>()
</script>

<style scoped>
.push-progress-name {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
