import {baseURL,projectName,requestUrl} from '@main/config'
// import { MessageBox, Message } from 'element-ui'
import Message from '@main/components/vue-m-message'
import store from '@main/store'
import { getToken,removeToken } from '@main/utils/auth'
import axios from 'axios'
// create an axios instance
const service = axios.create({
  // withCredentials: true, //加了这个 要明确那个地址跨域才行
  baseURL: baseURL, // api的base_url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['token'] = getToken()
      config.headers['Authorization'] = "Bearer " + getToken()
    }else{
      //没有token，跳转登录页
      
      if(top.window.SysPage&&top.window.SysPage.openMiniLogin){//小窗口
        top.window.SysPage.openMiniLogin();
      }else{
        if(window.HIVUI_SETTING.loginUrl){
          location=window.HIVUI_SETTING.loginUrl;
        }else{
          location="/"+projectName+"/hivuiLogin/index.html#/";
        }
      }
    }
    
    if (config.url.indexOf('?')==-1)
      config.url = config.url+"?pn="+projectName;
    else
      config.url = config.url+"&pn="+projectName;
    return config
  }, error => {
    // Do something with request error
    Promise.reject(error)
  }
)

// respone interceptor
service.interceptors.response.use(
  //response => response,
  /**
  * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
  * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
  (response) => {
    const res = response.data;
    if (res.code !== 0) {
      return Promise.reject('error');   
    } else {
      return res;
    }
  },
  */
  response => {
    const res = response.data
    if (res.type == "application/octet-stream")
      return res;
    // if the custom code is not 20000, it is judged as an error.
    if(response.status+"" == "401" || res.status+"" =="401"){
      removeToken();
      if(top.window.SysPage&&top.window.SysPage.openMiniLogin){//小窗口
        top.window.SysPage.openMiniLogin();
      }else{
        if(window.HIVUI_SETTING.loginUrl){
          location=window.HIVUI_SETTING.loginUrl;
        }
      }
    }else if (!(response.status+"" == "200" || res.status+"" =="200")) {
      
      Message.error(res.msg || res.message || 'Error')  
      /*Message({
        message: res.msg || res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })*/

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        /*MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })*/
        if(confirm('You have been logged out, you can cancel to stay on this page, or log in again')){
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }
      }
      
      //return Promise.reject(new Error(res.message || 'Error'))
      return Promise.reject(res)
    } else {
      if(res.status+"" =="200"){
        res.dataPack = res.dataPack || res.data
        return res
      }else{
        console.error(res.msg || res.message || 'Error'); 
        Message.error(res.msg || res.message || 'Error') 
      }
    }
  },
  error => {
    if(error.response.status+"" == "401" || error.response.data.status+"" =="401"){
      removeToken();
      if(top.window.SysPage&&top.window.SysPage.openMiniLogin){//小窗口
        top.window.SysPage.openMiniLogin();
      }else{
        if(window.HIVUI_SETTING.loginUrl){
          location=window.HIVUI_SETTING.loginUrl;
        }
      }
    }else{
       Message.error(error.msg||error.message)  
    }
    console.log('err' + error) // for debug 
   
    return Promise.reject(error)
  })

export default service
