import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import { removeToken } from '@/utils/auth'
import store from '@/store'
import qs from 'qs'
import Vue from 'vue'
// import moment from 'moment' // 时间库
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url  https://intesys.cms.g107.com
  timeout: 10000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  transformRequest: [function(data) {
    // 对 data 进行任意转换处理
    return qs.stringify(data)
  }]
})
// request interceptor
service.interceptors.request.use(
  config => {
    if (localStorage.getItem('user_token_temp')) {
      config.headers['A-TOKEN'] = localStorage.getItem('user_token_temp')
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)
var bool = true// 五秒执行一次变量
// respone interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 401) {
      // 50008:非法的token; 50012:其他客户端登录了;  401:Token 过期了; 2000 考勤系统的token过期
      MessageBox.confirm('当前登录授权时间已经过期，请重新授权登录', '确定登出', {
        confirmButtonText: '重新登录',
        showClose: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        showCancelButton: false,
        type: 'warning'
      }).then(() => {
        store.dispatch('LogOut')
      }).catch(() => {
        store.dispatch('LogOut')
      })
      return Promise.reject('error')
    } else if (res.code === 0) {
      if (res.msg == '') {
        return
      }
      Message({
        message: res.msg
      })
      return Promise.reject('error')
    } else if (res.code === 2001) {
      Message({
        message: res.msg
      })
      return Promise.reject('error')
    } else if (res.code === 999) {
      Message({
        message: res.msg
      })
      return Promise.reject('error')
    } else if (res.code === 3000) {
      Message({
        // message: '服务暂时不可用，请稍后重试，或联系客服',
        message: res.msg
      })
      return Promise.reject('error')
    } else if(res.code === 4444){
      store.state.user.pastDue = true
      localStorage.clear()
      sessionStorage.clear()
      removeAllToken()
      Router.push({
        path: '/login'
      })
      return Promise.reject('error')
    } else {
      return response
    }
  },
  error => {
    console.log('错误'+JSON.stringify(error))
    if(error.message=='interrupt'){//是强制中断请求就拦截报错
    	return Promise.reject(error)
    }
    // 五秒内只执行一次
    if (bool) {
      Message({
        message: error.message == 'timeout of 10000ms exceeded' ? '请求服务器超时，请稍后重试' : '请求网络错误，请稍后重试',
        duration: 1 * 2000,
        type: 'error'
      })
      bool = false
      setTimeout(() => {
        bool = true
      }, 5000)
    } else {
      console.log('不执行')
    }
  }
)
export default service
