import axios from 'axios'
import { Message } from 'element-ui'

const httpRequest = axios.create({
  timeout: 60000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
// 请求拦截
httpRequest.interceptors.request.use(
  function (config) {
    // 权限接口单独签名
    // https://gitlab.ezijing.com/root/api-documents/-/blob/master/ezijing_permissions/%E7%AD%BE%E5%90%8D%E9%AA%8C%E8%AF%81.md
    if (config.url && /^\/api\/[meta|msg]/.test(config.url)) {
      // 默认参数
      const defaultHeaders = {
        timestamp: Date.now(),
        nonce: Math.random().toString(36).slice(-8),
        signature: 'UG7wBenexQhiuD2wpCwuxkU0jqcj006d'
      }
      // config.headers = Object.assign(config.headers, defaultHeaders)
      config.params = Object.assign(config.params || {}, defaultHeaders)
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截
httpRequest.interceptors.response.use(
  function (response) {
    const { data } = response
    if (data.code === 1) {
      Message.error(data.message || data.msg)
      return Promise.reject(data)
    }
    return data
  },
  function (error) {
    if (error.response) {
      const { status, message } = error.response.data
      Message.error(message || error.message)
      console.error(`${status}: ${message}`)
    } else {
      console.log(error)
    }
    return Promise.reject(error.response || error)
  }
)

export default httpRequest
