<template>
  <div class="backup-manage">
    <div class="toolbar">
      <el-button type="primary" @click="handleCreate"><el-icon><Plus /></el-icon>创建备份</el-button>
      <el-button @click="loadList"><el-icon><Refresh /></el-icon>刷新</el-button>
    </div>
    <el-table :data="list" v-loading="loading" stripe size="small" style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="name" label="名称" min-width="140" show-overflow-tooltip />
      <el-table-column prop="vm_id" label="虚拟机ID" width="90" />
      <el-table-column prop="host_id" label="宿主机ID" width="90" />
      <el-table-column label="状态" width="90">
        <template #default="{ row }">
          <el-tag :type="taskStatusType(row.status)" size="small">
            {{ statusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="任务ID" width="160">
        <template #default="{ row }">
          <span style="font-family: Consolas, monospace; font-size: 12px">{{ row.task_id || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="170">
        <template #default="{ row }">{{ formatTs(row.created_at) }}</template>
      </el-table-column>
      <el-table-column label="更新时间" width="170">
        <template #default="{ row }">{{ formatTs(row.updated_at) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" size="small" @click="handleRestore(row)">恢复</el-button>
          <el-button link type="info" size="small" @click="handleProgress(row)" v-if="row.status === 'running' || row.status === 'pending'">进度</el-button>
          <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-empty v-if="!list.length && !loading" description="暂无备份数据" />
    <div class="pagination-wrapper" v-if="total > 0">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]" :total="total" layout="total, sizes, prev, pager, next"
        @size-change="s => { pageSize = s; currentPage = 1; loadList() }"
        @current-change="p => { currentPage = p; loadList() }" />
    </div>

    <el-dialog v-model="createVisible" title="创建备份" width="480px" destroy-on-close>
      <el-form :model="createForm" label-width="100px">
        <el-form-item label="虚拟机" required>
          <el-select v-model="createForm.vm_id" placeholder="请选择虚拟机" filterable style="width: 100%" :loading="vmOptionsLoading">
            <el-option v-for="vm in vmOptions" :key="vm.id" :label="`${vm.name} (ID: ${vm.id})`" :value="vm.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="备份名称" required>
          <el-input v-model="createForm.name" placeholder="请输入备份名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitCreate">创建</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="progressVisible" title="备份任务进度" width="520px" destroy-on-close>
      <div v-loading="progressLoading">
        <el-descriptions :column="1" border size="small" v-if="progressData">
          <el-descriptions-item label="任务ID">
            <span style="font-family: Consolas, monospace; font-size: 13px">{{ progressData.task_id || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="taskStatusType(progressData.status)" size="small">{{ taskStatusLabel(progressData.status) }}</el-tag>
          </el-descriptions-item>
          <template v-if="parsedMeta">
            <el-descriptions-item v-for="(val, key) in parsedMeta" :key="key" :label="metaLabelMap[key] || key">
              <span :style="key.includes('path') ? 'font-family: Consolas, monospace; font-size: 13px; word-break: break-all' : ''">{{ val }}</span>
            </el-descriptions-item>
          </template>
        </el-descriptions>
        <el-empty v-else description="暂无进度信息" />
      </div>
      <template #footer>
        <el-button @click="progressVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleProgress(progressRow)" :loading="progressLoading" v-if="progressData?.status === 'running' || progressData?.status === 'pending'">刷新进度</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, inject, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
import { getBackupList, createBackup, restoreBackup, deleteBackup, getBackupProgress, getVmList } from '@/api/admin/kvmService'
import { extractApiError } from '@/utils/kvmErrorUtil'

const serviceId = inject('serviceId')
const loading = ref(false)
const submitLoading = ref(false)
const list = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

const statusLabel = (s) => ({ completed: '完成', ready: '完成', success: '成功', pending: '等待', running: '运行中', failed: '失败', error: '错误' }[s] || s || '-')
const formatTs = (ts) => {
  if (!ts) return '-'
  if (typeof ts === 'object' && ts.seconds) return new Date(Number(ts.seconds) * 1000).toLocaleString('zh-CN')
  return typeof ts === 'string' ? ts : '-'
}

const loadList = async () => {
  loading.value = true
  try {
    const res = await getBackupList({ service_id: serviceId.value, page: currentPage.value, page_size: pageSize.value })
    if (res?.data?.code === 200 && res?.data?.data) {
      const d = res.data.data
      list.value = d.data || d.list || (Array.isArray(d) ? d : [])
      total.value = d.meta?.count ?? d.total ?? list.value.length
    } else { list.value = []; total.value = 0 }
  } catch { list.value = []; total.value = 0 } finally { loading.value = false }
}

const vmOptions = ref([])
const vmOptionsLoading = ref(false)

const loadVmOptions = async () => {
  vmOptionsLoading.value = true
  try {
    const res = await getVmList({ service_id: serviceId.value, page: 1, count: 10 })
    if (res?.data?.code === 200 && res?.data?.data) {
      const inner = res.data.data
      vmOptions.value = inner.vms || inner.data || inner.list || (Array.isArray(inner) ? inner : [])
    }
  } catch { /* */ } finally { vmOptionsLoading.value = false }
}

const createVisible = ref(false)
const createForm = reactive({ vm_id: null, name: '' })

const handleCreate = async () => {
  Object.assign(createForm, { vm_id: null, name: '' })
  if (!vmOptions.value.length) await loadVmOptions()
  createVisible.value = true
}

const submitCreate = async () => {
  if (!createForm.vm_id || !createForm.name) { ElMessage.warning('请填写必填项'); return }
  submitLoading.value = true
  try {
    const fd = new FormData()
    fd.append('service_id', serviceId.value)
    fd.append('vm_id', createForm.vm_id)
    fd.append('name', createForm.name)
    const res = await createBackup(fd)
    if (res?.data?.code === 200) { ElMessage.success('备份创建成功'); createVisible.value = false; loadList() }
    else ElMessage.error(extractApiError(res?.data, '创建失败'))
  } catch (e) { ElMessage.error(extractApiError(e?.response?.data, '创建失败')) } finally { submitLoading.value = false }
}

const handleRestore = (row) => {
  ElMessageBox.confirm(`确定要恢复备份「${row.name}」到虚拟机(ID:${row.vm_id})吗？`, '恢复确认', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  }).then(async () => {
    try {
      const fd = new FormData()
      fd.append('service_id', serviceId.value)
      fd.append('backup_id', row.id)
      fd.append('vm_id', row.vm_id)
      const res = await restoreBackup(fd)
      if (res?.data?.code === 200) ElMessage.success('恢复操作已提交')
      else ElMessage.error(extractApiError(res?.data, '恢复失败'))
    } catch (e) { ElMessage.error(extractApiError(e?.response?.data, '恢复失败')) }
  }).catch(() => {})
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除备份「${row.name}」吗？`, '删除确认', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  }).then(async () => {
    try {
      const fd = new FormData()
      fd.append('service_id', serviceId.value)
      fd.append('backup_id', row.id)
      fd.append('vm_id', row.vm_id)
      const res = await deleteBackup(fd)
      if (res?.data?.code === 200) { ElMessage.success('删除成功'); loadList() }
      else ElMessage.error(extractApiError(res?.data, '删除失败'))
    } catch (e) { ElMessage.error(extractApiError(e?.response?.data, '删除失败')) }
  }).catch(() => {})
}

const progressVisible = ref(false)
const progressLoading = ref(false)
const progressData = ref(null)
const progressRow = ref(null)

const taskStatusType = (s) => ({ running: 'primary', completed: 'success', ready: 'success', success: 'success', failed: 'danger', error: 'danger', pending: 'info', cancelled: 'warning' }[s] || 'info')
const taskStatusLabel = (s) => ({ running: '运行中', completed: '已完成', ready: '已完成', success: '成功', failed: '失败', error: '错误', pending: '等待中', cancelled: '已取消' }[s] || s || '-')
const metaLabelMap = { vm_name: '虚拟机名称', backup_path: '备份路径', snapshot_path: '快照路径', path: '路径', progress: '进度', message: '信息', error: '错误信息' }

const parsedMeta = computed(() => {
  if (!progressData.value?.meta) return null
  const raw = progressData.value.meta
  if (typeof raw === 'object') return raw
  if (typeof raw === 'string') {
    const trimmed = raw.trim()
    if (!trimmed || trimmed === '""' || trimmed === '{}') return null
    try { return JSON.parse(trimmed) } catch { return { 信息: raw } }
  }
  return null
})

const handleProgress = async (row) => {
  progressRow.value = row
  progressData.value = null
  progressVisible.value = true
  progressLoading.value = true
  try {
    const res = await getBackupProgress({ service_id: serviceId.value, task_id: String(row.task_id || row.id) })
    if (res?.data?.code === 200) {
      const d = res.data.data
      progressData.value = d?.data ?? d
    } else ElMessage.warning('暂无进度信息')
  } catch { ElMessage.warning('获取进度失败') } finally { progressLoading.value = false }
}

onMounted(() => { loadList() })

defineExpose({ loadList })
</script>

<style scoped>
.backup-manage { padding: 0; }
.toolbar { margin-top: 12px; }
</style>
