import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'
import { getNonce } from '@/utils/utils'
// import router from '@/router'
const httpRequest = axios.create({
  timeout: 60000,
  withCredentials: true,
  headers: { 'Content-Type': 'application/json', apikey: 'McS1WsnMwMhsfc7cJ7Y0' }
})

// 请求拦截
httpRequest.interceptors.request.use(
  function(config) {
    const defaultParams = {
      timestamp: parseInt(Date.now() / 1000),
      nonce: getNonce(12),
      signature: 'UG7wBenexQhiuD2wpCwuxkU0jqcj006d'
    }
    let params = config.params || config.data
    if (config.headers['Content-Type'] === 'multipart/form-data') {
      // Object.keys(defaultParams).forEach(key => {
      //   params.append(key, defaultParams[key])
      // })
    } else {
      params = Object.assign({}, defaultParams, params)
      if (['post', 'put', 'delete'].includes(config.method)) {
        config.data = params
      } else {
        config.params = params
      }
    }
    if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  function(error) {
    return Promise.reject(error)
  }
)

// 响应拦截
httpRequest.interceptors.response.use(
  function(response) {
    const { data } = response
    if (data.code === 1 && data.msg === '请先登录') {
      // Message.error(data.msg || data.message)
      // window.location.href = `${webConf.others.loginUrl}?rd=${encodeURIComponent(window.location.href)}`
      return Promise.reject(data)
    }
    if (data.code === 403) {
      window.location.href = `${webConf.others.loginUrl}?rd=${encodeURIComponent(window.location.href)}`
    }
    return data
  },
  function(error) {
    if (error.response) {
      const { status, message, code } = error.response.data
      // 未登录
      if (status === 403) {
        window.location.href = `${webConf.others.loginUrl}?rd=${encodeURIComponent(window.location.href)}`
      } else if (status === 400 && code === 401) {
        // router.push('/role')
      } else {
        Message.error(message || error.response.data)
      }
      return Promise.reject(error.response)
    } else if (typeof error === 'string') {
      Message.error(error)
    }
    return Promise.reject(error)
  }
)

export default httpRequest
