import Taro from '@tarojs/taro'
import getBaseUrl from './baseUrl'
import { pageToLogin } from "./utils"
import interceptors from './interceptors'

// interceptors.forEach(i => Taro.addInterceptor(i))

class httpRequest {
  baseOptions(params, method = "GET") {
    let { url, data } = params;
    const BASE_URL = getBaseUrl(url);
    let contentType = "application/x-www-form-urlencoded; charset=UTF-8;";
    contentType = params.contentType || contentType;
    let token = Taro.getStorageSync('token');
    data.token = token;
    const option = {
      url: BASE_URL + url,
      data: data,
      method: method,
      header: {
        'content-type': contentType,
        'Authorization': Taro.getStorageSync('Authorization'),
        'Accept':'application/json, text/javascript,'
      },
    };
    return Taro.request(option).then(res => {
      if(res.data.error && res.data.error.length !== 0 && res.data.error[0].field === '403'){
        Taro.setStorageSync("token", "");
        Taro.setStorageSync('userInfor', "");
        pageToLogin()
      }
      return res.data;
    })
  }

  get(url, data = "") {
    let option = { url, data };
    return this.baseOptions(option);
  }

  post(url, data, contentType) {
    let params = { url, data, contentType };
    return this.baseOptions(params, "POST");
  }

  put(url, data = "") {
    let option = { url, data };
    return this.baseOptions(option, "PUT");
  }

  delete(url, data = "") {
    let option = { url, data };
    return this.baseOptions(option, "DELETE");
  }

}

export default new httpRequest()
