import axios from 'axios'
import Promise from './promise.service.js'
import {Notice} from 'iview'
import Vue from 'vue'
import router from '../router/index.js'
import store from '../store'

var instance = axios.create({});
instance.defaults.timeout = 3600000;
instance.defaults.withCredentials = true;

instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
instance.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
let needLoadingRequestCount = 0
function startLoading() {
  store.state.loading =  true
}
function endLoading() {
  store.state.loading =  false
}
function showFullScreenLoading () {
  if (needLoadingRequestCount === 0) {
      startLoading()
  }
  needLoadingRequestCount++
}
function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
      setTimeout(() => {
        endLoading()
      }, 200)
    }
  }
let needLoading = ['resume/findListByQueryVO', 'sendMail/sendEmailTemplate', 'resume/forwardResume', 'interview/findListByQueryVO']
instance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    if (!config.headers['Content-Type']) {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }
    let url = config.url.split('api/')[1]
    let headers = config.headers
    if (headers.status!='init'&&needLoading.includes(url)){
      showFullScreenLoading()
    }
    delete headers.status
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });
instance.interceptors.response.use(function (response) {
    // 在发送请求之前做些什么
    let errorInfo = {
      '900': '您的账号已在其他地方登录，如不是您个人操作，请及时修改密码',
      '901': '',
      '902': 'cookie已失效，请重新登录'
    } 
    tryHideFullScreenLoading()
    if(response.status >= 200 && response.status < 300){
      let code = response.data&&response.data.body&&response.data.body.code || ''
      if (code == '900' || code == '901' || code == '902'){
        if (!store.state.cookieTips && code != '901') {
          store.dispatch('cookieTipsShow', true)
          Notice.error({render:(h) => {return h('div', {style: {
            paddingRight: '5px',
            fontSize: '14px',
            lineHeight: '20px',
            color: '#17233d'
          }}, errorInfo[code])}})
          setTimeout(() => {
            store.dispatch('cookieTipsHide', false)
          }, 2000)
        }
        router.replace({name: 'login'})
      }
      if(response.data.success){
        return Promise.resolve(response)
      } 
      else {
        return Promise.resolve(response);
      }
    } else {
      // return Promise.resolve(response);
    }
    return response;
  }, error => {
    tryHideFullScreenLoading()
    // Notice.error({desc:`${error.response.data.body.message}`})
  });
export default instance
// export default axios
