import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Vue from 'vue'
import EventBus from '@/utils/bus'

// create an axios instance
const service = axios.create({
  baseURL: '/', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

export let isRelogin = { show: false };

let loading = {}
function startLoading(el) {
  if (!el) return
  let target = document.querySelector(el)
  if (!target || loading[el]) return
  loading[el] = Vue.prototype.$loading({
    lock: true,
    target
  })
}

function endLoading(el) {
  if (el && loading[el]) {
    loading[el].close()
    delete loading[el]
  }
}

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    startLoading(config.el)
    // config.data = json.dumps(config.data)
    config.headers.get['Content-Type'] = 'application/json'
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    } else {
      config.headers['Authorization'] = '121212'
    }
    return config
  },
  error => {
    // do something with request error
    startLoading(error.request.config.el)
    return Promise.reject(error)
  }
)

let errorShowing = false
service.interceptors.response.use(
  response => {
    console.log(response)

    let res = response.data.data ? response.data.data : response.data
    if (response.data.msg == "操作成功") {
      res = response.data
    }
    if (response.data.recordsTotal) {
      res = {
        recordsTotal: response.data.recordsTotal,
        data: res
      }
    }
    if (!response.data) {
      res = response
    }

    // if (response.data.success) {
    //   res = response.data
    // }

    let config = response.config
    endLoading(config.el)
    let resFinal = res.rsp || res || {}
    let code = resFinal.errorCode || resFinal.code
    let message = resFinal.message || resFinal.errorMsg || resFinal.error || '接口错误'
    if (code) {
      if (code === 201) {
        location.href = location.href.replace(/#.+/, '') + '#/login'
        EventBus.$emit('cancelWS')
        return
      }
      if (code === 401) {
        if (!isRelogin.show) {
          isRelogin.show = true;
          MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => {
            isRelogin.show = false;
            store.dispatch('LogOut').then(() => {
              location.href = '/web';
            })
          }).catch(() => {
            isRelogin.show = false;
          });
        }
      }
      if (code === 501) {
        // !config.silence && !errorShowing && Message.error(message)
        errorShowing = true
        setTimeout(() => { errorShowing = false }, 3000)
        store.dispatch('user/resetToken')
        EventBus.$emit('cancelWS')
        location.href = location.href.replace(/#.+/, '') + '#/login'
        return
      }
      if (code !== 200) {
        !config.silence && Message.error(message)
        return Promise.reject(new Error(message))
      }
    }
    return res
  },
  error => {
    // console.log('err' + error) // for debug
    if (error.response) {
      endLoading(error.response.config.el)
      if (!error.response.config.silence) {
        Message.error(error.message)
      }
    }
    return Promise.reject(error)
  }
)

export default service
