<template>
  <view class="history-container">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <view class="nav-content">
        <view class="nav-left" @click="goBack">
          <text class="nav-icon">‹</text>
        </view>
        <view class="nav-title">充值记录</view>
        <view class="nav-right"></view>
      </view>
    </view>

    <!-- 筛选条件 -->
    <view class="filter-section">
      <view class="filter-tabs">
        <view 
          v-for="(tab, index) in filterTabs" 
          :key="index"
          class="filter-tab"
          :class="{ active: currentFilter === tab.value }"
          @click="selectFilter(tab.value)"
        >
          {{ tab.label }}
        </view>
      </view>
    </view>

    <!-- 记录列表 -->
    <view class="record-list">
      <view v-if="isLoading && recordList.length === 0" class="loading-state">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>
      
      <view v-else-if="recordList.length === 0" class="empty-state">
        <view class="empty-icon">📝</view>
        <text class="empty-text">暂无充值记录</text>
        <button class="recharge-btn" @click="goToRecharge">立即充值</button>
      </view>
      
      <view v-else>
        <view 
          v-for="(record, index) in recordList" 
          :key="index"
          class="record-item"
        >
          <view class="record-header">
            <view class="record-amount">
              <text class="amount-symbol">+</text>
              <text class="amount-value">¥{{ record.amount }}</text>
            </view>
            <view class="record-status" :class="record.status">
              {{ getStatusText(record.status) }}
            </view>
          </view>
          
          <view class="record-details">
            <view class="detail-item">
              <text class="detail-label">订单号：</text>
              <text class="detail-value">{{ record.orderId }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">支付方式：</text>
              <text class="detail-value">{{ getPaymentMethodText(record.paymentMethod) }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">充值时间：</text>
              <text class="detail-value">{{ formatTime(record.createTime) }}</text>
            </view>
            <view class="detail-item" v-if="record.bonusAmount > 0">
              <text class="detail-label">赠送金额：</text>
              <text class="detail-value bonus">+¥{{ record.bonusAmount }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore && !isLoading" class="load-more" @click="loadMore">
      <text class="load-more-text">加载更多</text>
    </view>
    
    <view v-if="isLoading && recordList.length > 0" class="loading-more">
      <view class="loading-spinner small"></view>
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script>
import { rechargeAPI } from '@/utils/api.js'

export default {
  name: 'RechargeHistoryPage',
  data() {
    return {
      recordList: [], // 充值记录列表
      currentFilter: 'all', // 当前筛选条件
      isLoading: false, // 是否正在加载
      hasMore: true, // 是否还有更多数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      
      // 筛选选项
      filterTabs: [
        { label: '全部', value: 'all' },
        { label: '成功', value: 'success' },
        { label: '失败', value: 'failed' },
        { label: '处理中', value: 'pending' }
      ]
    }
  },
  
  onLoad() {
    this.loadRecordList()
  },
  
  onPullDownRefresh() {
    this.refreshData()
  },
  
  onReachBottom() {
    if (this.hasMore && !this.isLoading) {
      this.loadMore()
    }
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 跳转到充值页面
    goToRecharge() {
      uni.navigateTo({
        url: '/pages/recharge/recharge'
      })
    },
    
    // 选择筛选条件
    selectFilter(filter) {
      if (this.currentFilter === filter) return
      
      this.currentFilter = filter
      this.refreshData()
    },
    
    // 刷新数据
    async refreshData() {
      this.currentPage = 1
      this.hasMore = true
      this.recordList = []
      await this.loadRecordList()
      
      // 停止下拉刷新
      uni.stopPullDownRefresh()
    },
    
    // 加载更多
    async loadMore() {
      if (!this.hasMore || this.isLoading) return
      
      this.currentPage++
      await this.loadRecordList()
    },
    
    // 加载充值记录列表
    async loadRecordList() {
      if (this.isLoading) return
      
      this.isLoading = true
      
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize
        }
        
        // 添加状态筛选
        if (this.currentFilter !== 'all') {
          params.status = this.currentFilter
        }
        
        const result = await rechargeAPI.getRechargeHistory(params)
        
        if (result.success) {
          const newRecords = result.data.records || []
          
          if (this.currentPage === 1) {
            this.recordList = newRecords
          } else {
            this.recordList = [...this.recordList, ...newRecords]
          }
          
          // 判断是否还有更多数据
          this.hasMore = newRecords.length === this.pageSize
        } else {
          uni.showToast({
            title: result.error?.message || '加载失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载充值记录失败:', error)
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'success': '充值成功',
        'failed': '充值失败',
        'pending': '处理中',
        'cancelled': '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    
    // 获取支付方式文本
    getPaymentMethodText(method) {
      const methodMap = {
        'wechat': '微信支付',
        'alipay': '支付宝',
        'bank': '银行卡'
      }
      return methodMap[method] || '未知方式'
    },
    
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return ''
      
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      // 小于1分钟
      if (diff < 60000) {
        return '刚刚'
      }
      
      // 小于1小时
      if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前'
      }
      
      // 小于1天
      if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前'
      }
      
      // 超过1天，显示具体日期
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      const minute = String(date.getMinutes()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hour}:${minute}`
    }
  }
}
</script>

<style lang="scss" scoped>
.history-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

// 导航栏
.nav-bar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-top: var(--status-bar-height);
  
  .nav-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 88rpx;
    padding: 0 30rpx;
    
    .nav-left {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .nav-icon {
        font-size: 40rpx;
        color: #fff;
        font-weight: bold;
      }
    }
    
    .nav-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #fff;
    }
    
    .nav-right {
      width: 60rpx;
    }
  }
}

// 筛选条件
.filter-section {
  background: #fff;
  padding: 30rpx;
  border-bottom: 1rpx solid #e5e5e5;
  
  .filter-tabs {
    display: flex;
    gap: 20rpx;
    
    .filter-tab {
      padding: 16rpx 32rpx;
      background: #f5f5f5;
      border-radius: 40rpx;
      font-size: 28rpx;
      color: #666;
      transition: all 0.3s ease;
      
      &.active {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #fff;
      }
    }
  }
}

// 记录列表
.record-list {
  padding: 30rpx;
  
  .loading-state,
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    
    .loading-spinner {
      width: 60rpx;
      height: 60rpx;
      border: 4rpx solid #e5e5e5;
      border-top: 4rpx solid #667eea;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 20rpx;
    }
    
    .loading-text {
      font-size: 28rpx;
      color: #999;
    }
  }
  
  .empty-state {
    .empty-icon {
      font-size: 120rpx;
      margin-bottom: 30rpx;
    }
    
    .empty-text {
      font-size: 32rpx;
      color: #999;
      margin-bottom: 40rpx;
    }
    
    .recharge-btn {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #fff;
      border: none;
      border-radius: 40rpx;
      padding: 20rpx 40rpx;
      font-size: 28rpx;
    }
  }
  
  .record-item {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .record-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      
      .record-amount {
        display: flex;
        align-items: baseline;
        
        .amount-symbol {
          font-size: 32rpx;
          color: #07c160;
          font-weight: bold;
          margin-right: 4rpx;
        }
        
        .amount-value {
          font-size: 40rpx;
          color: #07c160;
          font-weight: bold;
        }
      }
      
      .record-status {
        padding: 8rpx 16rpx;
        border-radius: 20rpx;
        font-size: 24rpx;
        
        &.success {
          background: #e8f5e8;
          color: #07c160;
        }
        
        &.failed {
          background: #ffe8e8;
          color: #ff4757;
        }
        
        &.pending {
          background: #fff3cd;
          color: #ffc107;
        }
      }
    }
    
    .record-details {
      .detail-item {
        display: flex;
        margin-bottom: 12rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .detail-label {
          font-size: 26rpx;
          color: #999;
          width: 140rpx;
          flex-shrink: 0;
        }
        
        .detail-value {
          font-size: 26rpx;
          color: #333;
          flex: 1;
          
          &.bonus {
            color: #ff6b6b;
          }
        }
      }
    }
  }
}

// 加载更多
.load-more {
  text-align: center;
  padding: 30rpx;
  
  .load-more-text {
    font-size: 28rpx;
    color: #667eea;
  }
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx;
  
  .loading-spinner {
    width: 40rpx;
    height: 40rpx;
    border: 3rpx solid #e5e5e5;
    border-top: 3rpx solid #667eea;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-right: 20rpx;
    
    &.small {
      width: 30rpx;
      height: 30rpx;
      border-width: 2rpx;
    }
  }
  
  .loading-text {
    font-size: 26rpx;
    color: #999;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
