import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'

let prodBaseURL = 'https://xiaoyou.dgtis.com/admin';//正式地址

// let prodBaseURL = 'https://malltest.dgtis.com/admin';//阿里云地址

let devBaseURL = 'https://malltest.dgtis.com/admin';//测试地址

// create an axios instance
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? prodBaseURL : devBaseURL,// api 的 base_url
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (getToken()) {
    config.headers['Authorization'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    let errmsg = res.errmsg;
    if (res.errno !== 0) {
      if(res.errno==503){
        MessageBox.alert('超时自动退出系统，请重新登录', '已退出', {
          confirmButtonText: '重新登录',
          type: 'error'
        }).then(() => {
            
            const prodHref = 'http://dgt.dgtis.com/oneportal/login';//正式地址

            // const prodHref = 'http://dgtcloud.dgtis.com/oneportal/login';//阿里云地址
          
            const devHref = 'http://192.168.100.208:8080/oneportal/login'; //测试地址

            location.href = process.env.NODE_ENV === 'production' ? prodHref : devHref;
        })
      }else{
        Message({
          message: errmsg,
          type: 'error',
          duration: 2 * 1000
        })
      }
      return Promise.reject('error')
    } else {
      return response
    }
  }, error => {
    console.log('err' + error)// for debug
    Message({
      message: '连接超时',
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  })

export default service
