import axios from 'axios';
import qs from 'qs';
import { message } from 'element-ui';
const requestUrl = 'http://153.37.175.42:8086/'; // 测试内部接口
// const requestUrl = 'http://192.168.50.97:8082/'; // 测试内部接口
// const requestUrl = 'https://api.liebaoai.cn/'; // 统一正式接口
//创建axios实例
const service = axios.create({
  timeout: 30000 //超时时间
})

//添加request拦截器
service.interceptors.request.use(config => {
  let token = localStorage.getItem('token')
  config.headers = {
    ...config.headers,
    // 设置全局请求头
    'token': token,
    'aliasId': '',
    'platformType': 'pc',
  }
  config.params = {
    t: Date.parse(new Date()),
    ...config.params
  }
  return config;
}, error => {
  Promise.reject(error);
})

//添加response拦截器
service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      let res = {};
      res.code = response.data.code;
      res.data = response.data;
      return Promise.resolve(res.data)
    } else {
      return Promise.reject(response)
    }
  },
  error => {
    let status = error.response && error.response.status;
    switch (status) {
      case 404:
        message({
          message: error.response.data.message,
          type: 'error'
        })
        break;
      case 500:
        message({
          message: error.response.data.message,
          type: 'error'
        })
        break;
      default:
        // to do something
        break;

    }
    return Promise.reject(error.response)
  }
)

//封装get接口
// params={} 是设置默认值
export function get(url, params = {}) {
  params.t = new Date().getTime(); //get方法加一个时间参数,解决ie下可能缓存问题.
  return service({
    url: requestUrl + url,
    method: 'get',
    headers: {
      'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
    params
  })
}

//封装post请求
export function post(url, data = {}) {
  //默认配置
  let sendObject = {
    url: requestUrl + url,
    method: "post",
    data: data,
    headers: {
      'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
    }
  };
  sendObject.data = qs.stringify(sendObject.data);
  return service(sendObject)
}

//封装post请求
export function postJson(url, data = {}) {
  //默认配置
  let sendObject = {
    url: requestUrl + url,
    method: "post",
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    },
    data: data
  };
  sendObject.data = qs.parse(qs.stringify(data));
  return service(sendObject)
}
