import axios from 'axios'
// import store from '@/store'
// import { getToken } from '@/utils/auth'
import { loginUrl } from '../config'
import { Encrypt } from '@/utils'
import { message } from 'antd';
// import router from '@/router/index.js'
// import store from '@/store/index.js'

// create an axios instance
const service = axios.create({
  baseURL: '/apis', // url = base url + request url
  timeout: 5000, // request timeout
  withCredentials: true
})

service.interceptors.request.use(
  config => {
    config.headers['secret'] = Encrypt()
    // config.retry = 2// 如果请求超时，重试次数
    // config.retryInterval = 1000 // 重试间隔
    return config
  },
  error => {
    message.error({
      content: res.msg || 'Error',
      duration: 1
    })
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    const res = response.data
    return res
    if(res.code === 200) {
      return res
    } else if (typeof res.code !== 'undefined' && res.code !== 200 && res.code !== 0) {
      message.error({
        content: res.msg || 'Error',
        duration: 1
      })
    } else if (typeof res.retCode !== 'undefined' && res.retCode !== 0) {
      message.error({
        content: res.msg || 'Error',
        duration: 1
      })
    } else {
      message.warning({
        content: '请稍后再试或联系管理员',
        duration: 1
      })
    }
    // return res
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '错误请求'
          break
        case 401:
          error.message = '未授权，请重新登录'
          break
        case 404:
          error.message = '请求错误,未找到该资源'
          break
        case 405:
          error.message = '请求方法未允许'
          break
        default:
          error.message = '服务出现异常，请稍后再试或联系管理员'
      }
      if (error.response.status !== 403) {
        // message({
        //   message: error.message,
        //   type: 'warning',
        //   duration: 5 * 1000
        // })
        message.warning({
          content: error.message,
          duration: 1
        })
      }
      if (error.response.status === 401) {
        // location.href = loginUrl
      } else if (error.response.status === 403) {
        console.log('403')
        // store.dispatch('global/setBizId', -1)
        // store.dispatch('global/setBizName', '')
        // router.push({ name: 'notAccess' })
      } else {
        message.warning({
          content: error.message,
          duration: 1
        })
      }
    }
    return Promise.reject(error)
  }
)

export default service
