// pages/match/match.js
const app = getApp()

Page({
  data: {
    isMatching: false,
    currentMatch: null,
    onlineCount: 0,
    matchAttempts: 0,
    recentMatches: [],
    matchTimer: null
  },

  onLoad() {
    this.initStarBackground()
    this.loadOnlineCount()
    this.loadRecentMatches()
  },

  onUnload() {
    // 清理匹配定时器
    if (this.data.matchTimer) {
      clearTimeout(this.data.matchTimer)
    }
  },

  // 初始化星空背景
  initStarBackground() {
    const ctx = wx.createCanvasContext('starCanvas')
    const width = wx.getSystemInfoSync().windowWidth
    const height = wx.getSystemInfoSync().windowHeight
    
    // 绘制星星
    for (let i = 0; i < 100; i++) {
      const x = Math.random() * width
      const y = Math.random() * height
      const radius = Math.random() * 2
      const opacity = Math.random()
      
      ctx.beginPath()
      ctx.arc(x, y, radius, 0, 2 * Math.PI)
      ctx.fillStyle = `rgba(255, 255, 255, ${opacity})`
      ctx.fill()
    }
    
    ctx.draw()
  },

  // 加载在线人数
  loadOnlineCount() {
    wx.request({
      url: `${app.globalData.apiBase}/match/online-count`,
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            onlineCount: res.data.count || 0
          })
        }
      },
      fail: () => {
        // 使用模拟数据
        this.setData({
          onlineCount: Math.floor(Math.random() * 500) + 100
        })
      }
    })
  },

  // 加载最近匹配记录
  loadRecentMatches() {
    const userInfo = app.getUserInfo()
    if (!userInfo) return

    wx.request({
      url: `${app.globalData.apiBase}/match/recent`,
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            recentMatches: res.data.matches || []
          })
        }
      },
      fail: () => {
        // 使用本地缓存
        const cached = wx.getStorageSync('recentMatches')
        if (cached) {
          this.setData({ recentMatches: cached })
        }
      }
    })
  },

  // 开始匹配
  startMatch() {
    const userInfo = app.getUserInfo()
    
    if (!userInfo) {
      this.showLoginModal()
      return
    }

    this.setData({
      isMatching: true,
      matchAttempts: 0
    })

    // 模拟匹配过程
    this.doMatch()
  },

  // 执行匹配
  doMatch() {
    const timer = setInterval(() => {
      const attempts = this.data.matchAttempts + 1
      this.setData({ matchAttempts: attempts })

      // 3-6秒后匹配成功
      if (attempts >= 3) {
        clearInterval(timer)
        this.matchSuccess()
      }
    }, 1000)

    this.setData({ matchTimer: timer })

    // 真实匹配请求
    wx.request({
      url: `${app.globalData.apiBase}/match/find`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      data: {
        interests: ['创业', '私域运营', '读书'],
        currentChapter: app.globalData.currentChapter
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.match) {
          clearInterval(timer)
          this.matchSuccess(res.data.match)
        }
      },
      fail: () => {
        // 使用模拟数据
        clearInterval(timer)
        this.matchSuccess(this.getMockMatch())
      }
    })
  },

  // 匹配成功
  matchSuccess(matchData) {
    const match = matchData || this.getMockMatch()
    
    this.setData({
      isMatching: false,
      currentMatch: match
    })

    // 震动反馈
    wx.vibrateShort()

    // 播放成功提示音
    wx.showToast({
      title: '匹配成功！',
      icon: 'success',
      duration: 1500
    })

    // 保存到最近匹配
    this.saveRecentMatch(match)
  },

  // 获取模拟匹配数据
  getMockMatch() {
    const nicknames = ['阅读爱好者', '创业小白', '私域达人', '书虫一枚', '灵魂摆渡人']
    const avatars = [
      'https://picsum.photos/200/200?random=1',
      'https://picsum.photos/200/200?random=2',
      'https://picsum.photos/200/200?random=3'
    ]
    const tagsList = [
      ['创业者', '私域运营', 'MBTI-INTP'],
      ['读书达人', 'Soul用户', '内容创作'],
      ['互联网人', '产品经理', '深度思考']
    ]
    const concepts = [
      '一个坚持长期主义的私域玩家，擅长内容结构化。',
      '相信阅读可以改变人生，每天坚持读书1小时。',
      '在Soul上分享创业经验，希望帮助更多人少走弯路。'
    ]
    const wechats = [
      'soul_book_friend_1',
      'soul_reader_2024',
      'soul_party_fan'
    ]

    const randomIndex = Math.floor(Math.random() * nicknames.length)
    
    return {
      id: `user_${Date.now()}`,
      nickname: nicknames[randomIndex],
      avatar: avatars[randomIndex % avatars.length],
      tags: tagsList[randomIndex % tagsList.length],
      matchScore: Math.floor(Math.random() * 20) + 80,
      concept: concepts[randomIndex % concepts.length],
      wechat: wechats[randomIndex % wechats.length],
      commonInterests: [
        { icon: '📚', text: '都在读《创业实验》' },
        { icon: '💼', text: '对私域运营感兴趣' },
        { icon: '🎯', text: '相似的职业背景' }
      ]
    }
  },

  // 保存最近匹配
  saveRecentMatch(match) {
    let recent = this.data.recentMatches
    const newMatch = {
      ...match,
      matchTime: '刚刚'
    }
    
    recent.unshift(newMatch)
    if (recent.length > 10) {
      recent = recent.slice(0, 10)
    }
    
    this.setData({ recentMatches: recent })
    wx.setStorageSync('recentMatches', recent)
  },

  // 取消匹配
  cancelMatch() {
    if (this.data.matchTimer) {
      clearTimeout(this.data.matchTimer)
    }
    
    this.setData({
      isMatching: false,
      matchAttempts: 0
    })

    wx.showToast({
      title: '已取消匹配',
      icon: 'none'
    })
  },

  // 一键加好友
  addWechat() {
    const match = this.data.currentMatch
    if (!match || !match.wechat) return

    wx.setClipboardData({
      data: match.wechat,
      success: () => {
        wx.showModal({
          title: '微信号已复制',
          content: `微信号：${match.wechat}\n\n已复制到剪贴板，请打开微信添加好友，备注"书友"即可。`,
          showCancel: false,
          confirmText: '打开微信',
          success: (res) => {
            if (res.confirm) {
              // 尝试打开微信（小程序无法直接跳转，只能提示）
              wx.showToast({
                title: '请手动打开微信添加',
                icon: 'none',
                duration: 2000
              })
            }
          }
        })
      }
    })
  },

  // 加入书友群
  joinGroup() {
    wx.showModal({
      title: '加入书友群',
      content: '请先添加书友微信，备注"书友群"，对方会拉你入群。\n\n群内可以：\n· 深度交流读书心得\n· 参加线下读书会\n· 获取独家资源',
      showCancel: true,
      cancelText: '取消',
      confirmText: '添加好友',
      success: (res) => {
        if (res.confirm) {
          this.addWechat()
        }
      }
    })
  },

  // 下一位
  nextMatch() {
    this.setData({
      currentMatch: null,
      matchAttempts: 0
    })
    
    wx.showToast({
      title: '重新匹配中',
      icon: 'loading'
    })

    setTimeout(() => {
      this.startMatch()
    }, 500)
  },

  // 查看匹配详情
  viewMatchDetail(e) {
    const matchId = e.currentTarget.dataset.id
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  },

  // 显示登录弹窗
  showLoginModal() {
    wx.showModal({
      title: '需要登录',
      content: '匹配书友前需要先登录账号',
      confirmText: '立即登录',
      success: (res) => {
        if (res.confirm) {
          app.wxLogin((success) => {
            if (success) {
              wx.showToast({
                title: '登录成功',
                icon: 'success'
              })
              setTimeout(() => {
                this.startMatch()
              }, 1500)
            }
          })
        }
      }
    })
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '来Soul派对匹配志同道合的书友吧！',
      path: '/pages/match/match',
      imageUrl: '/assets/images/share-match.png'
    }
  }
})
