<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>数据备份管理</span>
        </div>
      </template>

      <!-- Settings Section -->
      <div class="settings-section">
        <h3>自动备份设置</h3>
        <el-form :inline="true" :model="settingsForm" class="settings-form">
          <el-form-item label="开启自动备份">
            <el-switch v-model="settingsForm.auto_backup_enabled" />
          </el-form-item>
          <el-form-item label="备份时间 (每天)">
            <el-time-select
              v-model="settingsForm.backup_time"
              start="00:00"
              step="00:30"
              end="23:30"
              placeholder="选择时间"
              :disabled="!settingsForm.auto_backup_enabled"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveSettings" :loading="savingSettings">保存设置</el-button>
          </el-form-item>
        </el-form>
        <div v-if="settingsForm.last_backup_at" class="last-backup-info">
          上次自动备份时间: {{ formatDate(settingsForm.last_backup_at) }}
        </div>
      </div>

      <el-divider />

      <!-- Manual Backup Section -->
      <div class="manual-backup-section">
        <div class="header-actions">
           <h3>备份记录</h3>
           <el-button type="success" @click="handleManualBackup" :loading="creatingBackup">
            立即备份
           </el-button>
        </div>
        
        <!-- Search Filter -->
        <div class="filter-container">
           <el-form :inline="true" :model="queryParams" class="demo-form-inline">
             <el-form-item label="日期范围">
               <el-date-picker
                 v-model="dateRange"
                 type="daterange"
                 range-separator="至"
                 start-placeholder="开始日期"
                 end-placeholder="结束日期"
                 value-format="YYYY-MM-DD"
                 @change="handleFilterChange"
               />
             </el-form-item>
             <el-form-item label="排序">
                <el-select v-model="queryParams.sort_order" placeholder="选择排序" @change="handleFilterChange" style="width: 120px">
                   <el-option label="时间倒序" value="desc" />
                   <el-option label="时间正序" value="asc" />
                </el-select>
             </el-form-item>
             <el-form-item>
                <el-button type="primary" @click="handleFilterChange">查询</el-button>
             </el-form-item>
           </el-form>
        </div>
      </div>

      <!-- Backup List Section -->
      <div class="list-section">
        <el-table :data="backupList" style="width: 100%" v-loading="loadingList">
          <el-table-column prop="filename" label="文件名" min-width="200" />
          <el-table-column prop="created_at" label="备份时间" width="180">
             <template #default="scope">
                {{ formatDate(scope.row.created_at) }}
             </template>
          </el-table-column>
          <el-table-column prop="backup_type" label="类型" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.backup_type === 'AUTO' ? 'info' : 'success'">
                {{ scope.row.backup_type === 'AUTO' ? '自动' : '手动' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="file_size" label="大小" width="120">
            <template #default="scope">
              {{ formatSize(scope.row.file_size) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="primary" link @click="handleDownload(scope.row)">
                下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- Pagination -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  getBackups, 
  createBackup, 
  getBackupSettings, 
  updateBackupSettings,
  getDownloadUrl,
  type BackupRecord 
} from '../../../api/backup'

// --- State ---
const settingsForm = reactive({
  auto_backup_enabled: false,
  backup_time: '02:00',
  last_backup_at: null as string | null
})
const savingSettings = ref(false)

const creatingBackup = ref(false)

const backupList = ref<BackupRecord[]>([])
const loadingList = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

const dateRange = ref<string[] | null>(null)
const queryParams = reactive({
  sort_order: 'desc'
})

// --- Methods ---

const loadSettings = async () => {
  try {
    const res = await getBackupSettings()
    const data = res.data
    settingsForm.auto_backup_enabled = data.auto_backup_enabled
    settingsForm.backup_time = data.backup_time
    settingsForm.last_backup_at = data.last_backup_at
  } catch (e) {
    // ElMessage.error('加载设置失败')
    console.error(e)
  }
}

const saveSettings = async () => {
  savingSettings.value = true
  try {
    await updateBackupSettings({
      auto_backup_enabled: settingsForm.auto_backup_enabled,
      backup_time: settingsForm.backup_time
    })
    ElMessage.success('设置保存成功')
  } catch (e) {
    ElMessage.error('保存设置失败')
  } finally {
    savingSettings.value = false
  }
}

const loadBackups = async () => {
  loadingList.value = true
  try {
    const params: any = {
       skip: (currentPage.value - 1) * pageSize.value,
       limit: pageSize.value,
       sort_order: queryParams.sort_order
    }
    
    if (dateRange.value && dateRange.value.length === 2) {
        params.start_date = dateRange.value[0]
        params.end_date = dateRange.value[1]
    }
    
    const res = await getBackups(params)
    // Adjust for new response structure { total, items }
    if (res.data && Array.isArray(res.data.items)) {
       backupList.value = res.data.items
       total.value = res.data.total
    } else {
       // Fallback for old API if cached or mismatch
       backupList.value = Array.isArray(res.data) ? res.data : []
       total.value = backupList.value.length
    }

  } catch (e) {
    ElMessage.error('加载备份列表失败')
  } finally {
    loadingList.value = false
  }
}

const handleFilterChange = () => {
    currentPage.value = 1
    loadBackups()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadBackups()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadBackups()
}

const handleManualBackup = async () => {
  creatingBackup.value = true
  try {
    await createBackup()
    ElMessage.success('备份成功')
    // Reset to first page to see new backup
    currentPage.value = 1
    queryParams.sort_order = 'desc' 
    loadBackups()
  } catch (e) {
    ElMessage.error('备份失败')
  } finally {
    creatingBackup.value = false
  }
}

const handleDownload = async (record: BackupRecord) => {
  try {
    const token = localStorage.getItem('token')
    const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000/api/v1'
    const relativeUrl = getDownloadUrl(record.id)
    
    const response = await fetch(`${baseUrl}${relativeUrl}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (!response.ok) throw new Error('Download failed')
    
    const blob = await response.blob()
    const downloadUrl = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = downloadUrl
    a.download = record.filename
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(downloadUrl)
  } catch (e) {
    ElMessage.error('下载失败')
  }
}

const formatSize = (bytes: number) => {
  if (!bytes && bytes !== 0) return '未知'
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDate = (dateStr: string) => {
    if (!dateStr) return '-'
    return new Date(dateStr).toLocaleString()
}

// --- Lifecycle ---
onMounted(() => {
  loadSettings()
  loadBackups()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.settings-section, .manual-backup-section, .list-section {
  padding: 10px 0;
}
.last-backup-info {
    font-size: 12px;
    color: #666;
    margin-top: -10px;
    margin-bottom: 10px;
}
.header-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}
.filter-container {
    background-color: #f5f7fa;
    padding: 15px 15px 0 15px;
    border-radius: 4px;
    margin-bottom: 20px;
}
.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>
