import axios from 'axios'
import qs from 'qs'
import user from '@/state/user'
import { getApp } from '@/app'
import { openLoading, closeLoading } from './loading'
import { openErrorMsg } from './errorMsg'
import { fromUrls, fileUrls, GetUrls, PostUrls, notLoginUrls } from './config'

const gotoLoginCodes = [3004]

axios.defaults.baseURL = process.env.VUE_APP_PREFIX

axios.interceptors.request.use(async config => {
  const app = getApp()

  if (!user.value.token && !~notLoginUrls.indexOf(config.url)) {
    app.$router.replace({name: 'login'})
    throw '用户未登录'
  }

  config.headers.token = user.value.token
  config.headers.userid = user.value.info.id


  if (~GetUrls.indexOf(config.url)) {
    config.method = 'GET'
  } else if (~PostUrls.indexOf(config.url)) {
    config.method = 'POST'
    if (!config.data && config.params) {
      config.data = config.params 
    }
  }

  // 处理需要用表单上传的请求
  if (~fromUrls.indexOf(config.url)) {

    config.data = qs.stringify(config.data)
    config.headers['Content-Type'] = "application/x-www-form-urlencoded; charset=utf-8;"

  } else if (~fileUrls.indexOf(config.url)) {
    const fromData = new FormData()

    Object.keys(config.data).forEach(key => {
      fromData.append(key, config.data[key])
    })
    config.data = fromData
    config.headers['Content-Type'] = "multipart/form-data"
  }

  openLoading(config.url)
  return config
})

const resInterceptor = res => {
  const app = getApp()
  
  closeLoading()

  if (res.data.code !== 0 && res.data.code !== "000000") {
    let errMsg = res.data.msg || res.data.message
    openErrorMsg(errMsg)

    if (~gotoLoginCodes.indexOf(res.data.code) || errMsg === 'token已经失效，请重新登录') {
      app.$router.replace({name: 'login'})
      user.value.token = ''
    }
    throw res.data.msg
  }
  
  return res.data
}

axios.interceptors.response.use(resInterceptor, (error) => {
  closeLoading()
  if (error.response && error.response.data) {
    return resInterceptor(error.response)
  } else {
    openErrorMsg(typeof error === 'string' ? error : '请求失败，服务端发生了点小故障！')
    return Promise.reject(error);
  }
  
})

