import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import {VueAxios} from './axios'
import notification from 'ant-design-vue/es/notification'
import {ACCESS_TOKEN} from "@/store/mutation-types"

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_URL, // api base_url
  timeout: 600000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

const err = (error) => {
  store.commit('closeLoading')
  if (error.response) {
    let data = error.response.data
    if (data.status == SYS_CONST.REQUEST.CONTROLLER_ERROR) {
      notification.error({message: '请求失败', description: data.message})
    } else if (data.status == SYS_CONST.REQUEST.NOT_AUTHORITY) {
      notification.error({message: '权限不足', description: '当前用户无此操作权限，请联系管理员'})
    } else if (data.status == SYS_CONST.REQUEST.NOT_LOGIN) {
      gotoLogin()
    } else {
      notification.error({message: '请求失败', description: ((error.response || {}).data || {}).message || "请求出现错误，请稍后再试"})
    }
  } else {
    notification.error({message: '请求失败', description: "请求出现错误，请稍后再试"})
  }
  return Promise.reject(error)
};

// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN) || sessionStorage.getItem(ACCESS_TOKEN)
  if (config.useFullLoading != undefined && config.useFullLoading != null && config.useFullLoading == true) {
    store.commit('openLoading')
  }
  if (token) {
    config.headers['Authorization'] = token
  }
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  store.commit('closeLoading')
  if(response && response.headers && response.headers['content-type'] == 'application/octet-stream;charset=utf-8'){
    //导出时下载文件
    return response
  }
  let data = response.data
  console.info('data', 'datata', data)
  if (response.config.url.replace(response.config.baseURL, '/') != '/login') {
    // 非登录请求时
    if (data.code == SYS_CONST.REQUEST.NOT_LOGIN) {
      gotoLogin()
    } else if (data.code == SYS_CONST.REQUEST.CONTROLLER_ERROR) {
      // initModal('非常抱歉，系统刚刚发生了一个异常，异常代码为:' + data.errorCode + ',请将上述异常代码提供给系统管理员进行问题排查!', '确定');
      initModal('非常抱歉: ' + data.msg, '确定');
      return;
    } else if (data.code != SYS_CONST.REQUEST.SUCCEED) {
      initModal(data.msg, '确定');
      return;
    }
  }
  if(response.config.url.replace(response.config.baseURL, '/') == '/login') {
    if (data.code == SYS_CONST.REQUEST.NOT_LOGIN) {
      initModal(data.msg, '确定');
      return;
    }
  }
  return data
}, err)

function initModal(msg, okText, func) {
  return Vue.prototype.$error({
    title: '系统提醒',
    content: (msg),
    okText: okText,
    destroyOnClose: true,
    onOk() {
      if (func) {
        func()
      }
    }
  });
}

function toLogin() {
  store.dispatch('Logout').then(() => {
    window.location.reload()
  })
}

function gotoLogin() {
  let secondsToGo = 3;
  const modal = initModal('登录信息失效，3秒后自动跳转到登录页面', '去登陆', toLogin);
  const interval = setInterval(() => {
    secondsToGo--;
  }, 1000);
  setTimeout(() => {
    clearInterval(interval)
    toLogin()
    modal.destroy()
  }, secondsToGo * 1000);
}

const installer = {
  vm: {},
  install(Vue, router = {}) {
    Vue.use(VueAxios, router, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
