// API 基础配置
// @ts-ignore
const BASE_URL = (typeof import.meta !== 'undefined' && import.meta.env && import.meta.env.VITE_API_BASE_URL) || '/api';

// 开发环境使用本地 API，生产环境使用线上 API
const isDev = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development';

// 请求封装
export async function request<T = unknown>(
  url: string,
  options: {
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
    data?: Record<string, unknown>;
    header?: Record<string, string>;
    showLoading?: boolean;
  } = {}
): Promise<T> {
  const { method = 'GET', data, header = {}, showLoading = false } = options;

  // 获取 token
  const token = uni.getStorageSync('token');
  if (token) {
    header['Authorization'] = `Bearer ${token}`;
  }
  header['Content-Type'] = 'application/json';

  if (showLoading) {
    uni.showLoading({ title: '加载中...', mask: true });
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + url,
      method,
      data,
      header,
      success: (res) => {
        if (showLoading) {
          uni.hideLoading();
        }

        const result = res.data as { code: number; message: string; data?: T };

        if (result.code === 0) {
          resolve(result.data as T);
        } else if (result.code === 401) {
          // token 过期，跳转登录
          uni.removeStorageSync('token');
          uni.removeStorageSync('userInfo');
          // 如果不是登录页，则跳转
          const pages = getCurrentPages();
          const currentPage = pages[pages.length - 1] as any;
          if (currentPage && !currentPage.route.includes('login')) {
            uni.reLaunch({ url: '/pages/login/index' });
          }
          reject(new Error('请先登录'));
        } else if (result.code >= 500) {
          // 服务器错误
          uni.showToast({ title: result.message || '服务器错误', icon: 'none' });
          reject(new Error(result.message));
        } else {
          uni.showToast({ title: result.message, icon: 'none' });
          reject(new Error(result.message));
        }
      },
      fail: (err) => {
        if (showLoading) {
          uni.hideLoading();
        }
        uni.showToast({ title: '网络请求失败', icon: 'none' });
        reject(err);
      },
    });
  });
}

// GET 请求
export function get<T = unknown>(url: string, params?: Record<string, unknown>): Promise<T> {
  const queryString = params
    ? '?' + Object.entries(params)
        .filter(([, v]) => v !== undefined)
        .map(([k, v]) => `${k}=${encodeURIComponent(String(v))}`)
        .join('&')
    : '';
  return request<T>(url + queryString);
}

// POST 请求
export function post<T = unknown>(url: string, data?: Record<string, unknown>): Promise<T> {
  return request<T>(url, { method: 'POST', data });
}

// PUT 请求
export function put<T = unknown>(url: string, data?: Record<string, unknown>): Promise<T> {
  return request<T>(url, { method: 'PUT', data });
}

// DELETE 请求
export function del<T = unknown>(url: string, data?: Record<string, unknown>): Promise<T> {
  return request<T>(url, { method: 'DELETE', data });
}