<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Box } from '@element-plus/icons-vue'
import type { SyncLog } from '@/types'
import { syncApi } from '@/api/sync'

const logs = ref<SyncLog[]>([])
const loading = ref(false)
const syncing = ref(false)

let timer: ReturnType<typeof setInterval> | null = null

async function refreshLogs() {
  loading.value = true
  try {
    const data = await syncApi.getSyncStatus(50) as any
    logs.value = Array.isArray(data) ? data : []
  } catch (err) {
    console.warn('Failed to fetch sync status', err)
  } finally {
    loading.value = false
  }
}

async function handleSync() {
  try {
    await ElMessageBox.confirm(
      '确定立即执行产品同步吗？此操作可能需要一些时间。',
      '确认',
      { type: 'info', confirmButtonText: '执行', cancelButtonText: '取消' }
    )
  } catch { return }

  syncing.value = true
  try {
    await syncApi.syncProducts()
    ElMessage.success('产品同步完成')
    await refreshLogs()
  } catch {
    ElMessage.error('产品同步失败')
  } finally {
    syncing.value = false
  }
}

function formatDate(s?: string): string {
  if (!s) return '-'
  return new Date(s).toLocaleString()
}

onMounted(() => {
  refreshLogs()
  timer = setInterval(refreshLogs, 30_000)
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
})
</script>

<template>
  <div class="page-container">
    <div class="sync-cards">
      <el-card class="sync-card">
        <template #header>
          <div class="sync-card-header">
            <div class="sync-card-title">
              <el-icon><Box /></el-icon>
              <span>产品同步</span>
            </div>
          </div>
        </template>
        <p class="sync-card-desc">
          从上游拉取最新产品和原产品并与本地数据库进行同步。
        </p>
        <el-button type="primary" :loading="syncing" @click="handleSync">
          <el-icon><Refresh /></el-icon>
          <span>执行产品同步</span>
        </el-button>
      </el-card>
    </div>

    <div class="page-card logs-card">
      <div class="logs-toolbar">
        <h3 class="logs-title">同步日志</h3>
        <el-button @click="refreshLogs">
          <el-icon><Refresh /></el-icon>
          <span>刷新</span>
        </el-button>
      </div>

      <el-table v-loading="loading" :data="logs" border stripe>
        <el-table-column label="状态" width="100">
          <template #default="{ row }: { row: SyncLog }">
            <el-tag :type="row.status === 'SUCCESS' ? 'success' : 'danger'" size="small">
              {{ row.status === 'SUCCESS' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="时间" width="200">
          <template #default="{ row }: { row: SyncLog }">
            {{ formatDate(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="message" label="信息" min-width="200" show-overflow-tooltip />
        <template #empty>
          <el-empty description="暂无同步记录" />
        </template>
      </el-table>
    </div>
  </div>
</template>

<style scoped>
.sync-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
  margin-bottom: 16px;
}

.sync-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.sync-card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 15px;
}

.sync-card-title :deep(.el-icon) {
  color: var(--brand-color);
}

.sync-card-desc {
  color: #6b7280;
  font-size: 13px;
  margin: 0 0 16px;
  min-height: 40px;
}

.logs-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.logs-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}
</style>
