<template>
  <div class="reports-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>报表统计</h1>
      <p>查看和导出银行业务报表</p>
    </div>

    <!-- 报表生成区域 -->
    <div class="report-generator">
      <a-card title="生成报表" class="generator-card">
        <a-form
          :model="reportForm"
          :rules="reportRules"
          @finish="handleGenerateReport"
          layout="vertical"
        >
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item label="报表类型" name="reportType">
                <a-select
                  v-model:value="reportForm.reportType"
                  placeholder="选择报表类型"
                  @change="handleReportTypeChange"
                >
                  <a-select-option value="transaction">交易报表</a-select-option>
                  <a-select-option value="account">账户报表</a-select-option>
                  <a-select-option value="user">用户报表</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            
            <a-col :span="8">
              <a-form-item label="日期范围" name="dateRange">
                <a-range-picker
                  v-model:value="reportForm.dateRange"
                  style="width: 100%"
                  :placeholder="['开始日期', '结束日期']"
                />
              </a-form-item>
            </a-col>
            
            <a-col :span="8">
              <a-form-item label="交易类型" name="transactionType" v-if="reportForm.reportType === 'transaction'">
                <a-select
                  v-model:value="reportForm.transactionType"
                  placeholder="选择交易类型"
                  allow-clear
                >
                  <a-select-option value="deposit">存款</a-select-option>
                  <a-select-option value="withdrawal">取款</a-select-option>
                  <a-select-option value="transfer">转账</a-select-option>
                  <a-select-option value="payment">支付</a-select-option>
                  <a-select-option value="interest">利息</a-select-option>
                  <a-select-option value="fee">手续费</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item label="报表格式" name="format">
                <a-radio-group v-model:value="reportForm.format">
                  <a-radio value="excel">Excel</a-radio>
                  <a-radio value="pdf">PDF</a-radio>
                  <a-radio value="csv">CSV</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            
            <a-col :span="16">
              <a-form-item>
                <a-space>
                  <a-button 
                    type="primary" 
                    html-type="submit"
                    :loading="generating"
                    icon="file-text"
                  >
                    生成报表
                  </a-button>
                  <a-button @click="handleReset">
                    重置
                  </a-button>
                </a-space>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
    </div>

    <!-- 最近生成的报表 -->
    <div class="report-history">
      <a-card title="最近生成的报表" class="history-card">
        <template #extra>
          <a-button @click="handleRefreshHistory">
            <ReloadOutlined />
            刷新
          </a-button>
        </template>
        
        <a-table
          :columns="historyColumns"
          :data-source="reportHistory"
          :loading="historyLoading"
          :pagination="historyPagination"
          @change="handleHistoryTableChange"
          row-key="id"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'type'">
              <a-tag :color="getReportTypeColor(record.type)">
                {{ getReportTypeText(record.type) }}
              </a-tag>
            </template>
            
            <template v-else-if="column.key === 'format'">
              <a-tag :color="getFormatColor(record.format)">
                {{ record.format.toUpperCase() }}
              </a-tag>
            </template>
            
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button 
                  type="link" 
                  size="small" 
                  @click="handleDownload(record)"
                  :disabled="record.status !== 'completed'"
                >
                  <DownloadOutlined />
                  下载
                </a-button>
                <a-button 
                  type="link" 
                  size="small" 
                  @click="handlePreview(record)"
                  :disabled="record.status !== 'completed'"
                >
                  <EyeOutlined />
                  查看
                </a-button>
                <a-button 
                  type="link" 
                  size="small" 
                  danger
                  @click="handleDelete(record)"
                >
                  <DeleteOutlined />
                  删除
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 报表预览模态框 -->
    <a-modal
      v-model:open="previewModalVisible"
      title="报表预览"
      width="90%"
      :footer="null"
    >
      <div v-if="previewData" class="report-preview">
        <div class="preview-header">
          <h3>{{ previewData.name }}</h3>
          <p>生成时间: {{ previewData.createdAt }}</p>
        </div>
        <div class="preview-content">
          <a-table
            :columns="previewColumns"
            :data-source="previewData.data"
            :pagination="false"
            size="small"
          />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { 
  ReloadOutlined, 
  DownloadOutlined, 
  EyeOutlined, 
  DeleteOutlined 
} from '@ant-design/icons-vue'
import { api } from '@/utils/api'

// 响应式数据
const generating = ref(false)
const historyLoading = ref(false)
const previewModalVisible = ref(false)
const previewData = ref(null)

// 报表表单
const reportForm = reactive({
  reportType: 'transaction',
  dateRange: null,
  transactionType: undefined,
  format: 'excel'
})

// 表单验证规则
const reportRules = {
  reportType: [
    { required: true, message: '请选择报表类型', trigger: 'change' }
  ],
  dateRange: [
    { required: true, message: '请选择日期范围', trigger: 'change' }
  ],
  format: [
    { required: true, message: '请选择报表格式', trigger: 'change' }
  ]
}

