// pages/singles-party/singles-party.js - 单身聚会页面
const api = require('../../utils/api')
const app = getApp()

Page({
  data: {
    statusBarHeight: 44,
    navBarHeight: 44,
    totalNavHeight: 88,
    loading: false,
    
    // 活动标签
    activeTab: 'featured', // featured: 精选活动, free: 免费活动, vip: VIP活动, svip: SVIP活动
    
    // 活动列表
    activityList: [],
    
    // 二维码弹窗
    showQrcodeModal: false,
    qrcodeImageUrl: '' // 单身聚会群二维码
  },

  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.loadActivityList()
  },

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

  /**
   * 切换活动标签
   */
  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab
    if (tab === this.data.activeTab) return
    
    this.setData({ activeTab: tab })
    this.loadActivityList()
  },

  /**
   * 加载活动列表 - 根据category筛选单身聚会
   */
  async loadActivityList() {
    this.setData({ loading: true })
    
    try {
      const { activeTab } = this.data
      const params = {
        category: 'city', // 单身聚会通常属于同城活动
        limit: 100
      }

      // 根据选中的标签添加筛选条件
      if (activeTab === 'featured') {
        params.tab = 'featured'
      } else if (activeTab === 'free') {
        params.priceType = 'free'
      } else if (activeTab === 'vip') {
        params.is_vip = true
      } else if (activeTab === 'svip') {
        params.is_svip = true
      }

      const res = await api.activity.getList(params)
      
      if (res.success && res.data && res.data.list) {
        // 前端筛选：显示categoryName包含"单身"或"聚会"的活动
        const allActivities = res.data.list
        const filteredActivities = allActivities.filter(item => 
          item.categoryName === '单身聚会' || 
          (item.title && (item.title.includes('单身') || item.title.includes('聚会')))
        )

        // 获取第一个活动的二维码作为俱乐部二维码（如果有）
        let clubQrcode = ''
        const firstWithQrcode = filteredActivities.find(item => item.activityGuideQrcode || item.activity_guide_qrcode)
        if (firstWithQrcode) {
          clubQrcode = firstWithQrcode.activityGuideQrcode || firstWithQrcode.activity_guide_qrcode
        }

        // 转换数据格式
        const activityList = filteredActivities.map(item => {
          const heat = item.heat || (item.likes * 2 + (item.views || 0) + (item.current_participants || 0) * 3)
          
          return {
            id: item.id,
            title: item.title,
            date: this.formatDate(item.start_date || item.activityDate),
            location: item.location || '',
            venue: item.venue || '',
            image: item.coverImage || item.cover_image || '',
            heat: Math.floor(heat),
            price: item.price_text || item.priceText || '免费',
            priceType: item.is_free || item.priceType === 'free' ? 'free' : 'paid',
            likes: item.likes || item.likesCount || 0,
            participants: item.current_participants || item.currentParticipants || 0,
            isLiked: item.is_liked || item.isLiked || false,
            isSignedUp: item.is_registered || item.isSignedUp || false,
            status: item.status || (item.currentParticipants >= item.maxParticipants && item.maxParticipants > 0 ? 'full' : 'upcoming'),
            activityGuideQrcode: item.activityGuideQrcode || item.activity_guide_qrcode || ''
          }
        })
        
        console.log('[singles-party] 加载成功，数量:', activityList.length)
        this.setData({ 
          activityList,
          qrcodeImageUrl: clubQrcode || this.data.qrcodeImageUrl || 'https://ai-c.maimanji.com/images/qrcode-singles-party.jpg'
        })
      } else {
        this.setData({ activityList: [] })
      }
    } catch (err) {
      console.error('加载活动列表失败', err)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      this.setData({ activityList: [] })
    } finally {
      this.setData({ loading: false })
    }
  },
  
  /**
   * 格式化日期
   */
  formatDate(dateStr) {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}年${month}月${day}日`
  },

  /**
   * 点击活动卡片
   */
  onActivityTap(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/activity-detail/activity-detail?id=${id}`
    })
  },

  /**
   * 点赞
   */
  async onLike(e) {
    const id = e.currentTarget.dataset.id
    const index = e.currentTarget.dataset.index
    
    if (!app.globalData.isLoggedIn) {
      wx.navigateTo({ url: '/pages/login/login' })
      return
    }
    
    try {
      const res = await api.activity.toggleLike(id)
      if (res.success) {
        this.setData({
          [`activityList[${index}].isLiked`]: res.data.isLiked,
          [`activityList[${index}].likes`]: res.data.likesCount
        })
      }
    } catch (err) {
      console.error('点赞失败', err)
      wx.showToast({ title: '操作失败', icon: 'none' })
    }
  },

  /**
   * 立即报名
   */
  async onSignUp(e) {
    const id = e.currentTarget.dataset.id
    const index = e.currentTarget.dataset.index
    
    if (!app.globalData.isLoggedIn) {
      wx.navigateTo({ url: '/pages/login/login' })
      return
    }
    
    const activity = this.data.activityList[index]
    
    // 检查活动状态
    if (activity.status === 'full' || activity.status === 'ended') {
      const qrCode = activity.activityGuideQrcode || activity.activity_guide_qrcode || this.data.qrcodeImageUrl || 'https://ai-c.maimanji.com/api/common/qrcode?type=group'
      this.setData({ 
        qrcodeImageUrl: qrCode,
        showQrcodeModal: true 
      })
      return
    }

    try {
      if (activity.isSignedUp) {
        // 取消报名
        const res = await api.activity.cancelSignup(id)
        if (res.success) {
          wx.showToast({ title: '已取消报名', icon: 'success' })
          this.loadActivityList()
        }
      } else {
        // 报名
        const res = await api.activity.signup(id)
        if (res.success) {
          wx.showToast({ title: '报名成功', icon: 'success' })
          this.loadActivityList()
        } else {
          // 检查是否需要显示二维码
          if (res.code === 'QR_CODE_REQUIRED' || res.error === 'QR_CODE_REQUIRED' || res.code === 'ACTIVITY_ENDED' || res.error === '活动已结束') {
            if (activity.activityGuideQrcode || activity.activity_guide_qrcode) {
              this.setData({ qrcodeImageUrl: activity.activityGuideQrcode || activity.activity_guide_qrcode })
            }
            this.setData({ showQrcodeModal: true })
            if (res.code === 'ACTIVITY_ENDED' || res.error === '活动已结束') {
              wx.showToast({ title: '活动已结束，进群查看更多', icon: 'none' })
            }
          } else {
            wx.showToast({ 
              title: res.error || '操作失败', 
              icon: 'none' 
            })
          }
        }
      }
    } catch (err) {
      console.error('报名操作失败', err)
      const isQrRequired = err && (err.code === 'QR_CODE_REQUIRED' || (err.data && err.data.code === 'QR_CODE_REQUIRED'))
      const isActivityEnded = err && (err.code === 'ACTIVITY_ENDED' || (err.data && err.data.code === 'ACTIVITY_ENDED') || err.error === '活动已结束')
      
      if (isQrRequired || isActivityEnded) {
        if (activity.activityGuideQrcode || activity.activity_guide_qrcode) {
          this.setData({ qrcodeImageUrl: activity.activityGuideQrcode || activity.activity_guide_qrcode })
        }
        this.setData({ showQrcodeModal: true })
        if (isActivityEnded) {
          wx.showToast({ title: '活动已结束，进群查看更多', icon: 'none' })
        }
      } else {
        wx.showToast({ 
          title: err.error || err.message || '操作失败', 
          icon: 'none' 
        })
      }
    }
  },

  /**
   * 加入单身聚会群
   */
  onJoinGroup() {
    if (!this.data.qrcodeImageUrl && this.data.activityList.length > 0) {
      const firstWithQrcode = this.data.activityList.find(item => item.activityGuideQrcode || item.activity_guide_qrcode)
      if (firstWithQrcode) {
        this.setData({ qrcodeImageUrl: firstWithQrcode.activityGuideQrcode || firstWithQrcode.activity_guide_qrcode })
      }
    }
    this.setData({ showQrcodeModal: true })
  },

  /**
   * 关闭二维码弹窗
   */
  onCloseQrcodeModal() {
    this.setData({ showQrcodeModal: false })
  },

  /**
   * 阻止冒泡
   */
  preventBubble() {
    return
  },

  /**
   * 保存二维码
   */
  async onSaveQrcode() {
    try {
      const { qrcodeImageUrl } = this.data
      const downloadRes = await new Promise((resolve, reject) => {
        wx.downloadFile({
          url: qrcodeImageUrl,
          success: resolve,
          fail: reject
        })
      })
      
      if (downloadRes.statusCode !== 200) throw new Error('下载失败')
      
      await new Promise((resolve, reject) => {
        wx.saveImageToPhotosAlbum({
          filePath: downloadRes.tempFilePath,
          success: resolve,
          fail: reject
        })
      })
      
      wx.showToast({ title: '保存成功', icon: 'success' })
      this.onCloseQrcodeModal()
    } catch (err) {
      console.error('保存失败', err)
      wx.showToast({ title: '保存失败', icon: 'none' })
    }
  }
})