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

Page({
  data: {
    statusBarHeight: 44,
    navBarHeight: 44,
    totalNavHeight: 88,
    transactions: [],
    balance: 0,
    loading: false
  },

  async onLoad() {
    // 计算导航栏高度
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 44
    const menuButton = wx.getMenuButtonBoundingClientRect()
    const navBarHeight = menuButton.height + (menuButton.top - statusBarHeight) * 2
    const totalNavHeight = statusBarHeight + navBarHeight
    
    this.setData({
      statusBarHeight,
      navBarHeight,
      totalNavHeight
    })

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

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

  async loadBalance() {
    try {
      const res = await api.loveExchange.getOptions()
      if (res.success) {
        this.setData({
          balance: res.data.current_love_points || 0
        })
      }
    } catch (error) {
      console.error('加载余额失败:', error)
      // 401错误由API层统一处理
    }
  },

  async loadTransactions() {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    try {
      const res = await api.lovePoints.getTransactions({ limit: 100 })
      if (res.success) {
        this.setData({
          transactions: 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 })
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack()
  },

  // 格式化来源
  formatSource(source) {
    const sourceMap = {
      'share': '分享小程序',
      'invite': '邀请好友',
      'profile': '完善资料',
      'exchange_vip': '兑换会员',
      'exchange_gift': '兑换礼品',
      'admin': '管理员操作',
      'system': '系统赠送'
    }
    return sourceMap[source] || source
  },

  // 格式化时间
  formatTime(dateStr) {
    const date = new Date(dateStr)
    const now = new Date()
    const diff = now - date
    
    // 今天
    if (diff < 86400000 && date.getDate() === now.getDate()) {
      return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    }
    
    // 昨天
    const yesterday = new Date(now)
    yesterday.setDate(yesterday.getDate() - 1)
    if (date.getDate() === yesterday.getDate()) {
      return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    }
    
    // 其他日期
    return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' }) + ' ' + 
           date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  },

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