<template>
  <div class="exchange-records-page">
    <!-- 页面头部 -->
    <el-page-header @back="goBack" class="page-header">
      <template #title>
        返回
      </template>
      <template #content>
        <div class="header-content">
          <el-icon :size="24" style="margin-right: 8px;"><ShoppingBag /></el-icon>
          <span class="header-title">兑换记录</span>
        </div>
      </template>
    </el-page-header>

    <!-- 主要内容 -->
    <div class="records-container" v-loading="loading" element-loading-text="正在加载兑换记录...">
      <!-- 错误提示 -->
      <el-result
        v-if="errorMessage"
        status="error"
        title="加载失败"
        :sub-title="errorMessage"
      >
        <template #extra>
          <el-button type="primary" @click="loadExchangeRecords" :loading="loading">重新加载</el-button>
        </template>
      </el-result>

      <!-- 空状态 -->
      <el-empty v-else-if="records.length === 0 && !loading" description="暂无兑换记录">
        <el-button type="primary" @click="goToProfile">去兑换会员码</el-button>
      </el-empty>

      <!-- 兑换记录列表 -->
      <el-card v-else class="records-list-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>兑换记录 ({{ records.length }})</span>
            <el-button :icon="Refresh" circle @click="loadExchangeRecords" :loading="loading" />
          </div>
        </template>

        <div class="records-grid">
          <el-card 
            v-for="record in paginatedRecords" 
            :key="record.id"
            class="record-card"
            shadow="hover"
          >
            <template #header>
              <div class="record-card-header">
                <el-tag :type="getStatusClass(record.isUse)" effect="dark" size="large">
                  {{ getStatusText(record.isUse) }}
                </el-tag>
                <span class="record-date">{{ formatDate(record.exchangeTime) }}</span>
              </div>
            </template>
            <el-descriptions :column="1" border>
              <el-descriptions-item label-class-name="record-label" label="订单号">{{ record.orderNo || '-' }}</el-descriptions-item>
              <el-descriptions-item label-class-name="record-label" label="兑换类型">{{ getExchangeTypeText(record.type) }}</el-descriptions-item>
              <el-descriptions-item label-class-name="record-label" label="兑换模式">{{ getExchangeModeText(record.exchangeMode) }}</el-descriptions-item>
              <el-descriptions-item v-if="record.orderAmount" label-class-name="record-label" label="订单金额">
                <span class="amount-value">¥{{ record.orderAmount }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </div>

        <!-- 分页组件 -->
        <div v-if="totalPages > 1" class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="records.length"
            :page-size="pageSize"
            v-model:current-page="currentPage"
            @current-change="goToPage"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { lotteryApi } from '../api/index.js'
import { userStore } from '../store/user.js'
import {
  ElPageHeader,
  ElCard,
  ElButton,
  ElIcon,
  ElResult,
  ElEmpty,
  ElTag,
  ElDescriptions,
  ElDescriptionsItem,
  ElPagination
} from 'element-plus'
import { ShoppingBag, Refresh } from '@element-plus/icons-vue'

export default {
  name: 'ExchangeRecords',
  components: {
    ElPageHeader,
    ElCard,
    ElButton,
    ElIcon,
    ElResult,
    ElEmpty,
    ElTag,
    ElDescriptions,
    ElDescriptionsItem,
    ElPagination,
    ShoppingBag,
    Refresh
  },
  data() {
    return {
      loading: false,
      errorMessage: '',
      records: [],
      // 分页相关
      currentPage: 1,
      pageSize: 5
    }
  },

  computed: {
    // 总页数
    totalPages() {
      return Math.ceil(this.records.length / this.pageSize)
    },

    // 当前页的记录
    paginatedRecords() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.records.slice(start, end)
    }
  },

  async mounted() {
    await this.loadExchangeRecords()
  },
  methods: {
    // 加载兑换记录
    async loadExchangeRecords() {
      const userId = userStore.getUserId()
      
      if (!userId) {
        this.errorMessage = '请先登录'
        return
      }

      this.loading = true
      this.errorMessage = ''
      
      try {
        const response = await lotteryApi.getExchangeRecordsByUserId(userId)
        
        if (response && response.success) {
          this.records = response.data || []
          // 按兑换时间倒序排列
          this.records.sort((a, b) => new Date(b.exchangeTime) - new Date(a.exchangeTime))
        } else {
          this.errorMessage = response?.message || '获取兑换记录失败'
        }
      } catch (error) {
        console.error('获取兑换记录失败:', error)
        this.errorMessage = error?.response?.data?.message || '网络连接失败，请稍后重试'
      } finally {
        this.loading = false
      }
    },

    // 获取状态样式类
    getStatusClass(isUse) {
      switch (isUse) {
        case 1:
          return 'success'
        default:
          return 'info'
      }
    },

    // 获取状态文本
    getStatusText(isUse) {
      switch (isUse) {
        case 1:
          return '成功'
        default:
          return '未知'
      }
    },

    // 获取兑换类型文本
    getExchangeTypeText(type) {
      switch (type) {
        case '月度会员':
          return '月度会员'
        case '年度会员':
          return '年度会员'
        default:
          return type || '未知类型'
      }
    },

    // 获取兑换模式文本
    getExchangeModeText(mode) {
      switch (mode) {
        case 1:
          return '兑换码兑换'
        case 2:
          return '在线支付'
        default:
          return mode || '未知模式'
      }
    },

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

    // 跳转到个人中心
    goToProfile() {
      this.$router.push('/profile')
    },

    // 返回上一页
    goBack() {
      this.$router.go(-1)
    },

    // 跳转到指定页
    goToPage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page
      }
    }
  }
}
</script>

<style scoped>
.exchange-records-page {
  background-color: #f0f2f5;
  padding: 20px;
  min-height: calc(100vh - 70px);
}

.page-header {
  background: linear-gradient(135deg, #3a7bd5, #00d2ff);
  padding: 30px 24px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

:deep(.el-page-header__back .el-icon),
:deep(.el-page-header__back .el-page-header__title) {
  color: white;
}

:deep(.el-divider) {
  border-color: rgba(255, 255, 255, 0.5);
}

.header-content {
  display: flex;
  align-items: center;
  color: white;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
}

.records-container {
  max-width: 1200px;
  margin: 0 auto;
}

.records-list-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.records-grid {
  display: grid;
  gap: 16px;
}

.record-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-date {
  font-size: 14px;
  color: #909399;
}

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

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

:deep(.record-label) {
  width: 100px;
  font-weight: 600;
  color: #606266;
}
</style> 