import axios from 'axios'
import store from '@/store'
import vm from '../main'
import { Toast } from 'vant'
import { baseApi } from '@/config'
console.log(baseApi)
// const baseUrl = ''
// const baseUrl = 'http://192.168.3.47:8090/samagg'
const service = axios.create({
  baseURL: baseApi, // 请求的接口
  timeout: 10000 // 请求超时时间
})
// loading效果
let loading
function startLoading () {
  loading = Toast.loading({
    message: '加载中...',
    forbidClick: true
  })
}

function endLoading () {
  loading.clear()
}
// 添加请求拦截器
service.interceptors.request.use((config) => {
  // 设置token，Content-Type
  console.log(config)
  var token = window.sessionStorage.getItem('token') || ''
  // token暂时写死，等待登录接口返回存储本地
  config.headers.token = token
  config.headers['Content-Type'] = 'application/json;charset=UTF-8'
  if (config.method === 'post') {
    startLoading()
  }

  return config
},
(error) => {
  return Promise.reject(error)
})
// 响应拦截器
service.interceptors.response.use(response => {
  if (response.data.code === 401) {
    vm.$dialog({
      message: '登录状态已过期，您可以继续留在该页面，或者重新登录',
      showCancelButton: true,
      confirmButtonText: '重新登录',
      cancelButtonText: '取消'
    }).then(() => {
      // 更新访问页面
      // console.log(store.state.route)
      // console.log(router)
      // let sysUser = { accessPage: store.state.route.meta.title, userName: store.state.user.name };
      // updateaccessPage(sysUser).then((res) => {
      //   console.log(res);
      // });
      vm.$router.push({ path: '/' })
      // router.push(`/login`)
    })
  } else if (response.data.code !== 200) {
    vm.$notify({
      type: 'danger',
      message: response.data.msg,
      duration: 1000
    })
  }
  if (response.config.method === 'post') {
    endLoading()
  }

  return response
}, err => {
  vm.$notify({
    type: 'danger',
    message: err.response.data.msg,
    duration: 1000
  })
  if (err.response.config.method === 'post') {
    endLoading()
  }
})
export default service
