const config = require("../config/config.js");
class HttpBasics {
  constructor(address) {
    if (address) {
      this.address = address;
    }
  }
  /**
   * 配置
   */
  config = config;
  /**
   * 请求路径前缀
   */
  address = config.url;
  /**
   * 请求头
   */
  headers = {
    "Content-Type": "application/json;charset=UTF-8",
    token: ""
  };
  /**
   * 设置token
   * @param {*} token
   */
  setToken(token) {
    this.headers.token = token;
  }
  /**
   * 获取数据
   * @param {url,data,headers} param0
   */
  get({ url, data, headers }) {
    headers = { ...this.headers, ...headers };
    url = `${this.address}${url}`;
    // wx.showLoading({
    //     title: 'loading...',
    // })
    return new Promise((resolve, reject) => {
      wx.request({
        url: url,
        header: headers,
        data: data,
        method: "Get",
        success: res => {
          // wx.hideLoading();
          this.responseMap(res, resolve, reject);
        },
        fail: err => {
          // wx.hideLoading();
          reject(err);
        },
        complete: res => {}
      });
    });
  }
  /**
   * 提交数据
   * @param {url,data,headers} param0
   */
  post({ url, data, headers }) {
    headers = { ...this.headers, ...headers };
    url = `${this.address}${url}`;
    // wx.showLoading({
    //     title: 'loading...',
    // })
    return new Promise((resolve, reject) => {
      wx.request({
        url: url,
        header: headers,
        data: data,
        method: "POST",
        success: res => {
          wx.hideLoading();
          this.responseMap(res, resolve, reject);
        },
        fail: err => {
          // wx.hideLoading();
          reject(err);
        },
        complete: res => {}
      });
    });
  }
  /**
   * 过滤 请求信息
   * @param {*} res
   * @param {*} resolve
   * @param {*} reject
   */
  responseMap = (res, resolve, reject) => {
    console.log(res);
    // 网络状态码200
    if (res.statusCode == 200) {
      // 服务器code 200 成功
      if (res.data.code == 200) {
        resolve(res.data);
      } else {
        // wx.hideLoading();
        // wx.showToast({
        //   title: res.data.message,
        //   image:'./../../assets/img/fail.png'
        // });
        reject(res.data);
      }
    } 
    else {
      console.log("请求出错：", res);
      reject(res.data);
    }
  };
  /** 日志 */
  log(url, body, headers) {}
}
module.exports = new HttpBasics();
