const config = require("../config/config.js");
class HttpBasics {
  constructor(address) {
    if (address) {
      this.address = address;
    }
  }
  /**
   * 配置
   */
  config = config;
  /**
   * 请求路径前缀 
   */
  address = config.url;
  // address ='https://ctest.malls.iformall.com/C/api';//测试
  // address ='https://c.jcwise.cn/tt/api';//生产
  /**
   * 请求头
   */
  headers = {
    "Content-Type": "application/json;charset=UTF-8",
    token: "",
    // token:"3ab2afa2-f704-4086-b6e5-ad0715c7e2a1:1027:tt-cuser"
  };
  /**
   * 设置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}`;
    return new Promise((resolve, reject) => {
      tt.request({
        url: url,
        header: headers,
        data: data,
        method: "get",
        success: res => {
          this.responseMap(res, resolve, reject);
        }, 
        fail: err => {
          console.log(err)
          if (err.errMsg == 'request:fail timeout') {
            err.errMsg = '请求超时，请检查您的网络设置！'
          } else if (err.errMsg == 'request:fail'){
            err.errMsg = '未检查到您的网络，请检查您的网络设置！'
          } else if (err.errMsg == 'request:fail request connect error') {
            err.errMsg = '连接失败'
          } 
          reject(err);
        }
      });
    });
  }
  /**
   * 提交数据
   * @param {url,data,headers} param0
   */
  post({ url, data, headers }) {
    headers = { ...this.headers, ...headers };
    url = `${this.address}${url}`;
    return new Promise((resolve, reject) => {
      tt.request({
        url: url,
        header: headers,
        data: data,
        method: "post",
        success: res => {
          this.responseMap(res, resolve, reject);
        },
        fail: err => {
          if (err.errMsg == 'request:fail timeout') {
            err.errMsg = '请求超时，请检查您的网络设置！'
          } else if (err.errMsg == 'request:fail') {
            err.errMsg = '未检查到您的网络，请检查您的网络设置！'
          } else if (err.errMsg == 'request:fail request connect error') {
            err.errMsg = '连接失败'
          } 
          reject(err);
        },
        complete: res => {}
      });
    });
  }
  /**
   * 过滤 请求信息 
   * @param {*} res
   * @param {*} resolve
   * @param {*} reject
   */
  responseMap = (res, resolve, reject) => {
    // 网络状态码200
    if (res.statusCode == 200) {
      // 服务器code 200 成功
      if (res.data.code == 200) {
        resolve(res.data);
      } else if (res.data.code == 1052) {
        tt.reLaunch({
          url: '/pages/index/index'
        })
      } else {
        reject(res.data);
      }
    } else {
      console.log("请求出错：", res);
      reject(res.data);
    }
  };
  /** 日志 */
  log(url, body, headers) {}
}
module.exports = new HttpBasics();
