<template>
  <div class="orders-page">
    <div class="orders-container">
      <!-- 标题 -->
      <div class="section-title">
        <div class="title-bar"></div>
        <h2 class="title-text">订单管理</h2>
      </div>
      
      <!-- 订单统计 -->
     
      
      <!-- 骨架屏加载状态 -->
      <div v-if="loading" class="orders-table">
        <div class="table-skeleton">
          <div class="skeleton-header">
            <div v-for="i in 5" :key="`header-${i}`" class="skeleton-cell">
              <el-skeleton-item variant="text" style="width: 100%; height: 20px;" />
            </div>
          </div>
          <div v-for="i in 5" :key="`row-${i}`" class="skeleton-row">
            <div v-for="j in 5" :key="`cell-${i}-${j}`" class="skeleton-cell">
              <el-skeleton-item variant="text" style="width: 100%; height: 16px;" />
            </div>
          </div>
        </div>
      </div>
      
      <!-- 错误提示 -->
      <div v-if="error" class="error-message">
        <p>{{ error }}</p>
        <button @click="initData" class="retry-button">重试</button>
      </div>
      
      <!-- 订单列表 -->
      <div v-else-if="!loading && orders.length > 0" class="orders-table">
        <table class="orders-table-content">
          <thead>
            <tr>
              <th>订单编号</th>
              <th>类目</th>
              <th>金额</th>
              <th>购买时间</th>
              <!-- <th>流向</th> -->    
              <th>订单状态</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="order in orders" :key="order.id">
              <td class="order-no">{{ order.orderNo}}</td>
              <td class="plan-name">{{ order.planName }}</td>
              <td class="amount">{{ formatAmount(order.amount) }}</td>
              <td class="create-time">{{ formatDate(order.createTime) }}</td>
              <!-- <td class="direction">
                <span :class="getDirectionClass(order.amount)">
                  {{ getDirectionText(order.amount) }}
                </span>
              </td> -->
              <td class="status">
                <span :class="getStatusClass(order.status)">
                  {{ order.statusText }}
                </span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="!loading && orders.length === 0" class="empty-state">
       
        <p class="empty-text">暂无订单记录</p>
        <p class="empty-subtext">您还没有任何订单</p>
      </div>
      
      <!-- 分页组件 -->
      <div v-if="showPagination && !loading && orders.length > 0" class="pagination-container">
        <div class="pagination">
          <button 
            v-for="page in getPageNumbers()" 
            :key="page"
            class="page-button"
            :class="{ active: page === pagination.current, ellipsis: page === '...' }"
            @click="page !== '...' && handlePageChange(page)"
            :disabled="page === '...'"
          >
            {{ page }}
          </button>
          <button 
            v-if="pagination.current < pagination.pages"
            class="page-button next-button"
            @click="handlePageChange(pagination.current + 1)"
          >
            &gt;
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserOrders } from '../../api/user.js'

// 加载状态
const loading = ref(true)

// 订单数据
const orders = ref([])

// 统计数据
const stats = ref(null)

// 错误状态
const error = ref(null)

// 分页数据
const pagination = ref({
  current: 1,
  size: 10,
  total: 0,
  pages: 0
})

// 是否显示分页
const showPagination = computed(() => {
  return pagination.value.total > pagination.value.size
})

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true
    const response = await getUserOrders({
      page: pagination.value.current,
      size: pagination.value.size
    })
    if (response.success) {
      const records = response.records || []
      orders.value = records
      
      // 计算统计数据
      calculateStats(records)
      
      pagination.value.total = response.total || 0
      pagination.value.pages = Math.ceil(response.total / pagination.value.size)
    }
  } catch (err) {
    console.error('获取订单列表失败:', err)
    error.value = '获取订单列表失败'
  } finally {
    loading.value = false
  }
}

// 计算统计数据
const calculateStats = (orders) => {
  const totalOrders = orders.length
  const successOrders = orders.filter(order => order.status === 1).length
  const totalAmount = orders.reduce((sum, order) => sum + (order.amount || 0), 0)
  
  stats.value = {
    totalOrders,
    successOrders,
    totalAmount: totalAmount.toFixed(2)
  }
}

// 切换页码
const handlePageChange = async (page) => {
  pagination.value.current = page
  await fetchOrders()
}

// 生成页码数组
const getPageNumbers = () => {
  const pages = []
  const current = pagination.value.current
  const total = pagination.value.pages
  
  if (total <= 7) {
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    if (current <= 4) {
      for (let i = 1; i <= 7; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    } else if (current >= total - 3) {
      pages.push(1)
      pages.push('...')
      for (let i = total - 6; i <= total; i++) {
        pages.push(i)
      }
    } else {
      pages.push(1)
      pages.push('...')
      for (let i = current - 2; i <= current + 2; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    }
  }
  
  return pages
}

// 格式化订单编号（脱敏）
const maskOrderNo = (orderNo) => {
  if (!orderNo) return ''
  if (orderNo.length <= 8) {
    return orderNo.replace(/./g, 'X')
  }
  return orderNo.substring(0, 4) + 'X'.repeat(orderNo.length - 8) + orderNo.substring(orderNo.length - 4)
}

// 格式化金额
const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0.00元'
  return `${amount.toFixed(2)}元`
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '.')
}

// 获取流向文本
const getDirectionText = (amount) => {
//   return amount > 0 ? '收入' : '支出'
}

