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

// mark
var loadingInstance = null
const timeout = 60 * 1000 * 3
const Loadings = (text, time = timeout) => {
  const loading = Loading.service({
    lock: true,
    text: text || '正在处理您的操作，请稍候...',
    spinner: 'el-icon-loading',
    color: '#fff',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  setTimeout(() => {
    if (loading.visible) {
      Message.error('请求超时')
      loading.close()
    }
  }, time)
  return loading
}

// 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: 500000 // request timeout
})

const resetLogin = (res) => {
  const { code } = res.data
  if (code === '401' || code === 401) {
    // to re-login
    store.dispatch('user/resetToken').then(() => {
      setTimeout(() => {
        location.reload()
      }, 3000)
    })
  }
}

// request interceptor
service.interceptors.request.use(
  config => {
    // 处理post 请求
    if (config.data) {
      if (config.data.Loading) {
        loadingInstance = Loadings()
        if (config.data.isArray) {
          config.data = config.data.data
        }
        delete config.data.Loading
      }
    }
    // 处理get请求参数
    if (config.params) {
      if (config.params.Loading) {
        loadingInstance = Loadings()
        delete config.params.Loading
      }
    }
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    loadingInstance && loadingInstance.close()
    const res = response.data
    if (response.status === 200) {
      const isFile = Object.prototype.hasOwnProperty.call(response.headers, 'content-disposition')
      if (isFile) {
        return response
      }
      if (res.code !== '200') {
        Message({
          message: '后端异常：' + res.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
        // 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()
        //     })
        //   })
        // }
        resetLogin(res)
        return Promise.reject(new Error(res.message || 'Error'))
      } else {
        return res
      }
    } else {
      return response
    }
  },
  error => {
    loadingInstance && loadingInstance.close()
    const { msg } = error.response.data
    console.log('err' + error) // for debug
    Message({
      message: '后端异常：' + msg,
      type: 'error',
      duration: 5 * 1000
    })
    resetLogin(error.response)
    return Promise.reject(error)
  }
)

export default service
