<template>
  <div class="reports-container">
    <h2>值班报告管理</h2>

    <div class="report-form">
      <h3>生成新报告</h3>
      <div class="form-group">
        <label>报告人:</label>
        <input v-model="form.reporter_name" placeholder="默认为当前登录用户" />
      </div>
      <div class="form-group">
        <label>开始时间:</label>
        <input type="datetime-local" v-model="form.start_time" step="1" />
      </div>
      <div class="form-group">
        <label>结束时间:</label>
        <input type="datetime-local" v-model="form.end_time" step="1" />
      </div>
      <button @click="createReport" :disabled="loading">生成报告</button>
    </div>

    <div class="report-list">
      <h3>历史报告</h3>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>报告人</th>
            <th>时间范围</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="report in reports" :key="report.id">
            <td>{{ report.id }}</td>
            <td>{{ report.reporter_name }}</td>
            <td>
              {{ formatDateTime(report.start_time) }} - <br/>
              {{ formatDateTime(report.end_time) }}
            </td>
            <td>
              <span :class="getStatusClass(report.status)">{{ report.status }}</span>
            </td>
            <td>{{ formatDateTime(report.created_at) }}</td>
            <td>
              <button 
                v-if="report.status === 'completed'" 
                @click="downloadReport(report.id)"
              >
                下载 PDF
              </button>
              <span v-else-if="report.status === 'failed'">生成失败</span>
              <span v-else>生成中...</span>
            </td>
          </tr>
        </tbody>
      </table>
      
      <div class="pagination">
        <button @click="prevPage" :disabled="page === 0">上一页</button>
        <span>第 {{ page + 1 }} 页</span>
        <button @click="nextPage" :disabled="reports.length < limit">下一页</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import api from '../api'

interface Report {
  id: number
  reporter_name: string
  start_time: string
  end_time: string
  status: string
  file_path: string | null
  created_at: string
}

const reports = ref<Report[]>([])
const loading = ref(false)
const page = ref(0)
const limit = 10

const form = ref({
  reporter_name: '',
  start_time: '',
  end_time: ''
})

// Set default times (last 24 hours)
const now = new Date()
now.setMinutes(now.getMinutes() - now.getTimezoneOffset()) // Adjust to local ISO string
const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000)

form.value.end_time = now.toISOString().slice(0, 19)
form.value.start_time = yesterday.toISOString().slice(0, 19)

const fetchReports = async () => {
  try {
    const res = await api.get('/reports/', {
      params: {
        skip: page.value * limit,
        limit: limit
      }
    })
    reports.value = res.data
  } catch (error) {
    console.error('Failed to fetch reports:', error)
  }
}

const createReport = async () => {
  if (!form.value.start_time || !form.value.end_time) {
    alert('请选择时间范围')
    return
  }

  loading.value = true
  try {
    await api.post('/reports/', {
      reporter_name: form.value.reporter_name || undefined,
      start_time: new Date(form.value.start_time).toISOString(),
      end_time: new Date(form.value.end_time).toISOString()
    })
    // Reset form or keep it?
    fetchReports()
  } catch (error) {
    console.error('Failed to create report:', error)
    alert('生成报告失败')
  } finally {
    loading.value = false
  }
}

const downloadReport = async (reportId: number) => {
  try {
    // Construct download URL
    // const url = `${getBaseURL()}/reports/${reportId}/download`

    
    // Create hidden link to trigger download
    // Using axios for download needs blob handling, simpler to use window.open or link click with token
    // Since we use bearer token, we can't just open a new window unless we use a cookie or pass token in query (insecure)
    // So we use axios to get blob
    
    const response = await api.get(`/reports/${reportId}/download`, {
      responseType: 'blob'
    })
    
    const blob = new Blob([response.data], { type: 'application/pdf' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `report_${reportId}.pdf`
    link.click()
    
  } catch (error) {
    console.error('Download failed:', error)
    alert('下载失败')
  }
}

const formatDateTime = (dtStr: string) => {
  if (!dtStr) return ''
  // 后端返回的是 UTC 时间（ISO 格式，可能不带 Z），前端需要将其转换为本地时间显示
  // 如果字符串不包含时区信息（Z 或 +），手动添加 Z 视为 UTC
  if (!dtStr.includes('Z') && !dtStr.includes('+')) {
    dtStr += 'Z'
  }
  return new Date(dtStr).toLocaleString()
}

const getStatusClass = (status: string) => {
  return {
    'status-pending': status === 'pending',
    'status-completed': status === 'completed',
    'status-failed': status === 'failed'
  }
}

const prevPage = () => {
  if (page.value > 0) {
    page.value--
    fetchReports()
  }
}

const nextPage = () => {
  page.value++
  fetchReports()
}

onMounted(() => {
  fetchReports()
  // Poll for updates every 5 seconds if there are pending reports
  setInterval(() => {
    if (reports.value.some(r => r.status === 'pending')) {
      fetchReports()
    }
  }, 5000)
})
</script>

<style scoped>
.reports-container {
  padding: 20px;
}

.report-form {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.form-group label {
  width: 100px;
  font-weight: bold;
}

.form-group input {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 250px;
}

button {
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 15px;
}

th, td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
}

.pagination {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
  justify-content: center;
}

.status-pending {
  color: orange;
}
.status-completed {
  color: green;
}
.status-failed {
  color: red;
}
</style>
