"use strict";
const common_vendor = require("./vendor.js");
const config = require("../config.js");
const getDomain = (uri, method, type) => {
  let serverUrl = config.configInfo.serverUrl;
  let serverFile = config.configInfo.serverFile;
  if (type && type == "file")
    return serverFile + `/files` + uri;
  else
    return serverUrl + "/learn/api/" + uri;
};
const requestBase = async (uri, method = "GET", data, type) => {
  let baseUrl = getDomain(uri, method, type);
  let header = {};
  const token = common_vendor.index.getStorageSync("token");
  if (token)
    header.token = token;
  return new Promise((resolve, reject) => {
    common_vendor.index.request({
      url: baseUrl,
      method: method || "GET",
      data: data || {},
      header,
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        common_vendor.index.showToast({
          title: "请求接口失败",
          icon: "fail"
        });
        reject(err.data);
      }
    });
  });
};
const requestApp = async (uri, method = "GET", data, type) => {
  let baseUrl = `https://120.48.146.1${uri}`;
  return new Promise((resolve, reject) => {
    common_vendor.index.request({
      url: baseUrl,
      method: method || "GET",
      data: data || {},
      header: {},
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        common_vendor.index.showToast({
          title: "请求接口失败",
          icon: "fail"
        });
        reject(err.data);
      }
    });
  });
};
const requestFile = (uri, method, data, type) => {
  let serverFile = config.configInfo.serverFile;
  let baseUrl = getDomain(uri, method, type);
  return new Promise((resolve, reject) => {
    common_vendor.index.uploadFile({
      url: baseUrl,
      filePath: data,
      name: method || "file",
      formData: {},
      success: (res) => {
        let data2 = JSON.parse(res.data);
        if (data2.errcode != "0") {
          return common_vendor.index.showToast({
            title: data2.errmsg,
            icon: "error"
          });
        }
        data2.url = serverFile + data2.uri;
        resolve(data2);
      },
      fail: (err) => {
        let data2 = JSON.parse(err.data);
        common_vendor.index.showToast({
          title: "请求接口失败",
          icon: "fail"
        });
        reject(data2);
      }
    });
  });
};
exports.requestApp = requestApp;
exports.requestBase = requestBase;
exports.requestFile = requestFile;
