import config from '../config'

const LOGIN_PAGE = '/pages/user/login'

/**
 * 获取本地 token
 */
function getToken() {
  return uni.getStorageSync('token') || ''
}

/**
 * 统一处理未登录或被踢下线
 */
function handleAuthFail(checkLogin = true) {
  console.log('开始清理登录信息并跳转登录页')
  uni.removeStorageSync('token')
  uni.removeStorageSync('tokenExpiresAt')
  uni.removeStorageSync('userInfo')
  if (checkLogin) {
    console.log('准备跳转到登录页:', LOGIN_PAGE)
    // 使用 reLaunch 强制跳转到登录页，避免用户返回到已失效的页面
    uni.reLaunch({ 
      url: LOGIN_PAGE,
      success: () => {
        console.log('跳转登录页成功')
      },
      fail: (err) => {
        console.log('跳转登录页失败:', err)
      }
    })
  }
}

/**
 * 构建请求头
 */
function buildHeaders(customHeaders = {}) {
  return {
    'Content-Type': 'application/json',
    'Authorization': getToken(),
    ...customHeaders
  }
}

/**
 * 通用请求方法
 */
function baseRequest({ url, method = 'GET', data = {}, checkLogin = true, headers = {} }) {
  return new Promise((resolve, reject) => {
    // 确保URL拼接正确，避免重复的斜杠
    const fullUrl = config.baseUrl.replace(/\/$/, '') + '/' + url.replace(/^\//, '')
    console.log('请求URL:', fullUrl)
    
    uni.request({
      url: fullUrl,
      method,
      data,
      header: buildHeaders(headers),
      success: (res) => {
        const { statusCode, data: resData } = res
        if (statusCode === 200 && resData) {
          // 账号在其他设备登录
          if (resData.code === 409) {
            uni.showModal({
              title: '提示',
              content: '您的账号已在其他设备登录，已强制下线!',
              showCancel: false,
              success: () => handleAuthFail(checkLogin)
            })
            resolve(resData)
            return
          }
          // 用户认证失败
          if (resData.code === 5) {
            handleAuthFail(checkLogin)
            resolve(resData)
            return
          }
          // 授权已过期
          if (resData.code === 5) {
            console.log('检测到授权过期，code=7，准备跳转登录页')
            uni.showToast({
              title: '授权已过期，请重新登录',
              icon: 'none'
            })
            handleAuthFail(checkLogin)
            resolve(resData)
            return
          }
          resolve(resData)
        } else {
          reject({
            code: statusCode,
            msg: res.errMsg || '网络错误',
            data: null
          })
        }
      },
      fail: (err) => {
        console.log('请求失败:', err)
        // 处理401未授权错误
        if (err.statusCode === 401 || err.code === 401) {
          console.log('检测到401未授权，准备跳转登录页')
          uni.showToast({
            title: '授权已过期，请重新登录',
            icon: 'none'
          })
          handleAuthFail(true)
          reject({
            code: 7,
            msg: '授权已过期',
            data: null
          })
          return
        }
        reject({
          code: 0,
          msg: err.errMsg || '请求失败',
          data: null
        })
      }
    })
  })
}

/**
 * 导出常用请求方法
 */
const request = {
  get(url, data = {}, checkLogin = true, headers = {}) {
    return baseRequest({ url, method: 'GET', data, checkLogin, headers })
  },
  post(url, data = {}, checkLogin = true, headers = {}) {
    return baseRequest({ url, method: 'POST', data, checkLogin, headers })
  },
  put(url, data = {}, checkLogin = true, headers = {}) {
    return baseRequest({ url, method: 'PUT', data, checkLogin, headers })
  },
  delete(url, data = {}, checkLogin = true, headers = {}) {
    return baseRequest({ url, method: 'DELETE', data, checkLogin, headers })
  },
  
  // 兼容原有的http.request方法
  request: ({ url, method = 'GET', data = {}, headers = {} }) => {
    return baseRequest({ url, method, data, checkLogin: true, headers })
  }
}

export default request