import axios from 'axios';
import config from '../config/index';
import errorHandle from './errorHandle';
import store from '../store/index';
import { Toast } from 'antd-mobile';

const path = config.SERVER_URL;
// 创建axios实例
const service = axios.create({
  baseURL: path, // api的base_url
  timeout: 20000,
});
// request拦截器
service.interceptors.request.use(
  conf => {
    let userId = store.getUserId();

    if (/post/.test(conf.method.toLocaleLowerCase())) {
      let data = userId
        ? {
            ...conf.data,
            userId,
          }
        : conf.data;
      conf.data = data;
    } else {
      let data = userId
        ? {
            ...conf.params,
            userId,
          }
        : conf.params;
      conf.params = data;
    }

    Toast.loading('Loading...', 99);
    conf.headers = {
      ...conf.headers,
      reqSource: 'wx',
    };
    return conf;
  },
  error => {
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;

    Toast.hide();
    /**
     * code为非1000是抛错
     */
    if (res.code !== 1000) {
      return Promise.reject(response.data);
    } else {
      return response.data;
    }
  },
  err => {
    Toast.hide();
    return errorHandle(err);
  }
);

export default service;
