import Taro from '@tarojs/taro'
import {BaseUrl, TenantId} from "@/utils/config";

let baseUrl = BaseUrl

if(process.env.NODE_ENV === 'development'){
  // baseUrl = 'http://localhost:9200/api'
}
export function request<T>(options:any) {
  const token = Taro.getStorageSync('access_token');
  const header = {
    'Content-Type': 'application/json',
    'TenantId': Taro.getStorageSync('TenantId') || TenantId
  }
  if(token){
    header['Authorization'] = token;
  }
  // 发起网络请求
  return <T>new Promise((resolve, reject) => {
    Taro.request({
      url: options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: options.header || header,
      success: (res) => {
        resolve(res.data)
      },
      fail: (err) => {
        reject(err)
      }
      // 可以添加其他Taro.request支持的参数
    })
  });
}

export function get<T>(url: string,data?: any) {
  if(url.indexOf('http') === -1){
    url = baseUrl + url
  }
  if(data){
    url = url + '?' + Object.keys(data).map(key => {
      return key + '=' + data[key]
    }).join('&')
  }
  return <T>request({
    url,
    method: 'GET'
  })
}
export function post<T>(url:string, data?:any) {
  if(url.indexOf('http') === -1){
    url = baseUrl + url
  }
  return <T>request({
    url,
    method: 'POST',
    data
  })
}

export function put<T>(url:string, data?:any) {
  if(url.indexOf('http') === -1){
    url = baseUrl + url
  }
  return <T>request({
    url,
    method: 'PUT',
    data
  })
}

export function del<T>(url:string,data?: any) {
  if(url.indexOf('http') === -1){
    url = baseUrl + url
  }
  return <T>request({
    url,
    method: 'DELETE',
    data
  })
}

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