import qs from 'qs';
import axios from 'axios';
import Layer from '@/plugins/Layer/index';
const Cookie = process.client ? require('js-cookie') : {};
const Sentry = process.client ? require('@sentry/browser') : require('@sentry/node');
const service = axios.create({
  timeout: 1000 * 10,
  withCredentials: false,
  baseURL: process.client ? process.env.DEF_DOMAIM : `http:${process.env.DEF_DOMAIM}`,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'X-Ca-Stage': process.env.X_CA_STAGE
  }
});
// request拦截器
service.interceptors.request.use(
  config => {
    if (process.client) {
      config.headers['token'] =
        Cookie.get('token') || Cookie.get('BCC_PROGRAM_USER_LOGIN_TOKEN') || '';
    }
    const noMsg = config.headers['noMsg'] || '';
    if (config.headers.hasOwnProperty('noMsg')) {
      delete config.headers['noMsg'];
    }
    config.metadata = { noMsg };
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
// response拦截器
service.interceptors.response.use(
  res => {
    const { status, data, config } = res;
    if (status === 200) {
      const { code, errorCode, errorMessage } = data;
      if ((code !== 200 || errorCode !== 0) && code !== 0) {
        Sentry.captureException(
          new Error(`${status};${JSON.stringify(data)};${JSON.stringify(config)}`)
        );
        if (errorMessage && !config.metadata.noMsg) {
          if (process.client) {
            Layer.msg(errorMessage);
          }
        }
      }
      return Promise.resolve(data);
    } else {
      Sentry.captureException(
        new Error(`${status};${JSON.stringify(data)};${JSON.stringify(config)}`)
      );
      return Promise.reject(res);
    }
  },
  err => {
    const { message, config } = err;
    Sentry.captureException(new Error(`${message};${JSON.stringify(config)}`));
    return {
      code: 500,
      errorCode: 500,
      errorMessage: `网络错误 -${err}`
    };
  }
);

const get = (url, params, config = {}) => {
  const default_config = {
    method: 'get',
    url: url,
    params: params,
    ...config
  };
  return service(default_config);
};
const post = (url, data, config = {}) => {
  const default_config = {
    method: 'post',
    url: url,
    data: qs.stringify(data),
    ...config
  };
  return service(default_config);
};

export default {
  get,
  post,
  service
};
