// 获取当前平台的 API 基础地址
function getBaseURL(): string {
  // 判断当前运行平台
  // #ifdef H5
  return import.meta.env.VITE_H5_API_BASE_URL || 'http://localhost:3000';
  // #endif

  // #ifdef MP-WEIXIN
  return import.meta.env.VITE_MP_API_BASE_URL || 'http://localhost:3000';
  // #endif

  // 其他平台默认值
  // #ifndef H5 || MP-WEIXIN
  return import.meta.env.VITE_MP_API_BASE_URL || 'http://localhost:3000';
  // #endif
}

const BASE_URL = getBaseURL();

interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: Record<string, string>;
  showLoading?: boolean;
  useSellerToken?: boolean;
  skipAuthRedirect?: boolean;
}

interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
}

function getToken(): string {
  return uni.getStorageSync('token') || '';
}

export function request<T = any>(options: RequestOptions): Promise<ApiResponse<T>> {
  const { url, method = 'GET', data, header = {}, showLoading = false, useSellerToken = false, skipAuthRedirect = false } = options;

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

  let token = '';
  if (useSellerToken) {
    token = uni.getStorageSync('sellerToken') || '';
  } else {
    token = getToken();
  }
  if (token) {
    header['Authorization'] = `Bearer ${token}`;
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASE_URL}${url}`,
      method,
      data,
      header: {
        'Content-Type': 'application/json',
        ...header,
      },
      success: (res) => {
        if (showLoading) uni.hideLoading();

        const responseData = res.data as ApiResponse<T>;

        // 检查响应体中的 code 是否为 401
        if (responseData.code === 401 || res.statusCode === 401) {
          // 如果是 skipAuthRedirect，只清除 token 不跳转页面
          if (skipAuthRedirect) {
            if (useSellerToken) {
              uni.removeStorageSync('sellerToken');
              uni.removeStorageSync('sellerInfo');
            } else {
              uni.removeStorageSync('token');
              uni.removeStorageSync('userInfo');
            }
            reject(new Error(responseData.message || '登录已过期'));
            return;
          }

          // 正常 401 处理，只清除对应账户的 token，不互相干扰
          if (useSellerToken) {
            // 商家 token 失效，跳转到商家登录页
            uni.removeStorageSync('sellerToken');
            uni.removeStorageSync('sellerInfo');
            uni.navigateTo({ url: '/pages/seller/register?mode=login' });
          } else {
            // 用户 token 失效，清除用户登录状态并跳转登录页
            uni.removeStorageSync('token');
            uni.removeStorageSync('userInfo');
            uni.navigateTo({ url: '/pages/login/index' });
          }
          reject(new Error('登录已过期'));
          return;
        }

        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(responseData);
        } else {
          uni.showToast({ title: responseData.message || '请求失败', icon: 'none' });
          reject(new Error(responseData.message));
        }
      },
      fail: (err) => {
        if (showLoading) uni.hideLoading();
        uni.showToast({ title: '网络异常', icon: 'none' });
        reject(err);
      },
    });
  });
}

export function get<T = any>(url: string, data?: any) {
  return request<T>({ url, method: 'GET', data });
}

export function post<T = any>(url: string, data?: any) {
  return request<T>({ url, method: 'POST', data });
}

export function put<T = any>(url: string, data?: any) {
  return request<T>({ url, method: 'PUT', data });
}

export function del<T = any>(url: string, data?: any) {
  return request<T>({ url, method: 'DELETE', data });
}
