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

Page({
  data: {
    statusBarHeight: 44,
    navBarHeight: 44,
    totalNavHeight: 88,
    lovePoints: 0,
    gifts: [],
    giftsLoading: false,
    giftsError: '',
    skeletonGifts: Array.from({ length: 6 }).map((_, idx) => ({ id: idx + 1 }))
  },

  getGiftImageUrl(url) {
    if (!url) return ''
    if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('data:')) return url
    // 兼容所有相对路径
    if (url.startsWith('/')) {
      const baseUrl = String(config.API_BASE_URL || '').replace(/\/api$/, '')
      return baseUrl + url
    }
    return url
  },

  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
    })

    this.loadGifts()

    const isValid = await auth.ensureLogin({
      pageName: 'gift-shop',
      redirectUrl: '/pages/gift-shop/gift-shop'
    })

    if (!isValid) return

    await new Promise(resolve => setTimeout(resolve, 50))
    this.loadLovePoints()
  },

  onShow() {
    const app = getApp()
    if (app.globalData.isLoggedIn) {
      this.loadLovePoints()
    }
  },

  // 加载爱心值
  async loadLovePoints() {
    try {
      const res = await api.loveExchange.getOptions()
      if (res.success) {
        this.setData({
          lovePoints: res.data.current_love_points || 0
        })
      }
    } catch (error) {
      console.error('加载爱心值失败:', error)
    }
  },

  async loadGifts() {
    if (this.data.giftsLoading) return

    this.setData({
      giftsLoading: true,
      giftsError: ''
    })

    try {
      // 使用 shop.getItems 获取 exchange_items 数据
      const res = await api.shop.getItems()
      if (res.success) {
        const gifts = (res.data || []).map(gift => ({
          id: gift.id,
          name: gift.name,
          // 兼容后端返回 image 或 image_url
          image: this.getGiftImageUrl(gift.image_url || gift.image),
          // 兼容后端返回 price 或 love_cost
          love_cost: gift.price || gift.love_cost,
          stock: gift.stock,
          sold_count: gift.sold_count,
          category: gift.category
        }))
        this.setData({ gifts })
      } else {
        this.setData({ giftsError: res.error || '获取礼品失败' })
      }
    } catch (error) {
      console.error('加载礼品失败:', error)
      this.setData({ giftsError: error.message || '获取礼品失败' })
    } finally {
      this.setData({ giftsLoading: false })
    }
  },

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

  // 查看明细
  onViewDetails() {
    wx.navigateTo({
      url: '/pages/love-transactions/love-transactions'
    })
  },

  // 点击礼品卡片
  onGiftTap(e) {
    wx.showModal({
      title: '提示',
      content: '请联系在线客服',
      showCancel: false,
      confirmText: '知道了'
    })
  },

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