/**
 * uni-app 简易请求封装
 * - 统一拼接 BASE_URL + path
 * - 注入 token header
 * - Promise 化，提供 get/post/put/delete 快捷方法
 *
 * 用法：
 *   import request from '@/api/request.js'
 *   request.get('/user/info', { id: 1 })
 *   request.post('/user/login', { username, password })
 */

// 基础路径：修改此处即可切换后端地址
const BASE_URL = 'http://192.168.124.137:3001';

// 默认配置
const TIMEOUT = 30000;
const DEFAULT_HEADER = { 'Content-Type': 'application/json' };

// 统一拼装 URL：完整地址直接返回，否则 BASE_URL + path
function buildUrl(url) {
    if (!url) return '';
    if (/^https?:\/\//i.test(url)) return url;
    const base = BASE_URL.replace(/\/+$/, '');
    const path = url.replace(/^\/+/, '');
    return path ? `${base}/${path}` : base;
}

// 统一取 header（注入 token）
function buildHeader(extraHeader) {
    const header = Object.assign({}, DEFAULT_HEADER, extraHeader || {});
    const token = uni.getStorageSync('token');
    if (token) header['Authorization'] = `Bearer ${token}`;
    return header;
}

/**
 * 核心请求方法
 * @param {Object} options
 * @param {string} options.url    相对路径或完整 URL
 * @param {string} [options.method='GET']
 * @param {Object} [options.data] 请求参数 / body
 * @param {Object} [options.header] 额外 header
 * @returns {Promise<any>}
 */
function request(options = {}) {
    return new Promise((resolve, reject) => {
        uni.request({
            url: buildUrl(options.url || ''),
            method: (options.method || 'GET').toUpperCase(),
            data: options.data || {},
            header: buildHeader(options.header),
            timeout: TIMEOUT,
            dataType: 'json',
            success: resolve,
            fail: reject
        });
    });
}

// 快捷方法
request.get = (url, data, options) => request({ url, method: 'GET', data, ...options });
request.post = (url, data, options) => request({ url, method: 'POST', data, ...options });
request.put = (url, data, options) => request({ url, method: 'PUT', data, ...options });
request.delete = (url, data, options) => request({ url, method: 'DELETE', data, ...options });

export default request;
