import store from '@/store'
import axios from 'axios'
import { Toast } from 'vant'

console.log(process.env.HOST_URL)

const service = axios.create({
  baseURL: process.env.HOST_URL + process.env.PORT + process.env.BASE_URL,
  timeout: 300000
})

const isArray = data => Object.prototype.toString.call(data) === '[object Array]'

const showToast = (toast, data, msg) => {
  if (toast) {
    const { code, message } = data
    const isToastArray = isArray(toast)
    let needToast = (isToastArray && toast.indexOf(code) === -1) || (!isToastArray && toast)
    if (needToast) {
      Toast(message || msg)
    }
  }
}

//  拦截器 ，作用： 检查token 和 显示loading
service.interceptors.request.use((request) => {
  // const { uid, access_token } = store.getters.getUserInfo
  // if (uid) {
  //   request.headers.access_token = access_token
  // }
  const { method } = request
  const { loading = method === 'post' } = request
  if (loading && !service.isLoading) {
    service.isLoading = true
    Toast.loading({
      forbidClick: false, // 禁用背景点击
      loadingType: 'spinner',
      message: '加载中...',
      duration: -1
    })
  }
  return request
})

// 对接口请求异常的拦截
service.interceptors.response.use(
  (response) => {
    const { data, config } = response
    const { loading, toast = loading } = config

    if (loading) {
      service.isLoading = false
      Toast.clear()
    }
    // if (data.code === 12 || data.code === 10 || data.code === 21) {
    //   store.commit('logout')
    // }
    // showToast(toast, data, '内部错误')
    return data
  },
  (err) => {
    const { loading, toast = loading } = err.config
    const data = {code: 1000, message: '网络异常', data: {}}
    err.data = data
    if (loading) {
      service.isLoading = false
      Toast.clear()
    }
    showToast(toast, data, '网络异常')
    return Promise.reject(err)
  }
)

const fetch = options => service.request(options)

export default fetch
