const env = require('./config/env')

App({
  onLaunch() {
    console.log('App Launch')
    this.login();
  },
  globalData: {
    userInfo: null,
    baseUrl: env.baseUrl,
    token: null
  },
  login() {
      wx.login({
          success: res => {
              if (res.code) {
                  // 发送 res.code 到后台换取 openId, sessionKey, unionId
                  wx.request({
                      url: `${this.globalData.baseUrl}/auth/login/`,
                      method: 'POST',
                      data: {
                          code: res.code
                      },
                      success: (response) => {
                          // FitJSONRenderer wraps response in { code, data, msg }
                          const resBody = response.data;
                          if (response.statusCode === 200 && resBody.code >= 200 && resBody.code < 300) {
                              // Handle wrapped data
                              const payload = resBody.data || resBody;
                              const { token, user, is_new_user } = payload;
                              
                              if (!token || !user) {
                                  console.error('Login response missing token or user', payload);
                                  return;
                              }

                              this.globalData.token = token;
                              this.globalData.userInfo = user;

                              // Logic:
                              // 1. If it's a new user (is_new_user=True), go to Login Page to authorize.
                              // 2. If it's an existing user (is_new_user=False), stay at Home (or redirect there if not).
                              // Note: We ignore whether they have phone/nickname if they are existing users, per user request "direct login".
                              
                              if (is_new_user) {
                                  wx.reLaunch({
                                      url: '/pages/login/login'
                                  })
                              } else {
                                  // If we are currently on login page, go to home
                                  // But onLaunch happens early. Usually we just don't redirect TO login.
                                  // However, if the entry page WAS login (e.g. from share), we might want to go home.
                                  // Or if the entry page is Home, we just stay there.
                                  // Since we can't easily know "current page" in onLaunch without complex logic,
                                  // and default entry is usually Home (pages/index/index), we just do nothing.
                                  // BUT, if the app was configured to start at Login page in json, we might need to redirect.
                                  // Let's assume default is index.
                                  
                                  // If we are explicitly on login page (re-launched or shared), we should leave.
                                  const pages = getCurrentPages()
                                  if (pages.length > 0) {
                                      const route = pages[pages.length - 1].route
                                      if (route.includes('pages/login/login')) {
                                          wx.switchTab({ url: '/pages/index/index' })
                                      }
                                  }
                              }
                              
                              // 如果有页面需要监听登录状态，可以在这里触发回调
                              if (this.loginCallback) {
                                  this.loginCallback(user);
                              }
                          } else {
                              console.log('登录失败！', resBody.msg || response.errMsg)
                          }
                      }
                  })
              } else {
                  console.log('登录失败！' + res.errMsg)
              }
          }
      })
  }
})
