<template>
  <div class="reports-page">
    <a-page-header
      title="报表管理"
      sub-title="生成和管理系统报表"
    >
      <template #extra>
        <a-space>
          <a-button @click="fetchReportList">
            <template #icon><ReloadOutlined /></template>
            刷新列表
          </a-button>
          <a-button type="primary" @click="showGenerateModal = true">
            <template #icon><FilePdfOutlined /></template>
            生成报表
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <div class="reports-content">
      <!-- 快捷导出区域 -->
      <a-card title="快捷数据导出" :bordered="false" style="margin-bottom: 24px;">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-button 
              type="primary" 
              block 
              :loading="exportLoading.farms"
              @click="quickExport('farms', 'excel')"
            >
              <template #icon><ExportOutlined /></template>
              导出农场数据
            </a-button>
          </a-col>
          <a-col :span="6">
            <a-button 
              type="primary" 
              block 
              :loading="exportLoading.devices"
              @click="quickExport('devices', 'excel')"
            >
              <template #icon><ExportOutlined /></template>
              导出设备数据
            </a-button>
          </a-col>
          <a-col :span="6">
            <a-button 
              type="primary" 
              block 
              :loading="exportLoading.animals"
              @click="quickExport('animals', 'excel')"
            >
              <template #icon><ExportOutlined /></template>
              导出动物数据
            </a-button>
          </a-col>
          <a-col :span="6">
            <a-button 
              type="primary" 
              block 
              :loading="exportLoading.alerts"
              @click="quickExport('alerts', 'excel')"
            >
              <template #icon><ExportOutlined /></template>
              导出预警数据
            </a-button>
          </a-col>
        </a-row>
      </a-card>

      <!-- 报表文件列表 -->
      <a-card title="历史报表文件" :bordered="false">
        <a-table
          :columns="reportColumns"
          :data-source="reportFiles"
          :loading="loading"
          :pagination="{ pageSize: 10 }"
          row-key="fileName"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'size'">
              {{ formatFileSize(record.size) }}
            </template>
            <template v-else-if="column.dataIndex === 'createdAt'">
              {{ formatDate(record.createdAt) }}
            </template>
            <template v-else-if="column.dataIndex === 'action'">
              <a-space>
                <a-button 
                  type="primary" 
                  size="small" 
                  @click="downloadReport(record)"
                >
                  <template #icon><DownloadOutlined /></template>
                  下载
                </a-button>
                <a-button 
                  type="primary" 
                  danger 
                  size="small" 
                  @click="deleteReport(record)"
                  v-if="userStore.userData?.roles?.includes('admin')"
                >
                  <template #icon><DeleteOutlined /></template>
                  删除
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 生成报表模态框 -->
    <a-modal
      v-model:open="showGenerateModal"
      title="生成报表"
      :confirm-loading="generateLoading"
      @ok="generateReport"
      @cancel="resetGenerateForm"
      width="600px"
    >
      <a-form
        ref="generateFormRef"
        :model="generateForm"
        :rules="generateRules"
        layout="vertical"
      >
        <a-form-item label="报表类型" name="reportType">
          <a-select v-model:value="generateForm.reportType" @change="onReportTypeChange">
            <a-select-option value="farm">养殖统计报表</a-select-option>
            <a-select-option value="sales">销售分析报表</a-select-option>
            <a-select-option value="compliance" v-if="userStore.userData?.roles?.includes('admin')">
              监管合规报表
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="开始日期" name="startDate">
              <a-date-picker 
                v-model:value="generateForm.startDate" 
                style="width: 100%;"
                format="YYYY-MM-DD"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="结束日期" name="endDate">
              <a-date-picker 
                v-model:value="generateForm.endDate" 
                style="width: 100%;"
                format="YYYY-MM-DD"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="报表格式" name="format">
          <a-radio-group v-model:value="generateForm.format">
            <a-radio-button value="pdf">PDF</a-radio-button>
            <a-radio-button value="excel">Excel</a-radio-button>
            <a-radio-button value="csv" v-if="generateForm.reportType === 'farm'">CSV</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item 
          label="选择农场" 
          name="farmIds" 
          v-if="generateForm.reportType === 'farm'"
        >
          <a-select
            v-model:value="generateForm.farmIds"
            mode="multiple"
            placeholder="不选择则包含所有农场"
            style="width: 100%;"
          >
            <a-select-option 
              v-for="farm in dataStore.farms" 
              :key="farm.id" 
              :value="farm.id"
            >
              {{ farm.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { 
  ReloadOutlined, 
  FilePdfOutlined, 
  ExportOutlined, 
  DownloadOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import { api } from '../utils/api'
import { useUserStore } from '../stores/user'
import { useDataStore } from '../stores/data'
import moment from 'moment'

// Store
const userStore = useUserStore()
const dataStore = useDataStore()

// 响应式数据
const loading = ref(false)
const generateLoading = ref(false)
const showGenerateModal = ref(false)
const reportFiles = ref([])

// 导出加载状态
const exportLoading = reactive({
  farms: false,
  devices: false,
  animals: false,
  alerts: false
})

// 生成报表表单
const generateFormRef = ref()
const generateForm = reactive({
  reportType: 'farm',
  startDate: moment().subtract(30, 'days'),
  endDate: moment(),
  format: 'pdf',
  farmIds: []
})

// 表单验证规则
const generateRules = {
  reportType: [{ required: true, message: '请选择报表类型' }],
  startDate: [{ required: true, message: '请选择开始日期' }],
  endDate: [{ required: true, message: '请选择结束日期' }],
  format: [{ required: true, message: '请选择报表格式' }]
}

// 报表文件列表表格列定义
const reportColumns = [
  {
    title: '文件名',
    dataIndex: 'fileName',
    key: 'fileName',
    ellipsis: true
  },
  {
    title: '文件大小',
    dataIndex: 'size',
    key: 'size',
    width: 120
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 150
  }
]

// 组件挂载时获取数据
onMounted(async () => {
  await dataStore.fetchAllData()
  await fetchReportList()
})

// 获取报表文件列表
async function fetchReportList() {
  loading.value = true
  try {
    const response = await api.get('/reports/list')
    if (response.success) {
      reportFiles.value = response.data
    }
  } catch (error) {
    console.error('获取报表列表失败:', error)
    message.error('获取报表列表失败')
  } finally {
    loading.value = false
  }
}

// 生成报表
async function generateReport() {
  try {
    await generateFormRef.value.validate()
    generateLoading.value = true

    const params = {
      startDate: generateForm.startDate.format('YYYY-MM-DD'),
      endDate: generateForm.endDate.format('YYYY-MM-DD'),
      format: generateForm.format
    }

    if (generateForm.reportType === 'farm' && generateForm.farmIds.length > 0) {
      params.farmIds = generateForm.farmIds
    }

    let endpoint = ''
    if (generateForm.reportType === 'farm') {
      endpoint = '/reports/farm'
    } else if (generateForm.reportType === 'sales') {
      endpoint = '/reports/sales'
    } else if (generateForm.reportType === 'compliance') {
      endpoint = '/reports/compliance'
    }

    const response = await api.post(endpoint, params)
    
    if (response.success) {
      message.success('报表生成成功')
      showGenerateModal.value = false
      resetGenerateForm()
      await fetchReportList()
      
      // 自动下载生成的报表
      if (response.data.downloadUrl) {
        window.open(`${api.baseURL}${response.data.downloadUrl}`, '_blank')
      }
    }
  } catch (error) {
    console.error('生成报表失败:', error)
    message.error('生成报表失败')
  } finally {
    generateLoading.value = false
  }
}

// 重置生成表单
function resetGenerateForm() {
  generateForm.reportType = 'farm'
  generateForm.startDate = moment().subtract(30, 'days')
  generateForm.endDate = moment()
  generateForm.format = 'pdf'
  generateForm.farmIds = []
}

// 报表类型改变时的处理
function onReportTypeChange(value) {
  if (value !== 'farm') {
    generateForm.farmIds = []
  }
}

// 快捷导出
async function quickExport(dataType, format) {
  exportLoading[dataType] = true
  try {
    let endpoint = ''
    let fileName = ''

    switch (dataType) {
      case 'farms':
        endpoint = '/reports/export/farms'
        fileName = `农场数据_${moment().format('YYYYMMDD_HHmmss')}.xlsx`
        break
      case 'devices':
        endpoint = '/reports/export/devices'
        fileName = `设备数据_${moment().format('YYYYMMDD_HHmmss')}.xlsx`
        break
      case 'animals':
        // 使用农场报表API导出动物数据
        endpoint = '/reports/farm'
        fileName = `动物数据_${moment().format('YYYYMMDD_HHmmss')}.xlsx`
        break
      case 'alerts':
        // 使用农场报表API导出预警数据
        endpoint = '/reports/farm'
        fileName = `预警数据_${moment().format('YYYYMMDD_HHmmss')}.xlsx`
        break
    }

    if (dataType === 'animals' || dataType === 'alerts') {
      // 生成包含动物或预警数据的报表
      const response = await api.post(endpoint, { format: 'excel' })
      if (response.success && response.data.downloadUrl) {
        downloadFile(`${api.baseURL}${response.data.downloadUrl}`, response.data.fileName)
        message.success('数据导出成功')
      }
    } else {
      // 直接导出
      const url = `${api.baseURL}${endpoint}?format=${format}`
      downloadFile(url, fileName)
      message.success('数据导出成功')
    }
    
    await fetchReportList()
  } catch (error) {
    console.error(`导出${dataType}数据失败:`, error)
    message.error('数据导出失败')
  } finally {
    exportLoading[dataType] = false
  }
}

// 下载报表文件
function downloadReport(record) {
  const url = `${api.baseURL}${record.downloadUrl}`
  downloadFile(url, record.fileName)
}

// 下载文件辅助函数
function downloadFile(url, fileName) {
  const link = document.createElement('a')
  link.href = url
  link.download = fileName
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 删除报表文件
async function deleteReport(record) {
  try {
    // 注意：这里需要在后端添加删除API
    message.success('删除功能将在后续版本实现')
  } catch (error) {
    console.error('删除报表失败:', error)
    message.error('删除报表失败')
  }
}

// 格式化文件大小
function formatFileSize(bytes) {
  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]
}

// 格式化日期
function formatDate(date) {
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}
</script>

<style scoped>
.reports-page {
  padding: 0;
}

.reports-content {
  padding: 24px;
  background: #f0f2f5;
  min-height: calc(100vh - 180px);
}

.ant-card {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
  border-radius: 8px;
}

.ant-page-header {
  background: #fff;
  padding: 16px 24px;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  color: #262626;
  font-weight: 500;
}

:deep(.ant-btn-group) .ant-btn {
  margin: 0;
}

.ant-col {
  margin-bottom: 16px;
}
</style>
