import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import Router from'@/router'
import {cookGetToken, getToken, removeAllToken, setToken} from '@/utils/auth'
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) {
    return qs.stringify(data)
  }]
})
service.interceptors.request.use(
  config => {
    if(getToken()){
      config.headers['A-TOKEN'] = getToken()
    }else if (store.getters.token) {
      config.headers['A-TOKEN'] = cookGetToken()
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

var bool = true// 五秒执行一次变量
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 401) {
      store.dispatch('LogOut');
      window.location.href = process.env.BASE_API//直接重新授权
      return Promise.reject('error')
    } else if (res.code === 0) {
      if (res.msg == '') {
        return
      }
      if (bool) {
        Message({
          message: res.msg,
          duration: 1 * 3000,
        })
        bool = false
        setTimeout(() => {
          bool = true
        }, 5000)
      } else {
      }
      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){
        localStorage.clear()
        sessionStorage.clear()
        Router.push({
          path: '/noAccess',
          query: {
            msg: res.msg
          }
        })

        // console.log(store.state)

        // store.state.user.pastDue = true
        // localStorage.clear()
        // sessionStorage.clear()
        // removeAllToken()
        // Router.push({
        //   path: '/login'
        // })
        return Promise.reject('error')
    } else {
      // console.log('setToken')
      // console.log(res.refresh_token)
      // if(res.refresh_token && res.code == 1){
      //   console.log('公司Token'+moment().format('YYYY-MM-DD  HH:mm:ss'))
      //   console.log(res.refresh_token)
      //   setToken(res.refresh_token);
      // }
      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('不执行')
    }
    return Promise.reject(error)
  }
)
// export default service

// 接口再次封装
var CancelToken = axios.CancelToken; //中断请求
Vue.$httpRequestList=[];
export default (type, url, data,versions,Content_Type,transform) => {
  var Accept,Token,ContentType,transformRequest='';
  switch(versions){
    case '':
      Accept='application/json, text/plain, */*'
      break;
    case undefined:
      Accept='application/json, text/plain, */*'
      break;
     case 'v2':
       Accept='application/vnd.test.v2+json'
       break;
     case 'v3':
       Accept='application/vnd.test.v3+json'
       break;
     case 'v4':
       Accept='application/vnd.test.v4+json'
       break;
  };
  if(Content_Type == '' || Content_Type == undefined){
    ContentType='application/x-www-form-urlencoded'
  }else{
    ContentType=Content_Type
  }
  if(transform){
    transformRequest = transform
  }
	return new Promise((resolve, reject) => {   //封装ajax
		    var aa = {
		        method: type,
		        url: url,
            headers:{
              'Accept':Accept,
              'Content-Type':ContentType
            },
		        cancelToken: new CancelToken(c => {  //强行中断请求要用到的
		            Vue.$httpRequestList.push(c);
		        })
		    }
        var json = (type == 'get') ? Object.assign(aa, { params: data },transformRequest) : Object.assign(aa, { data: data },transformRequest);
        // console.log(json)
		    var ajax = service(json).then(res => {
		        resolve(res);
		    }).catch(error => {   //中断请求和请求出错的处理
            if (error.message == "interrupt") {
                return;
            } else {
                reject(error);
            }
        })
		    return ajax;
		})
};

