import axios from 'axios'
import { Message } from 'element-ui'
import store from '../store'
import { MessageBox } from 'element-ui'
import { showLoading, hideLoading } from './loading'
import {getToken} from '@/utils/auth'


// import * as getters from "../store/getters";

// 创建axios实例
const service = axios.create({
  withCredentials: true,
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 1000 * 10 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    const url = process.env.BASE_API
    //config.url = config.url
    // console.log(this.$store.getters)
    config.headers['ka_token'] = getToken()
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  // response => response.data,
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data

    if ((typeof res.code === 'number' && res.code !== 200000) || (typeof res.code === 'string' && res.code !== '0000')) {
      if (res.code === 500003 || res.code === 500006 || res.code === 500007) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('logout').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        }).catch(() => {})
      } else if (res.code === 500006) {
        store.dispatch('logout').then(() => {
          Message({
            message: res.message,
            type: 'error',
            duration: 2 * 1000,
            onClose() {
              location.replace(`${location.protocol}//${location.host}/login`)
            }
          })
        })
      } else {
        Message({
          message: res.message,
          type: 'error',
          duration: 3 * 1000
        })
      }

      return Promise.reject(res.message || 'responseInterceptorsError')
    } else {
      return response.data
    }
  },
  error => {
    //console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

/* 请求拦截器（请求之前的操作） */
service.interceptors.request.use((req) => {
  showLoading()
  return req
}, err => Promise.reject(err))

/* 请求之后的操作 */
service.interceptors.response.use((res) => {
  hideLoading()
  return res
}, (err) => {
  hideLoading()
  return Promise.reject(err)
})

export default service
