import axios from 'axios'
import store from '@/store'
import storage from 'store'
import message from 'ant-design-vue/es/message'
import {
  ACCESS_TOKEN
} from '@/store/mutation-types'

// 创建 axios 实例
const request = axios.create({
  baseURL: 'http://192.168.1.88:8082/api',
  timeout: 10000, // 请求超时时间,
})

// 异常拦截处理器

const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      message.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      message.error({
        message: 'Unauthorized',
        description: '暂无权限'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
let loading
const delay = 1000
let timeout
request.interceptors.request.use(config => {
    const token = storage.get(ACCESS_TOKEN)
    if (token) {
      config.headers['token'] = token
    }
    if (timeout) {
      clearTimeout(timeout)
      timeout = null
    }
    timeout = setTimeout(() => {
      loading = message.loading({
        duration: 0, // 持续展示 toast
        message: '请求中...',
        forbidClick: true
      })
    }, delay)
    return config
  },
  err => Promise.reject(err)
)

request.interceptors.response.use((response) => {
    console.log(response)
    if (response.status == 200) {
      if (loading) {
        loading.clear()
      }
      if (timeout) {
        clearTimeout(timeout)
        timeout = null
      }
    }
    return response.data
  },
  err => {
    console.log(err.response)
    if (timeout) {
      clearTimeout(timeout)
      timeout = null
    }
    if (loading) {
      loading.clear()
    }
    return Promise.reject(err)
  }
)

//get请求
function get(url, params) {
  return service({
    method: 'get',
    url: baseURL,
    params: params,
  }).then((res) => {
    return res.data
  }).catch((error) => {
    return error
  })
}
//post请求
function post(url, param) {
  return service({
    method: 'post',
    url: baseURL,
    data: param,
    header: {
      'Content-Type': 'application/jsoncharset=UTF-8'
    }
  }).then((res) => {
    return res.data
  }).catch((error) => {
    return error
  })
}
export default request