// 分页配置
const historyPagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 历史记录表格列
const historyColumns = [
  {
    title: '报表名称',
    dataIndex: 'name',
    key: 'name',
    width: 200
  },
  {
    title: '报表类型',
    dataIndex: 'type',
    key: 'type',
    width: 120
  },
  {
    title: '格式',
    dataIndex: 'format',
    key: 'format',
    width: 80
  },
  {
    title: '生成时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 150
  },
  {
    title: '生成人',
    dataIndex: 'createdBy',
    key: 'createdBy',
    width: 120
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 预览表格列
const previewColumns = [
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date'
  },
  {
    title: '交易类型',
    dataIndex: 'type',
    key: 'type'
  },
  {
    title: '金额',
    dataIndex: 'amount',
    key: 'amount'
  },
  {
    title: '账户',
    dataIndex: 'account',
    key: 'account'
  }
]

// 报表历史记录
const reportHistory = ref([
  {
    id: 1,
    name: '2023年9月交易报表',
    type: 'transaction',
    format: 'excel',
    createdAt: '2023-09-17 10:30:25',
    createdBy: '张三 (管理员)',
    status: 'completed',
    filePath: '/reports/transaction_202309.xlsx'
  },
  {
    id: 2,
    name: '储蓄账户余额报表',
    type: 'account',
    format: 'pdf',
    createdAt: '2023-09-16 15:45:12',
    createdBy: '李四 (经理)',
    status: 'completed',
    filePath: '/reports/account_balance_20230916.pdf'
  },
  {
    id: 3,
    name: '用户活跃度报表',
    type: 'user',
    format: 'csv',
    createdAt: '2023-09-15 09:20:45',
    createdBy: '张三 (管理员)',
    status: 'completed',
    filePath: '/reports/user_activity_20230915.csv'
  },
  {
    id: 4,
    name: '信用卡交易报表',
    type: 'transaction',
    format: 'excel',
    createdAt: '2023-09-14 14:10:33',
    createdBy: '王五 (柜员)',
    status: 'completed',
    filePath: '/reports/credit_transaction_20230914.xlsx'
  },
  {
    id: 5,
    name: '新用户注册报表',
    type: 'user',
    format: 'pdf',
    createdAt: '2023-09-13 11:05:22',
    createdBy: '李四 (经理)',
    status: 'completed',
    filePath: '/reports/new_users_20230913.pdf'
  }
])

// 计算属性
const filteredHistory = computed(() => {
  return reportHistory.value
})

// 方法
const handleReportTypeChange = (value) => {
  if (value !== 'transaction') {
    reportForm.transactionType = undefined
  }
}

const handleGenerateReport = async () => {
  try {
    generating.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 生成新的报表记录
    const newReport = {
      id: Date.now(),
      name: `${reportForm.reportType === 'transaction' ? '交易' : reportForm.reportType === 'account' ? '账户' : '用户'}报表_${new Date().toISOString().split('T')[0]}`,
      type: reportForm.reportType,
      format: reportForm.format,
      createdAt: new Date().toLocaleString('zh-CN'),
      createdBy: '当前用户',
      status: 'completed',
      filePath: `/reports/${reportForm.reportType}_${Date.now()}.${reportForm.format}`
    }
    
    reportHistory.value.unshift(newReport)
    historyPagination.value.total += 1
    
    message.success('报表生成成功！')
    handleReset()
    
  } catch (error) {
    console.error('生成报表失败:', error)
    message.error('生成报表失败，请重试')
  } finally {
    generating.value = false
  }
}

const handleReset = () => {
  reportForm.reportType = 'transaction'
  reportForm.dateRange = null
  reportForm.transactionType = undefined
  reportForm.format = 'excel'
}

const handleRefreshHistory = async () => {
  try {
    historyLoading.value = true
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    message.success('刷新成功')
  } catch (error) {
    message.error('刷新失败')
  } finally {
    historyLoading.value = false
  }
}

const handleHistoryTableChange = (pagination) => {
  historyPagination.value = pagination
}

const handleDownload = (record) => {
  // 模拟下载
  const link = document.createElement('a')
  link.href = record.filePath
  link.download = record.name
  link.click()
  message.success('开始下载报表')
}

const handlePreview = (record) => {
  // 模拟预览数据
  previewData.value = {
    name: record.name,
    createdAt: record.createdAt,
    data: [
      { date: '2023-09-17', type: '存款', amount: '¥10,000.00', account: '6225123456789001' },
      { date: '2023-09-17', type: '取款', amount: '¥5,000.00', account: '6225123456789002' },
      { date: '2023-09-17', type: '转账', amount: '¥2,000.00', account: '6225123456789001' }
    ]
  }
  previewModalVisible.value = true
}

const handleDelete = (record) => {
  const index = reportHistory.value.findIndex(item => item.id === record.id)
  if (index > -1) {
    reportHistory.value.splice(index, 1)
    historyPagination.value.total -= 1
    message.success('删除成功')
  }
}

// 工具方法
const getReportTypeColor = (type) => {
  const colors = {
    transaction: 'blue',
    account: 'green',
    user: 'orange'
  }
  return colors[type] || 'default'
}

const getReportTypeText = (type) => {
  const texts = {
    transaction: '交易报表',
    account: '账户报表',
    user: '用户报表'
  }
  return texts[type] || type
}

const getFormatColor = (format) => {
  const colors = {
    excel: 'green',
    pdf: 'red',
    csv: 'blue'
  }
  return colors[format] || 'default'
}

const getStatusColor = (status) => {
  const colors = {
    completed: 'green',
    processing: 'blue',
    failed: 'red'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    completed: '已完成',
    processing: '生成中',
    failed: '失败'
  }
  return texts[status] || status
}

// 生命周期
onMounted(() => {
  historyPagination.value.total = reportHistory.value.length
})
</script>

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

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.report-generator {
  margin-bottom: 24px;
}

.generator-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.history-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.report-preview {
  max-height: 70vh;
  overflow-y: auto;
}

.preview-header {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-header h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
}

.preview-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.preview-content {
  overflow-x: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .reports-page {
    padding: 12px;
  }
  
  .page-header h1 {
    font-size: 20px;
  }
  
  .generator-card,
  .history-card {
    margin-bottom: 16px;
  }
}
</style>