<template>
  <div>
    <div class="page-header">
      <h1>数据管理</h1>
      <p>备份、恢复与清除系统数据</p>
    </div>

    <!-- Backup -->
    <div class="content-card">
      <div class="card-title">💾 手动备份</div>
      <p style="color: var(--text-muted); margin-bottom: 16px;">
        将当前全部数据（用户、项目、工时记录）导出为 JSON 文件，可用于恢复。
      </p>
      <el-button type="primary" @click="handleBackup" :loading="backingUp">⬇️ 立即备份 / 下载</el-button>
    </div>

    <!-- Auto-backup list -->
    <div class="content-card" style="margin-top: 20px;">
      <div class="card-title">
        <span>🕐 自动备份列表</span>
        <el-button size="small" @click="loadBackups" :loading="loadingBackups">刷新</el-button>
      </div>
      <p style="color: var(--text-muted); font-size: 13px; margin-bottom: 14px;">
        系统每天凌晨3点自动备份，最多保留30天。
      </p>
      <el-table :data="backups" stripe v-loading="loadingBackups" empty-text="暂无自动备份">
        <el-table-column prop="name" label="文件名" min-width="220" />
        <el-table-column label="大小" width="100">
          <template #default="{ row }">{{ (row.size / 1024).toFixed(1) }} KB</template>
        </el-table-column>
        <el-table-column label="备份时间" min-width="180">
          <template #default="{ row }">{{ row.created_at?.slice(0, 19).replace('T', ' ') }}</template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button size="small" @click="downloadAutoBackup(row.name)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Restore -->
    <div class="content-card" style="margin-top: 20px;">
      <div class="card-title">📂 从备份文件恢复</div>
      <p style="color: var(--text-muted); font-size: 13px; margin-bottom: 16px;">
        上传一个 <code>.json</code> 备份文件，系统将清除当前全部数据并从备份中恢复。<br/>
        ⚠️ 此操作不可撤销，请确认您已保留重要数据。
      </p>
      <el-upload
        accept=".json"
        :auto-upload="false"
        :show-file-list="true"
        :limit="1"
        :on-change="handleFileChange"
        :on-exceed="() => ElMessage.warning('只能选择一个文件')"
      >
        <el-button>选择备份文件 (.json)</el-button>
      </el-upload>
      <el-button type="warning" style="margin-top: 12px" :loading="restoring"
        :disabled="!restoreFile" @click="handleRestore">
        🔄 开始恢复
      </el-button>
    </div>

    <!-- Danger zone: Reset -->
    <div class="content-card danger-card" style="margin-top: 20px;">
      <div class="card-title" style="color: #f87171;">⚠️ 危险操作</div>
      <p style="color: var(--text-muted); font-size: 13px; margin-bottom: 16px;">
        清除所有工时记录与客户/项目数据，<strong>用户账号保留</strong>。此操作不可撤销。
      </p>
      <el-button type="danger" @click="handleReset" :loading="resetting">🗑️ 清除所有项目与工时数据</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminApi } from '../../api'

const backingUp = ref(false)
const loadingBackups = ref(false)
const backups = ref([])
const restoring = ref(false)
const resetting = ref(false)
const restoreFile = ref(null)

async function handleBackup() {
  backingUp.value = true
  try {
    const response = await adminApi.downloadBackup()
    const date = new Date().toISOString().slice(0, 10)
    downloadBlob(response.data, `backup-${date}.json`)
    ElMessage.success('备份文件已下载')
  } finally { backingUp.value = false }
}

async function loadBackups() {
  loadingBackups.value = true
  try {
    const res = await adminApi.getBackups()
    backups.value = res.data
  } finally { loadingBackups.value = false }
}

async function downloadAutoBackup(filename) {
  const response = await adminApi.downloadAutoBackup(filename)
  downloadBlob(response.data, filename)
}

function handleFileChange(file) {
  restoreFile.value = file.raw
}

async function handleRestore() {
  if (!restoreFile.value) return
  await ElMessageBox.confirm(
    '恢复将清除当前所有数据，替换为备份内容。此操作不可撤销，确定继续吗？',
    '确认恢复', { type: 'warning', confirmButtonText: '确认恢复', cancelButtonText: '取消' }
  )
  restoring.value = true
  try {
    const text = await restoreFile.value.text()
    const data = JSON.parse(text)
    const res = await adminApi.restoreData(data)
    ElMessage.success(res.message || '恢复成功')
    restoreFile.value = null
  } catch (e) {
    if (e?.response?.data?.message) ElMessage.error(e.response.data.message)
  } finally { restoring.value = false }
}

async function handleReset() {
  await ElMessageBox.confirm(
    '此操作将永久删除所有工时记录和客户/项目数据，用户账号保留。确定吗？',
    '二次确认', { type: 'error', confirmButtonText: '确认清除', cancelButtonText: '取消' }
  )
  await ElMessageBox.confirm(
    '最后确认：所有数据将无法恢复，请确保已备份！',
    '最终确认', { type: 'error', confirmButtonText: '我确认，执行清除', cancelButtonText: '取消' }
  )
  resetting.value = true
  try {
    const res = await adminApi.resetData()
    ElMessage.success(res.message || '数据已清除')
  } finally { resetting.value = false }
}

function downloadBlob(data, filename) {
  const url = URL.createObjectURL(new Blob([data]))
  const link = document.createElement('a')
  link.href = url; link.download = filename; link.click()
  URL.revokeObjectURL(url)
}

onMounted(loadBackups)
</script>

<style scoped>
.danger-card {
  border: 1px solid rgba(248, 113, 113, 0.3) !important;
  background: rgba(248, 113, 113, 0.04) !important;
}
code {
  background: rgba(255,255,255,0.1);
  padding: 1px 6px;
  border-radius: 4px;
  font-family: monospace;
}
</style>
