const BASE_URL = 'https://mini-chat.1024tool.vip'

let authModalShown = false

function handleAuthExpired() {
  if (authModalShown) return
  authModalShown = true
  uni.removeStorageSync('token')
  uni.showModal({
    title: '提示',
    content: '账号登录已过期，请重新登录',
    showCancel: false,
    success: () => {
      authModalShown = false
      uni.navigateTo({ url: '/pages/login/index' })
    }
  })
}

// 不再脱敏，直接打印原始数据

export function request({ url, method = 'GET', data = {}, header = {} }) {
  return new Promise((resolve, reject) => {
    const finalHeader = { ...buildDefaultHeaders(), ...header }
    uni.request({
      url: BASE_URL + url,
      method,
      data,
      header: finalHeader,
      timeout: 15000,
      success: (res) => {
        const code = res.statusCode
        if (code >= 200 && code < 300) {
          const body = res.data
          resolve(body && body.data !== undefined ? body.data : body)
        } else {
          if (code === 401) {
            const suppress = finalHeader && (finalHeader['X-Suppress-Auth-Modal'] || finalHeader['x-suppress-auth-modal'])
            if (!suppress) {
              handleAuthExpired()
            }
          }
          const msg = (res.data && (res.data.message || res.data.msg)) || '请求错误'
          reject({ message: msg, statusCode: code, data: res.data })
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

export function authRequest(options) {
  const token = uni.getStorageSync('token')
  const base = buildDefaultHeaders()
  const header = { ...base, ...(options.header || {}) }
  // 不再添加 Bearer，直接原样透传 token
  if (token) {
    header.Authorization = token
    header.authorization = token
  }
  return request({ ...options, header })
}

export function redeemProductByPoints(user_id, product_id, quantity) {
  return authRequest({
    url: `/api/app/users/${user_id}/points/redeem-product`,
    method: 'POST',
    data: { product_id, quantity }
  })
}

function getLanguage() {
  try { return (uni.getSystemInfoSync().language || 'zh-CN') } catch (_) { return 'zh-CN' }
}

function getPlatform() {
  try {
    // 简单判断当前运行平台
    if (typeof wx !== 'undefined') return 'mp-weixin'
    const info = uni.getSystemInfoSync()
    return info.platform || 'unknown'
  } catch (_) { return 'unknown' }
}

function getDeviceId() {
  try {
    let id = uni.getStorageSync('device_id')
    if (!id) {
      id = 'dev-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8)
      uni.setStorageSync('device_id', id)
    }
    return id
  } catch (_) { return 'dev-unknown' }
}

function buildDefaultHeaders() {
  const info = uni.getSystemInfoSync()
  const lang = info.language || 'zh-CN'
  const platform = info.platform || 'unknown'
  const brand = info.brand || ''
  const model = info.model || ''
  const osName = info.system || ''
  const osVersion = info.system ? info.system.split(' ')[1] || '' : ''
  const screen = `${info.screenWidth}x${info.screenHeight}`
  const pixelRatio = info.pixelRatio || 1
  const windowSize = `${info.windowWidth}x${info.windowHeight}`
  return {
    'Accept': 'application/json',
    'content-type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest',
    'Accept-Language': lang,
    'X-App-Client': 'uni-app',
    'X-App-Platform': platform,
    'X-Device-Id': getDeviceId(),
    'X-Device-Brand': brand,
    'X-Device-Model': model,
    'X-OS-Name': osName,
    'X-OS-Version': osVersion,
    'X-Screen': screen,
    'X-Pixel-Ratio': pixelRatio,
    'X-Window': windowSize,
    'Cache-Control': 'no-cache',
    'User-Agent': `UniApp/${platform} (${brand} ${model}; ${osName} ${osVersion}) MiniProgram`
  }
}
