import axios from 'axios'
import { showToast } from 'vant'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: import.meta.env.VITE_APP_BASE_API,
  // 超时
  timeout: 100000
})

// request拦截器
service.interceptors.request.use(config => {
  if (config.headers['Content-Type'] == 'application/json;charset=utf-8') {
    config.data.systemCode = import.meta.env.VITE_APP_SYSTEM_CODE
    if (config.requireAuth) {
      const user = JSON.parse(localStorage.getItem('user'))
      config.data.token = user.token
    }
  }
  console.log('config--->',config)
  return config
}, error => {
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
  // 未设置状态码则默认成功状态
  const code = res.data.code;
  // 获取错误信息
  const message = res.data.message
  if (code !== 1 && code !== 200) {
    showToast(message)
    return Promise.reject(message)
  } else {
    return res.data
  }
},
  error => {
    let { message, response } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    }
    else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    }
    else if (message.includes("Request failed with status code")) {
      if (response.data.code == 401) {
        errorHandlerBy401()
      } else {
        message = "系统接口" + message.substr(message.length - 3) + "异常";
      }
    }
    showToast(message)
    return Promise.reject(error)
  }
)


export default service
