// miniprogram/app.js
App({
  globalData: {
    userInfo: null,
    apiBase: 'http://localhost:3000/api', // 本地开发API地址
    // 生产环境请改为: 'http://kr-soul.lytiao.com/api'
    appId: 'wx0976665c3a3d5a7c',
    appSecret: 'a262f1be43422f03734f205d0bca1882',
    bookData: null,
    currentChapter: null
  },

  onLaunch() {
    console.log('Soul派对小程序启动')
    
    // 检查登录态
    this.checkLoginStatus()
    
    // 加载书籍数据
    this.loadBookData()
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token')
    if (token) {
      // 验证token有效性
      this.validateToken(token)
    }
  },

  // 验证token
  validateToken(token) {
    wx.request({
      url: `${this.globalData.apiBase}/auth/validate`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.globalData.userInfo = res.data.user
        } else {
          wx.removeStorageSync('token')
        }
      }
    })
  },

  // 加载书籍数据
  loadBookData() {
    wx.request({
      url: `${this.globalData.apiBase}/book/structure`,
      success: (res) => {
        if (res.statusCode === 200) {
          this.globalData.bookData = res.data
          wx.setStorageSync('bookData', res.data)
        }
      },
      fail: () => {
        // 从缓存加载
        const cached = wx.getStorageSync('bookData')
        if (cached) {
          this.globalData.bookData = cached
        }
      }
    })
  },

  // 微信登录
  wxLogin(callback) {
    wx.login({
      success: (res) => {
        if (res.code) {
          wx.request({
            url: `${this.globalData.apiBase}/auth/wx-login`,
            method: 'POST',
            data: { code: res.code },
            success: (loginRes) => {
              if (loginRes.statusCode === 200) {
                const { token, user } = loginRes.data
                wx.setStorageSync('token', token)
                this.globalData.userInfo = user
                callback && callback(true, user)
              } else {
                callback && callback(false)
              }
            },
            fail: () => {
              callback && callback(false)
            }
          })
        }
      }
    })
  },

  // 获取用户信息
  getUserInfo() {
    return this.globalData.userInfo
  }
})
