import axios from 'axios'
import store from '../store'

let instance = axios.create({
  baseURL: process.env.NODE_ENV === "production" ? "/" : "/lan",
  timeout: 600000,
  withCredentials: true,
})
instance.interceptors.request.use(config => {
  store.commit('initWaterMarker')
  if (!config.withoutToken && store.state.token) {
    config.headers["Authorization"] = store.state.token
  }
  return config
}, err => {
  console.error(err)
})

instance.interceptors.response.use(res => {
  if (res.data) {
    if (res.data.code) {
      if (res.data.code == 0) {
        return res.data
      } else if (res.data.code == 401) {
        store.commit("logout");
        uni.navigateTo({url: "/pages/login"})
      } else {
        console.error(res.data.msg || "请求失败!")
        return Promise.reject(res.data.msg)
      }
    } else {
      return res.data
    }
  } else {
    console.error("服务器异常,请联系管理员!")
  }
}, err => {
  console.error(err)
})

export default instance
