import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Item from '@/layout/components/Sidebar/Item.vue'


axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (config.method.toUpperCase() == 'PUT') {
      config.method = 'POST'
      config.headers['X-HTTP-Method-Override'] = 'PUT'
    }
    if (config.method.toUpperCase() == 'DELETE') {
      config.method = 'POST'
      config.headers['X-HTTP-Method-Override'] = 'DELETE'
    }
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    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
    // code不为200,请求错误
    console.log(response, 'request')
    if (res.code === 200102) {
      return res
    } else
      if (res.code >= 300000) {
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })

        // 400112登录过期
        if (res.code === 400112) {
          // 重新登录
          Message.error('token过期,请重新登陆')
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        } else if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
          // to re-login
          MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
            confirmButtonText: 'Re-Login',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
        }
        return Promise.reject(new Error(res.message || 'Error'))
      } else {
        return res
      }
  },
  error => {
    let msg = ''
    let code = null
    console.log(error.response.data, 'code1')
    try {
      const { message, status_code } = error.response.data
      msg = message
      code = status_code
    } catch (e) {
      msg = error.message
    }
    console.log(code, "codecode")
    if (code) {
      switch (code) {
        case 405:
          console.log(405)
          break
        case 422:
          // 重新登录
          console.log(422)
          Message.error('token过期,请重新登陆')
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
          break
        default:
          console.log('other' + code)
      }
    } else
      if (error.response.data.code === 422001) {
        console.log("表单验证错误request")
        console.log(error.response.data.error, 'err1')
        console.log(typeof (error.response.data.error))
        let err1 = error.response.data.error
        if (err1 !== 'undefined' && Object.keys(err1).length > 0) {
          Message({
            message: error.response.data.error,
            type: 'error',
            duration: 5 * 1000
          })
        } else {
          return error.response.data
          Message({
            message: error.response.data.message,
            type: 'error',
            duration: 5 * 1000
          })
        }

      } else {
        console.log('err' + error) // for debug
        Message({
          message: msg,
          type: 'error',
          duration: 5 * 1000
        })
      }



    return Promise.reject(error)
  }
)
export default service
