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

let loadingRequestCount = 0
let loadingInstance

const showLoading = () => {
  if (loadingRequestCount === 0) {
    loadingInstance = Loading.service({ target: '.loadingtext'})
  }
  loadingRequestCount++
}

const hideLoading = () => {
  if (loadingRequestCount <= 0) return
  loadingRequestCount--
  if (loadingRequestCount === 0) {
    loadingInstance.close()
  }
}

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 100000
})
// request拦截器
service.interceptors.request.use(config => {
  showLoading()

  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  //config.headers['Authorization'] = 'Bearer ' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbk5hbWUiOiIxNTcxMTEzOTg5NSIsInVpZCI6NTI4MjgsImNoYW5uZWxJZCI6MCwiZXhwIjoxNjE5ODMzMzk3LCJpc3MiOiJnaW4tYmxvZyJ9.rh-WXSaFqgqY611Tm5dhba532OYEZvm06vUmgZknoy4'
  return config
}, error => {
  console.log("25reject");
  Promise.reject(error);
})

// 响应拦截器
service.interceptors.response.use(res => {
    setTimeout(() => {
      hideLoading()
    }, 200)

    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 返回所有数据的统一处理
    const data = res.data;
    // 获取错误信息
    const message = errorCode[code] || res.data.msg || errorCode['default'];
    // 200，1意味着成功返回数据
    if(code === 200 || code === 1) {
      if( res.data ) {
        return res.data
      } else {
        if( message ) {
          Message({message: message, type: 'error'});
        }else {
          Message({message: '后台数据出错啦！', type: 'error'});
        }
        return Promise.reject('error');
      }
    }
    else if( code === 500) {
      Message({
        message: message,
        type: 'error'
      })
      return Promise.reject(new Error(message));
    }
    else if(code === 401 || code == 99999) {
      MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('LogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      })
    } else if (code === 500) {
      Message({
        message: message,
        type: 'error'
      })
      return Promise.reject(new Error(message))
    } else if (code !== 200 && code !== 1) {
      Notification.error({
        title: message
      })
      return Promise.reject('error')
      store.dispatch('LogOut').then(() => {
        var ssa = window.location.host;
        // setTimeout(function (){
        if (ssa == 'localhost:1024') {
          window.location.href = 'http://sso.jxhh.com/logout?redirect=http://' + ssa
        } else {
          window.location.href = 'http://sso.jxhh.com/logout?redirect=http://' + ssa
        }
        // }, 1000)
        // location.reload() // 为了重新实例化vue-router对象 避免bug
      })
    } else if (code === 200 || code === 1 ) {
      return res.data
    }
  }, error => {
    setTimeout(() => {
      hideLoading()
    }, 200)

    // --- start ---- 开发时候用这段，把错误彻底抛出来 --- start ---
    let {message} = error;
    if (message == 'Network Error') {
      message = "后端接口连接异常";
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时';
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
      type: "error"
    });
    // console.log(message);
    // --- end ---- 开发时候用这段，把错误彻底抛出来 --- end ---

    // --- start --- 正式上线，隐藏报错信息 ----- start ----

    // let ssa = window.location.host;
    // setTimeout(function () {
    //   if (ssa == 'localhost:1024') {
    //     window.location.href = 'http://sso.jxhh.com/logout?redirect=http://' + ssa
    //   } else {
    //     window.location.href = 'http://sso.jxhh.com/logout?redirect=http://' + ssa
    //   }
    // }, 1000);

    // --- end  --- 正式上线，隐藏报错信息 ----- end ----

    return Promise.reject(error)
  }
)

export default service
