const app = getApp()
const { request } = require('../../utils/request')

Page({
  data: {
    hasUserInfo: false,
    hasPhone: false
  },
  onLoad() {
    this.checkStatus();
  },
  checkStatus() {
      // If the user is already here, we check if they are valid.
      // However, app.js handles the redirection for existing users.
      // If we are here, it means either app.js sent us here (New User),
      // or app.js hasn't finished checking yet,
      // or the user manually navigated here (unlikely).
      
      const user = app.globalData.userInfo;
      if (user) {
          // We can't rely on is_new_user here because we don't persist it in globalData (though we could).
          // But based on new logic:
          // If user exists, app.js wouldn't redirect here.
          // If we are here, user probably needs to authorize.
          
          // Update UI state
          const hasNick = user.wechat_nickname && user.wechat_nickname !== '微信用户';
          const hasPhone = !!user.phone;
          
          this.setData({
              hasUserInfo: hasNick,
              hasPhone: hasPhone
          })
          
          // If somehow we ended up here but profile is full, go home
          if (hasNick && hasPhone) {
               wx.switchTab({ url: '/pages/index/index' })
          }
      } else {
          // Wait for app.js login callback
          app.loginCallback = (user) => {
              // Re-run check
              this.checkStatus();
              // If app.js determines it's an existing user, it might redirect.
              // But if not, we update UI here.
          }
      }
  },
  getUserProfile(e) {
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        const { userInfo } = res
        console.log('getUserProfile success', userInfo)
        
        // Update backend
        // We need user ID from globalData
        if (app.globalData.userInfo && app.globalData.userInfo.id) {
             this.updateUserInfo(userInfo)
        } else {
            // Should not happen if app.js login succeeded
            wx.showToast({ title: '登录状态异常，请重启', icon: 'none' })
        }
      },
      fail: (err) => {
          console.error('getUserProfile failed', err)
          wx.showToast({ title: '需要授权才能继续', icon: 'none' })
      }
    })
  },
  updateUserInfo(wxUserInfo) {
      request({
          url: `/students/${app.globalData.userInfo.id}/`, 
          method: 'PATCH',
          data: {
              wechat_nickname: wxUserInfo.nickName,
              avatar: wxUserInfo.avatarUrl
              // name: wxUserInfo.nickName // Optional: sync name too
          }
      }).then(res => {
          console.log('Update user info success', res)
          app.globalData.userInfo = { ...app.globalData.userInfo, ...res }
          this.setData({ hasUserInfo: true })
      }).catch(err => {
          console.error('Update user info failed', err)
          wx.showToast({ title: '更新资料失败', icon: 'none' })
      })
  },
  getPhoneNumber(e) {
    console.log('getPhoneNumber', e)
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      request({
          url: '/user/phone/',
          method: 'POST',
          data: {
              code: e.detail.code
          }
      }).then(res => {
          console.log('Get phone success', res)
          if (res.phone) {
              this.setData({ hasPhone: true })
              if (app.globalData.userInfo) {
                  app.globalData.userInfo.phone = res.phone
              }
              
              wx.showToast({
                  title: '登录成功',
                  icon: 'success'
              })
              
              // Redirect to home
              setTimeout(() => {
                  wx.switchTab({ url: '/pages/index/index' })
              }, 1500)
          }
      }).catch(err => {
          console.error('Get phone failed', err)
          wx.showToast({ title: '获取手机号失败', icon: 'none' })
      })
    } else {
         console.log('User denied phone number')
         // If user denies, we can optionally let them in anyway if that's the requirement?
         // User said: "If openID exists, direct login".
         // This implies for NEW users, they MIGHT need to authorize phone.
         // But strictly speaking, once they authorized UserProfile (Avatar/Nick), 
         // the OpenID exists.
         // But the "User Phone" part is usually critical.
         // Let's keep strict requirement for phone for NEW users for now unless asked otherwise.
    }
  }
})
