import md5 from "md5";

const header = {
  // "sign": true
}

function generateRandomString(length) {
  let str = Math.random().toString(36).substring(2, length + 2);
  return str;
}

window.ajaxTimeout = 20000
export default async (
  url = '',
  data = {},
  type = 'GET',
  params = {},
  headers = header,
  onUploadProgress
) => {
  type = type.toLowerCase()
  const obj = {
    method: type,
    baseURL: '',
    url: url,
    data,
    params,
    timeout: window.ajaxTimeout,
    headers,
    onUploadProgress
  }
  if (onUploadProgress && typeof onUploadProgress === 'function') {
    obj.onUploadProgress = onUploadProgress
  }
  // 请求拦截器
  axios.interceptors.request.use(
    config => {

      const noce = generateRandomString(10);
      const origin = window.location.origin;
      const timestamp = new Date().valueOf();

      config.headers.noce = noce;
      config.headers.origin = origin;
      config.headers.timestamp = timestamp;
      config.headers.sign = md5(origin + noce + timestamp);
      config.headers['web-auth'] = 1;
      return config
    },
    error => {
      // 错误抛到业务代码
      return Promise.reject(new Error('服务器异常，请联系管理员！'))
    }
  )
  // 添加响应拦截器
  axios.interceptors.response.use(
    response => {
      return response
    },
    error => {
      return Promise.reject(error.response.data)
    }
  )
  return new Promise((resolve, reject) => {
    axios(obj)
      .then(response => {
        resolve(response.data)
      })
      .catch(res => {
        reject(res)
      })
  })
}
