/**
 * 兼容旧版API的请求工具
 * 这个文件是为了保持向后兼容性，让现有的API代码能够正常工作
 * 逐步迁移完成后可以删除此文件
 */

import { getRaw, postRaw, putRaw, delRaw } from './request';
import { BaseUrl, TenantId } from "@/config/app";
import Taro from '@tarojs/taro';

let baseUrl = BaseUrl;

// 开发环境
if (process.env.NODE_ENV === 'development') {
  // baseUrl = 'http://localhost:9200/api'
}

// 兼容旧版的request函数
export function request<T>(options: any): Promise<T> {
  const token = Taro.getStorageSync('access_token');
  const header: Record<string, string> = {
    'Content-Type': 'application/json',
    'TenantId': Taro.getStorageSync('TenantId') || TenantId
  };

  if (token) {
    header['Authorization'] = token;
  }

  // 构建完整URL
  let url = options.url;
  if (url.indexOf('http') === -1) {
    url = baseUrl + url;
  }

  // 根据方法调用对应的新请求函数
  const method = (options.method || 'GET').toUpperCase();
  const config = {
    header: { ...header, ...options.header },
    showError: false // 让API层自己处理错误
  };

  switch (method) {
    case 'GET':
      return getRaw<T>(url, null, config);
    case 'POST':
      return postRaw<T>(url, options.data, config);
    case 'PUT':
      return putRaw<T>(url, options.data, config);
    case 'DELETE':
      return delRaw<T>(url, options.data, config);
    default:
      return getRaw<T>(url, null, config);
  }
}

// 兼容旧版的便捷方法
export function get<T>(url: string, data?: any): Promise<T> {
  if (url.indexOf('http') === -1) {
    url = baseUrl + url;
  }

  if (data) {
    // 处理查询参数
    if (data.params) {
      // 如果data有params属性，使用params作为查询参数
      const queryString = Object.keys(data.params)
        .filter(key => data.params[key] !== undefined && data.params[key] !== null)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data.params[key])}`)
        .join('&');
      if (queryString) {
        url += `?${queryString}`;
      }
    } else {
      // 否则直接使用data作为查询参数
      const queryString = Object.keys(data)
        .filter(key => data[key] !== undefined && data[key] !== null)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
        .join('&');
      if (queryString) {
        url += `?${queryString}`;
      }
    }
  }

  return getRaw<T>(url, null, { showError: false });
}

export function post<T>(url: string, data?: any): Promise<T> {
  if (url.indexOf('http') === -1) {
    url = baseUrl + url;
  }
  return postRaw<T>(url, data, { showError: false });
}

export function put<T>(url: string, data?: any): Promise<T> {
  if (url.indexOf('http') === -1) {
    url = baseUrl + url;
  }
  return putRaw<T>(url, data, { showError: false });
}

export function del<T>(url: string, data?: any): Promise<T> {
  if (url.indexOf('http') === -1) {
    url = baseUrl + url;
  }
  return delRaw<T>(url, data, { showError: false });
}

export default {
  request,
  get,
  post,
  put,
  del
};
