<template>
  <div class="dashboard">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>仪表盘</h1>
      <p>欢迎使用银行管理后台系统</p>
    </div>
    
    <!-- 统计卡片 -->
    <a-row :gutter="[16, 16]" class="stats-cards">
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stat-card">
          <a-statistic
            title="总用户数"
            :value="stats.totalUsers"
            :loading="loading"
          >
            <template #prefix>
              <user-outlined style="color: #1890ff" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stat-card">
          <a-statistic
            title="总账户数"
            :value="stats.totalAccounts"
            :loading="loading"
          >
            <template #prefix>
              <bank-outlined style="color: #52c41a" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stat-card">
          <a-statistic
            title="今日交易数"
            :value="stats.todayTransactions"
            :loading="loading"
          >
            <template #prefix>
              <transaction-outlined style="color: #fa8c16" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stat-card">
          <a-statistic
            title="总资产"
            :value="stats.totalAssets"
            :precision="2"
            :loading="loading"
            suffix="元"
          >
            <template #prefix>
              <dollar-outlined style="color: #f5222d" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>
    
    <!-- 图表区域 -->
    <a-row :gutter="[16, 16]" class="charts-section">
      <a-col :xs="24" :lg="12">
        <a-card title="交易趋势" class="chart-card">
          <div ref="transactionChartRef" class="chart-container"></div>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :lg="12">
        <a-card title="账户类型分布" class="chart-card">
          <div ref="accountTypeChartRef" class="chart-container"></div>
        </a-card>
      </a-col>
    </a-row>
    
    <!-- 最近交易 -->
    <a-row :gutter="[16, 16]" class="recent-section">
      <a-col :xs="24" :lg="16">
        <a-card title="最近交易" class="recent-card">
          <a-table
            :columns="transactionColumns"
            :data-source="recentTransactions"
            :loading="loading"
            :pagination="false"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'amount'">
                <span :class="getAmountClass(record.transaction_type)">
                  {{ formatAmount(record.amount) }}
                </span>
              </template>
              <template v-else-if="column.key === 'type'">
                <a-tag :color="getTypeColor(record.transaction_type)">
                  {{ getTypeName(record.transaction_type) }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'status'">
                <a-tag :color="getStatusColor(record.status)">
                  {{ getStatusName(record.status) }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :lg="8">
        <a-card title="系统信息" class="system-card">
          <a-descriptions :column="1" size="small">
            <a-descriptions-item label="系统版本">
              v1.0.0
            </a-descriptions-item>
            <a-descriptions-item label="运行时间">
              {{ systemInfo.uptime }}
            </a-descriptions-item>
            <a-descriptions-item label="数据库状态">
              <a-tag color="green">正常</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="最后更新">
              {{ systemInfo.lastUpdate }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'
import * as echarts from 'echarts'
import { 
  UserOutlined, 
  BankOutlined, 
  TransactionOutlined, 
  DollarOutlined 
} from '@ant-design/icons-vue'
import { api } from '@/utils/api'

// 响应式数据
const loading = ref(false)
const stats = ref({
  totalUsers: 0,
  totalAccounts: 0,
  todayTransactions: 0,
  totalAssets: 0
})

const recentTransactions = ref([])
const systemInfo = ref({
  uptime: '0天0小时',
  lastUpdate: new Date().toLocaleString()
})

// 图表引用
const transactionChartRef = ref()
const accountTypeChartRef = ref()
let transactionChart = null
let accountTypeChart = null

// 交易表格列配置
const transactionColumns = [
  {
    title: '交易号',
    dataIndex: 'transaction_number',
    key: 'transaction_number',
    width: 120,
    ellipsis: true
  },
  {
    title: '类型',
    dataIndex: 'transaction_type',
    key: 'type',
    width: 80
  },
  {
    title: '金额',
    dataIndex: 'amount',
    key: 'amount',
    width: 100,
    align: 'right'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80
  },
  {
    title: '时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 120
  }
]

// 获取统计数据
const fetchStats = async () => {
  try {
    loading.value = true
    
    // 获取仪表盘统计数据
    const statsResult = await api.dashboard.getStats()
    if (statsResult.success) {
      const data = statsResult.data
      stats.value = {
        totalUsers: data.overview?.totalUsers || 0,
        totalAccounts: data.overview?.totalAccounts || 0,
        todayTransactions: data.today?.transactionCount || 0,
        totalAssets: data.overview?.totalBalance || 0
      }
    }
    
    // 获取最近交易
    const transactionResult = await api.dashboard.getRecentTransactions({
      limit: 10
    })
    
    if (transactionResult.success) {
      recentTransactions.value = transactionResult.data || []
    }
    
  } catch (error) {
    console.error('获取统计数据失败:', error)
    message.error('获取统计数据失败')
    
    // 如果API调用失败，使用模拟数据
    stats.value = {
      totalUsers: 1250,
      totalAccounts: 3420,
      todayTransactions: 156,
      totalAssets: 12500000.50
    }
  } finally {
    loading.value = false
  }
}

// 初始化交易趋势图表
const initTransactionChart = () => {
  if (!transactionChartRef.value) return
  
  transactionChart = echarts.init(transactionChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['存款', '取款', '转账']
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '存款',
        type: 'line',
        data: [120, 132, 101, 134, 90, 230, 210],
        smooth: true
      },
      {
        name: '取款',
        type: 'line',
        data: [220, 182, 191, 234, 290, 330, 310],
        smooth: true
      },
      {
        name: '转账',
        type: 'line',
        data: [150, 232, 201, 154, 190, 330, 410],
        smooth: true
      }
    ]
  }
  
  transactionChart.setOption(option)
}

// 初始化账户类型分布图表
const initAccountTypeChart = () => {
  if (!accountTypeChartRef.value) return
  
  accountTypeChart = echarts.init(accountTypeChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '账户类型',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 1048, name: '储蓄账户' },
          { value: 735, name: '支票账户' },
          { value: 580, name: '信用卡账户' },
          { value: 484, name: '贷款账户' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  accountTypeChart.setOption(option)
}

// 格式化金额
const formatAmount = (amount) => {
  return (amount / 100).toFixed(2)
}

// 获取金额样式类
const getAmountClass = (type) => {
  if (type === 'deposit' || type === 'transfer_in') {
    return 'amount-positive'
  } else if (type === 'withdrawal' || type === 'transfer_out') {
    return 'amount-negative'
  }
  return 'amount-zero'
}

// 获取类型名称
const getTypeName = (type) => {
  const typeMap = {
    'deposit': '存款',
    'withdrawal': '取款',
    'transfer_in': '转入',
    'transfer_out': '转出',
    'interest': '利息',
    'fee': '手续费'
  }
  return typeMap[type] || type
}

// 获取类型颜色
const getTypeColor = (type) => {
  const colorMap = {
    'deposit': 'green',
    'withdrawal': 'red',
    'transfer_in': 'blue',
    'transfer_out': 'orange',
    'interest': 'purple',
    'fee': 'gray'
  }
  return colorMap[type] || 'default'
}

// 获取状态名称
const getStatusName = (status) => {
  const statusMap = {
    'pending': '处理中',
    'completed': '已完成',
    'failed': '失败',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    'pending': 'processing',
    'completed': 'success',
    'failed': 'error',
    'cancelled': 'default'
  }
  return colorMap[status] || 'default'
}

// 处理窗口大小变化
const handleResize = () => {
  if (transactionChart) {
    transactionChart.resize()
  }
  if (accountTypeChart) {
    accountTypeChart.resize()
  }
}

onMounted(() => {
  fetchStats()
  
  // 延迟初始化图表，确保DOM已渲染
  setTimeout(() => {
    initTransactionChart()
    initAccountTypeChart()
  }, 100)
  
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (transactionChart) {
    transactionChart.dispose()
  }
  if (accountTypeChart) {
    accountTypeChart.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

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

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

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

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.stat-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.charts-section {
  margin-bottom: 24px;
}

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

.chart-container {
  height: 300px;
  width: 100%;
}

.recent-section {
  margin-bottom: 24px;
}

.recent-card,
.system-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.amount-positive {
  color: #52c41a;
  font-weight: 600;
}

.amount-negative {
  color: #ff4d4f;
  font-weight: 600;
}

.amount-zero {
  color: #8c8c8c;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-cards .ant-col {
    margin-bottom: 16px;
  }
  
  .charts-section .ant-col {
    margin-bottom: 16px;
  }
  
  .recent-section .ant-col {
    margin-bottom: 16px;
  }
  
  .chart-container {
    height: 250px;
  }
}
</style>