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

Page({
  data: {
    giftId: '',
    gift: null,
    userLovePoints: 0,
    loading: false
  },

  getGiftImageUrl(url) {
    if (!url) return ''
    if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('data:')) return url
    if (url.startsWith('/images/gifts/')) {
      const baseUrl = String(config.API_BASE_URL || '').replace(/\/api$/, '')
      return baseUrl + url
    }
    return url
  },

  async onLoad(options) {
    if (!options.id) {
      wx.showToast({ title: '礼物ID缺失', icon: 'none' })
      setTimeout(() => wx.navigateBack(), 1500)
      return
    }
    
    this.setData({ giftId: options.id })
    
    // 统一登录验证
    const isValid = await auth.ensureLogin({
      pageName: 'gift-detail',
      redirectUrl: `/pages/gift-detail/gift-detail?id=${options.id}`
    })
    
    if (!isValid) return
    
    // 验证通过后，稍作延迟确保token稳定
    await new Promise(resolve => setTimeout(resolve, 50))
    
    // 加载数据
    this.loadGiftDetail()
    this.loadUserLovePoints()
  },

  async loadGiftDetail() {
    this.setData({ loading: true })
    
    try {
      const res = await api.gifts.getDetail(this.data.giftId)
      if (res.success) {
        const gift = res.data || null
        if (gift && gift.image) gift.image = this.getGiftImageUrl(gift.image)
        this.setData({
          gift
        })
      }
    } catch (error) {
      console.error('加载礼品详情失败:', error)
      // 401错误由API层统一处理，这里只处理其他错误
      if (error.code !== 401) {
        wx.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      }
    } finally {
      this.setData({ loading: false })
    }
  },

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

  // 兑换礼品
  async exchangeGift() {
    const gift = this.data.gift

    // 检查爱心值是否足够
    if (this.data.userLovePoints < gift.love_cost) {
      wx.showModal({
        title: '爱心值不足',
        content: `需要 ${gift.love_cost} 爱心值，当前 ${this.data.userLovePoints} 爱心值`,
        showCancel: false
      })
      return
    }

    // 检查库存
    if (gift.stock <= 0) {
      wx.showToast({
        title: '库存不足',
        icon: 'none'
      })
      return
    }

    // 获取收货地址
    try {
      const address = await wx.chooseAddress()
      
      // 确认兑换
      wx.showModal({
        title: '确认兑换',
        content: `确定使用 ${gift.love_cost} 爱心值兑换${gift.name}吗？`,
        success: async (res) => {
          if (res.confirm) {
            await this.doExchange(address)
          }
        }
      })
    } catch (error) {
      if (error.errMsg && error.errMsg.includes('cancel')) {
        // 用户取消选择地址
        return
      }
      console.error('获取地址失败:', error)
      wx.showToast({
        title: '请授权收货地址',
        icon: 'none'
      })
    }
  },

  async doExchange(address) {
    wx.showLoading({ title: '兑换中...' })
    
    try {
      const res = await api.gifts.exchange({
        giftId: this.data.giftId,
        shippingInfo: {
          name: address.userName,
          phone: address.telNumber,
          address: `${address.provinceName}${address.cityName}${address.countyName}${address.detailInfo}`
        }
      })

      wx.hideLoading()

      if (res.success) {
        wx.showModal({
          title: '兑换成功',
          content: res.message || '礼品兑换成功，请在兑换记录中查看物流信息',
          showCancel: false,
          success: () => {
            wx.navigateTo({
              url: '/pages/gift-exchanges/gift-exchanges'
            })
          }
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('兑换失败:', error)
      wx.showToast({
        title: error.message || '兑换失败',
        icon: 'none'
      })
    }
  },

  // 预览图片
  previewImage() {
    const imageUrl = this.data.gift && (this.data.gift.image || this.data.gift.image_url)
    if (imageUrl) {
      wx.previewImage({
        urls: [imageUrl],
        current: imageUrl
      })
    }
  }
})
