import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

/**
 * 创建请求
 * @param baseURL
 */
export const createRequest = function(baseURL) {
  // create an axios instance
  const service = axios.create({
    baseURL: baseURL || process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 30000, // request timeout,
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    }
  })
  // request interceptor
  service.interceptors.request.use(
    config => {
      // do something before request is sent
      if (store.getters.token) {
        config.headers['api-token'] = store.getters.token
      }
      return config
    },
    error => {
      // do something with request error
      console.log(error) // for debug
      return Promise.reject(error)
    }
  )

  // response interceptor
  service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
      const res = response.data
      let code = 0
      let message = ''
      if (res.ret !== undefined) {
        code = res.ret
        message = res.msg
      } else {
        code = res.code
        message = res.message
      }
      // if the custom code is not 20000, it is judged as an error.
      if (code !== 0) {
        var errorStr = ''
        if (message) {
          errorStr = message
        } else {
          errorStr = typeof res === 'string' ? res : 'Error'
        }
        if (code === 401) {
          console.log('error', errorStr)
          store.dispatch('logout').then(() => {

          })
        } else {
          console.log('error', errorStr)
        }
        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
        if (code === 50008 || code === 50012 || code === 50014 || code === 500) {
          // to re-login
          store.dispatch('logout').then(() => {

          })
        }
        return Promise.reject(new Error(res.message || 'Error'))
      } else {
        return res
      }
    },
    (error) => {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
      console.log(error.config.url)
      if (error.config.url === '/api/admin/user/get-admin-user') {
        store.dispatch('logout').then(() => {
          location.reload()
        })
      }
      return Promise.reject(error)
    }
  )
  service.api = {
    get: (url) => (params, cancelToken) => {
      return service.get(url, {
        'params': params,
        'cancelToken': cancelToken
      })
    },
    post: (url) => (params, config) => {
      return service.post(url, params, config)
    },
    delete: (url) => (params) => {
      return service.delete(url, params)
    },
    link: url => url
  }
  return service
}
const service = createRequest()
export default service