// 获取流向样式类
const getDirectionClass = (amount) => {
  return amount > 0 ? 'direction-income' : 'direction-expense'
}

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 1:
      return 'status-success'
    case 2:
      return 'status-failed'
    case 0:
      return 'status-pending'
    default:
      return 'status-unknown'
  }
}

// 初始化数据
const initData = async () => {
  await fetchOrders()
}

// 组件挂载时初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.orders-page {
  width: 100%;
  min-height: 800px;
  padding: 0;
  margin: 0;
  overflow: hidden;
  box-sizing: border-box;
}

.orders-container {
  width: 100%;
  box-sizing: border-box;
}

.section-title {
  width: 312px;
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 0;
  margin-bottom: 20px;
}

.title-bar {
  width: 4px;
  height: 24px;
  background: #333;
  border-radius: 2px;
}

.title-text {
  font-family: Arial, sans-serif;
  font-weight: 600;
  font-size: 24px;
  line-height: 28px;
  letter-spacing: 0px;
  color: #333;
  margin: 0;
  text-align: left;
}

.stats-section {
  margin-bottom: 30px;
}

.stats-card {
  display: flex;
  gap: 20px;
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.stats-item {
  flex: 1;
  text-align: center;
}

.stats-number {
  font-family: Arial, sans-serif;
  font-weight: 600;
  font-size: 32px;
  line-height: 36px;
  color: #333;
  margin-bottom: 8px;
}

.stats-label {
  font-family: Arial, sans-serif;
  font-weight: 400;
  font-size: 14px;
  line-height: 16px;
  color: #666;
}

.orders-table {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.orders-table-content {
  width: 100%;
  border-collapse: collapse;
  font-family: Arial, sans-serif;
}

.orders-table-content thead {
  background: #f8f9fa;
}

.orders-table-content th {
  padding: 16px 12px;
  text-align: left;
  font-weight: 500;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #e0e0e0;
}

.orders-table-content td {
  padding: 16px 12px;
  text-align: left;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #f0f0f0;
}

.orders-table-content tbody tr:hover {
  background: #f8f9fa;
}

.order-no {
  font-family: 'Courier New', monospace;
  font-weight: 500;
}

.plan-name {
  font-weight: 500;
}

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

.create-time {
  color: #666;
}

.direction-income {
  color: #52c41a;
  font-weight: 500;
}

.direction-expense {
  color: #ff4d4f;
  font-weight: 500;
}

.status-success {
  color: #52c41a;
  font-weight: 500;
}

.status-failed {
  color: #ff4d4f;
  font-weight: 500;
}

.status-pending {
  color: #faad14;
  font-weight: 500;
}

.status-unknown {
  color: #666;
  font-weight: 500;
}

/* 骨架屏样式 */
.table-skeleton {
  padding: 20px;
}

.skeleton-header {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
  gap: 12px;
  margin-bottom: 20px;
}

.skeleton-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
  gap: 12px;
  margin-bottom: 16px;
}

.skeleton-cell {
  height: 20px;
}

/* 错误提示样式 */
.error-message {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.error-message p {
  margin: 0 0 20px 0;
  font-size: 16px;
}

.retry-button {
  background: #333;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s ease;
}

.retry-button:hover {
  background: #555;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  margin: 0 0 8px 0;
}

.empty-subtext {
  font-size: 14px;
  margin: 0;
  color: #ccc;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  padding: 20px 0;
}

.pagination {
  display: flex;
  gap: 8px;
  align-items: center;
}

.page-button {
  min-width: 40px;
  height: 40px;
  border: 1px solid #e0e0e0;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 12px;
}

.page-button:hover:not(.ellipsis):not(:disabled) {
  background: #f5f5f5;
  border-color: #d0d0d0;
}

.page-button.active {
  background: #333;
  color: white;
  border-color: #333;
}

.page-button.ellipsis {
  cursor: default;
  background: white;
  border-color: #e0e0e0;
  color: #999;
}

.page-button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.next-button {
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .orders-table-content {
    font-size: 13px;
  }
  
  .orders-table-content th,
  .orders-table-content td {
    padding: 12px 8px;
  }
}

@media (max-width: 992px) {
  .orders-table {
    overflow-x: auto;
  }
  
  .orders-table-content {
    min-width: 700px; /* 确保表格有最小宽度，防止挤压 */
  }
}

@media (max-width: 768px) {
  
  .orders-table-content {
    font-size: 12px;
    min-width: 650px; /* 确保表格有最小宽度，防止挤压 */
  }
  
  .orders-table-content th,
  .orders-table-content td {
    padding: 8px 6px;
  }
  
  .stats-card {
    flex-direction: column;
    gap: 12px;
  }
  
  .stats-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .stats-number {
    font-size: 28px;
  }
  
  .table-skeleton {
    overflow-x: auto;
  }
  
  .skeleton-header,
  .skeleton-row {
    min-width: 650px;
  }
}

@media (max-width: 480px) {
  
  .orders-table-content {
    font-size: 11px;
    min-width: 500px; /* 确保表格有最小宽度，防止挤压 */
  }
  
  .orders-table-content th,
  .orders-table-content td {
    padding: 6px 4px;
    white-space: nowrap; /* 防止文本换行 */
  }
  
  .section-title {
    margin-top: 0;
    width: 100%; /* 标题宽度调整 */
  }
  
  .title-text {
    font-size: 18px;
  }
  
  .pagination {
    flex-wrap: wrap; /* 分页按钮在小屏幕上可以换行 */
    justify-content: center;
  }
}
</style> 