import auth from "../utils/auth";
import settings from "../settings.js";

export const host = settings.getApiAddress();
export const base_api = host + settings.getApiService();
export const base_api_v2 = host + settings.getApi2Service();
/**
 * 组装全局Header
 * @param {*} params header
 */
function xyHeader(params) {
  if (params.header) {
    //params.header["content"] = auth.getOpenId();
    params.header["accessToken"] = auth.getToken()
  } else {
    params.header = {
      //"content": auth.getOpenId(),
      "accessToken": auth.getToken()
    }
  }
}
/**
 * GET请求
 * @param {Object} params 需传入url, data, header, complete
 */
export function get(params) {
  //xyHeader(params)
  return new Promise((resolve, reject) => {
    uni.request({
      method: 'GET',
      timeout: 60000,
      ...params,
      success: (res) => {
        if (res.data.success) {
          resolve(res.data)
        } else {
          if (res.data.msg)
            reject(res.data.msg)
          else
            reject('Request Failed')
        }
      },
      fail: (err) => {
        if (typeof err == 'string')
          reject(err)
        else
          reject('Request Failed')
      }
    })
  })
}

/**
 * POST请求
 * @param {Object} params 需传入url, data, header, success, fail, complete
 */
export function post(params) {
  //xyHeader(params)
  return new Promise((resolve, reject) => {
    uni.request({
      method: 'POST',
      timeout: 60000,
      ...params,
      success: (res) => {
        if (res.data.success) {
          resolve(res.data)
        } else {
          if (res.data.msg)
            reject(res.data.msg)
          else
            reject('Request Failed')
        }
      },
      fail: (err) => {
        console.error('vbe-request', err);
        if (typeof err == 'string')
          reject(err)
        else
          reject('Request Failed')
      }
    })
  })
}

/**
 * 上传文件
 * @param {Object} params 需传入url, files/(filePath,name), header, success, fail, complete
 */
export function upload(params) {
  //xyHeader(params)
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      ...params,
      success: (res) => {
        resolve(JSON.parse(res.data))
      },
      fail: (err) => {
        console.error('vbe-upload', err);
        if (typeof err == 'string')
          reject(err)
        else
          reject('Request Failed')
      }
    })
  })
}