import { API_BASE_URL, API_BASE_URL_CANDIDATES, SHOP_ID, ENABLE_DEFAULT_USER, DEFAULT_USER_ID } from './config.js'

function buildUrl(path) {
  if (!path) return API_BASE_URL
  if (path.startsWith('http')) return path
  return API_BASE_URL + (path.startsWith('/') ? path : '/' + path)
}

function requestWithFallback(options, candidates, idx, resolve, reject) {
  const base = candidates[idx] || API_BASE_URL
  const url = options.url.replace(/^https?:\/\/[^/]+/, base)
  uni.request({ ...options, url, success: (res) => {
    const { statusCode, data } = res
    if (statusCode >= 200 && statusCode < 300) return resolve(data)
    const msg = (data && (data.message || data.error || data.msg)) || ('HTTP ' + statusCode)
    uni.showToast({ title: msg, icon: 'none' })
    if (idx + 1 < candidates.length) return requestWithFallback(options, candidates, idx + 1, resolve, reject)
    reject(new Error(msg))
  }, fail: (err) => {
    if (idx + 1 < candidates.length) return requestWithFallback(options, candidates, idx + 1, resolve, reject)
    reject(err)
  } })
}

export function get(path, params = {}) {
  return new Promise((resolve, reject) => {
    const headers = { 'X-Shop-Id': SHOP_ID }
    if (ENABLE_DEFAULT_USER && DEFAULT_USER_ID) headers['X-User-Id'] = DEFAULT_USER_ID
    const options = { url: buildUrl(path), method: 'GET', data: params, header: headers }
    requestWithFallback(options, API_BASE_URL_CANDIDATES, 0, resolve, reject)
  })
}


export function post(path, body = {}) {
  return new Promise((resolve, reject) => {
    const headers = { 'Content-Type': 'application/json', 'X-Shop-Id': SHOP_ID }
    if (ENABLE_DEFAULT_USER && DEFAULT_USER_ID) headers['X-User-Id'] = DEFAULT_USER_ID
    const options = { url: buildUrl(path), method: 'POST', data: body, header: headers }
    requestWithFallback(options, API_BASE_URL_CANDIDATES, 0, resolve, reject)
  })
}


export function put(path, body = {}) {
  return new Promise((resolve, reject) => {
    const headers = { 'Content-Type': 'application/json', 'X-Shop-Id': SHOP_ID }
    if (ENABLE_DEFAULT_USER && DEFAULT_USER_ID) headers['X-User-Id'] = DEFAULT_USER_ID
    const options = { url: buildUrl(path), method: 'PUT', data: body, header: headers }
    requestWithFallback(options, API_BASE_URL_CANDIDATES, 0, resolve, reject)
  })
}

export function del(path, body = {}) {
  return new Promise((resolve, reject) => {
    const headers = { 'Content-Type': 'application/json', 'X-Shop-Id': SHOP_ID }
    if (ENABLE_DEFAULT_USER && DEFAULT_USER_ID) headers['X-User-Id'] = DEFAULT_USER_ID
    const options = { url: buildUrl(path), method: 'DELETE', data: body, header: headers }
    requestWithFallback(options, API_BASE_URL_CANDIDATES, 0, resolve, reject)
  })
}

function uploadWithFallback(options, candidates, idx, resolve, reject) {
  const base = candidates[idx] || API_BASE_URL
  const url = options.url.replace(/^https?:\/\/[^/]+/, base)
  const uploadOptions = { ...options, url }
  uni.uploadFile({
    ...uploadOptions,
    success: (res) => {
      const statusCode = res.statusCode || 0
      if (statusCode >= 200 && statusCode < 300) {
        try {
          const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
          return resolve(data)
        } catch (e) {
          return resolve(res.data)
        }
      }
      if (idx + 1 < candidates.length) return uploadWithFallback(options, candidates, idx + 1, resolve, reject)
      reject(new Error('HTTP ' + statusCode))
    },
    fail: (err) => {
      if (idx + 1 < candidates.length) return uploadWithFallback(options, candidates, idx + 1, resolve, reject)
      reject(err)
    }
  })
}

// 文件上传封装：自动注入租户/用户头并进行多地址回退
export function upload(path, filePath, formData = {}, name = 'file') {
  return new Promise((resolve, reject) => {
    const header = { 'X-Shop-Id': SHOP_ID }
    if (ENABLE_DEFAULT_USER && DEFAULT_USER_ID) header['X-User-Id'] = DEFAULT_USER_ID
    const options = { url: buildUrl(path), filePath, name, formData, header }
    uploadWithFallback(options, API_BASE_URL_CANDIDATES, 0, resolve, reject)
  })
}

