/*
 * @Author: your name
 * @Date: 2020-09-14 16:53:49
 * @LastEditTime: 2020-10-19 22:17:55
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /consoles_program/Users/xiawei/gdy/web-live/plugins/API/request.js
 */
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 DEF_DOMAIM = process.client
  ? process.env.DEF_DOMAIM + (window.location.protocol.split(':')[0] === 'https' ? process.env.HTTPS_PORT : process.env.HTTP_PORT)
  : `http:${process.env.DEF_DOMAIM + process.env.HTTP_PORT}`;

const service = axios.create({
  timeout: 1000 * 10,
  withCredentials: false,
  baseURL: `${DEF_DOMAIM}/v1`,
  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
};
