import axios from 'axios'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

import { baseUrl, proBaseUrl, mode, devToken, proToken } from '@/utils/config'

/**
 * @description axios初始化
 */
const instance = axios.create({
  baseURL: mode == 'dev' ? baseUrl : proBaseUrl,
  timeout: 100000,
  headers: {
    Authorization: mode == 'dev' ? devToken : proToken,
    'User-Type': '1',
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

const isHttpsOrHttp = (url) => {
  return /^https?:\/\//i.test(url)
}

/**
 * @description axios请求拦截器
 */
instance.interceptors.request.use(
  (config) => {
    if (isHttpsOrHttp(config.url)) {
      config.baseURL = ''
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (res) => {
    if (res.data.code == 200) {
      return res.data
    } else {
        console.error("接口请求错误："+res.data.msg)
      // ElMessage({
      //   message: res.data.msg,
      //   type: 'error'
      // })
      return Promise.reject(res.data)
    }
  },
  (err) => {
    // 对响应错误做些什么
    return Promise.reject(err.response)
  }
)

export default instance
