const api = require('../../utils/api')
const auth = require('../../utils/auth')

Page({
  data: {
    exchanges: [],
    loading: false
  },

  async onLoad() {
    // 统一登录验证
    const isValid = await auth.ensureLogin({
      pageName: 'gift-exchanges',
      redirectUrl: '/pages/gift-exchanges/gift-exchanges'
    })
    
    if (!isValid) return
    
    // 验证通过后，稍作延迟确保token稳定
    await new Promise(resolve => setTimeout(resolve, 50))
    
    // 加载数据
    this.loadExchanges()
  },

  onShow() {
    // 每次显示页面时刷新数据（已登录的情况下）
    const app = getApp()
    if (app.globalData.isLoggedIn) {
      this.loadExchanges()
    }
  },

  async loadExchanges() {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    try {
      const res = await api.gifts.getMyExchanges({ limit: 50 })
      if (res.success) {
        this.setData({
          exchanges: res.data
        })
      }
    } catch (error) {
      console.error('加载兑换记录失败:', error)
      // 401错误由API层统一处理，这里只处理其他错误
      if (error.code !== 401) {
        wx.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      }
    } finally {
      this.setData({ loading: false })
    }
  },

  // 查看物流
  viewTracking(e) {
    const trackingNumber = e.currentTarget.dataset.tracking
    if (!trackingNumber) {
      wx.showToast({
        title: '暂无物流信息',
        icon: 'none'
      })
      return
    }

    // 复制物流单号
    wx.setClipboardData({
      data: trackingNumber,
      success: () => {
        wx.showToast({
          title: '物流单号已复制',
          icon: 'success'
        })
      }
    })
  },

  // 格式化状态
  formatStatus(status) {
    const statusMap = {
      'pending': '待发货',
      'shipped': '已发货',
      'delivered': '已送达',
      'cancelled': '已取消'
    }
    return statusMap[status] || status
  },

  // 格式化时间
  formatTime(dateStr) {
    const date = new Date(dateStr)
    return date.toLocaleDateString('zh-CN', { 
      year: 'numeric',
      month: '2-digit', 
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadExchanges()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  }
})
