<template>
  <div class="app-container">
    <!-- 备份记录 -->
    <a-card class="box-card">
      <template #title>
        <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
          <span style="font-weight: bold;">备份记录</span>
          <div>
             <a-button type="primary" @click="openConfig" style="margin-right: 10px">备份策略配置</a-button>
             <a-button type="primary" status="success" @click="manualBackup" :loading="backingUp">立即备份</a-button>
             <a-button @click="fetchLogs" style="margin-left: 10px">刷新</a-button>
          </div>
        </div>
      </template>
      <a-table :data="logs" :columns="columns" style="width: 100%" :loading="tableLoading" :pagination="false">
        <template #status="{ record }">
           <a-tag :color="record.status === 'SUCCESS' ? 'green' : 'red'">{{ record.status }}</a-tag>
        </template>
        <template #uploadStatus="{ record }">
           <a-tag v-if="record.uploadStatus === 'UPLOADED'" color="green">已上传</a-tag>
           <a-tag v-else color="gray">未上传</a-tag>
        </template>
        <template #operation="{ record }">
           <a-button type="text" size="small" @click="downloadBackup(record)" :disabled="record.uploadStatus !== 'UPLOADED'">下载</a-button>
        </template>
      </a-table>
    </a-card>

    <!-- 备份策略配置弹窗 -->
    <a-modal v-model:visible="configVisible" title="备份策略配置" @before-ok="saveConfig" width="800px">
      <a-form :model="config" :label-col-props="{span: 6}" :wrapper-col-props="{span: 18}">
        <a-form-item label="数据库自动备份">
          <a-switch v-model="config.enabled" active-text="开启" inactive-text="关闭" />
          <span style="margin-left: 10px; color: #909399;">(备份完整的 PostgreSQL 数据库)</span>
        </a-form-item>
        <a-form-item label="资源配置自动备份">
          <a-switch v-model="config.resourceEnabled" active-text="开启" inactive-text="关闭" />
          <span style="margin-left: 10px; color: #909399;">(导出资源中心配置为 Zip: 数据源、设备、模板、拓扑)</span>
        </a-form-item>
        <a-form-item label="每日备份时间">
          <a-time-picker v-model="config.time" format="HH:mm" value-format="HH:mm" placeholder="选择时间" style="width: 100%;" />
        </a-form-item>
        <a-form-item label="本地保留天数">
          <a-input-number v-model="config.keepDays" :min="1" :max="365" />
          <span style="margin-left: 10px; color: #909399;">(MinIO 上的文件建议配置生命周期规则管理)</span>
        </a-form-item>
        
        <a-divider orientation="left">MinIO 存储配置 (已部署服务)</a-divider>
        <a-form-item label="Endpoint">
          <a-input v-model="config.endpoint" placeholder="例如: 192.168.1.100:9000" />
        </a-form-item>
        <a-form-item label="Access Key">
          <a-input v-model="config.accessKey" placeholder="MinIO Access Key" />
        </a-form-item>
        <a-form-item label="Secret Key">
          <a-input-password v-model="config.secretKey" placeholder="MinIO Secret Key" />
        </a-form-item>
        <a-form-item label="Bucket Name">
          <a-input v-model="config.bucket" placeholder="存储桶名称，如: ems-backups" />
        </a-form-item>
        
        <a-form-item>
           <a-button type="secondary" @click="testConnection" :loading="testingConnection">测试连接</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import api from '../../api'

const backingUp = ref(false)
const tableLoading = ref(false)
const testingConnection = ref(false)
const configVisible = ref(false)

const columns = [
  { title: '开始时间', dataIndex: 'startTime', width: 180 },
  { title: '状态', dataIndex: 'status', width: 100, slotName: 'status' },
  { title: '文件名', dataIndex: 'fileName', width: 200 },
  { title: '大小', dataIndex: 'size', width: 120 },
  { title: 'MinIO上传', dataIndex: 'uploadStatus', width: 120, slotName: 'uploadStatus' },
  { title: '操作', width: 120, slotName: 'operation' },
  { title: '备注', dataIndex: 'message', ellipsis: true, tooltip: true }
]

const config = reactive({
  enabled: false,
  resourceEnabled: false,
  time: '03:00',
  keepDays: 7,
  endpoint: '',
  accessKey: '',
  secretKey: '',
  bucket: ''
})

const logs = ref([])

onMounted(() => {
  fetchConfig()
  fetchLogs()
})

function openConfig() {
  configVisible.value = true
  fetchConfig() // Ensure config is fresh when opening
}

async function fetchConfig() {
  try {
    const res: any = await api.get('/backup/config')
    if (res && res.data) {
      Object.assign(config, res.data)
    }
  } catch (error) {
    console.error('Failed to load backup config', error)
  }
}

async function saveConfig() {
  // loading state is handled by Modal if we return a promise (which async function does)
  try {
    await api.post('/backup/config', config)
    Message.success('配置已保存')
    return true
  } catch (error) {
    Message.error('保存失败')
    return false
  }
}

async function testConnection() {
  testingConnection.value = true
  try {
    const res: any = await api.post('/backup/test', config)
    if (res.success) {
      Message.success('连接测试成功')
    } else {
      Message.error('连接失败: ' + res.message)
    }
  } catch (error) {
    Message.error('连接测试请求失败')
  } finally {
    testingConnection.value = false
  }
}

async function manualBackup() {
  backingUp.value = true
  try {
    await api.post('/backup/exec')
    Message.success('备份任务已触发')
    // 延迟一下刷新列表
    setTimeout(fetchLogs, 1000)
  } catch (error) {
    Message.error('触发备份失败')
  } finally {
    backingUp.value = false
  }
}

async function downloadBackup(record: any) {
  // Use window.open or hidden form to trigger download
  // API URL needs to include auth token if backend requires it.
  // Since we use 'api' client usually, we can use it to get blob but window.open is simpler if we have token.
  // Actually, api client handles interceptors. Better to use api client with responseType blob.
  
  try {
     // const token = localStorage.getItem('token') || ''; // Assuming token storage
     // Construct URL manually if using window.open, but let's try fetch first
     
     // Method 1: Direct link (Requires token in query param or cookie if header not possible)
     // Since our backend expects Header "Authorization", window.open won't work easily without a "download token" mechanism.
     // Method 2: Axios Blob
     const res = await api.get(`/backup/download/${record.id}`, { responseType: 'blob' })
     const url = window.URL.createObjectURL(new Blob([res as any]));
     const link = document.createElement('a');
     link.href = url;
     link.setAttribute('download', record.fileName || 'backup.sql'); // or extract from content-disposition
     document.body.appendChild(link);
     link.click();
     document.body.removeChild(link);
  } catch (error) {
     Message.error('下载失败')
     console.error(error)
  }
}

async function fetchLogs() {
  tableLoading.value = true
  try {
    const res: any = await api.get('/backup/logs')
    console.log('Logs response:', res) // Debug log
    logs.value = res.data || (Array.isArray(res) ? res : [])
  } catch (error) {
    console.error(error)
  } finally {
    tableLoading.value = false
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
