import { lst } from './index'

const _instance = window.axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL,
  timeout: 100000
})

_instance.interceptors.request.use(
  (config) => {
    const _token = lst.get('token')
    _token && (config.headers.Authorization = _token)

    if (config.formData) {
      config.headers['Content-Type'] = 'multipart/form-data;'
      config.data = new FormData()
      for (const k in config.formData) config.data.append(k, config.formData[k])
    }

    return config
  },
  (e) => {
    throw e
  }
)

_instance.interceptors.response.use(
  ({ data, status, config }) => {
    if ([201, 200].includes(status) && (data.code === 0 || config.noCatch)) return data
    throw new Error(data.msg)
  },
  (e) => {
    throw e
  }
)

/**
 * @param {Object} option 选项
 * @param {string} option.url 请求地址
 * @param {string} option.headers 请求头
 * @param {{}} option.params URL 参数
 * @param {{}} option.data body 参数
 * @param {{}} option.formData FormData 对象参数
 * @param {'get'|'post'|'patch'|'delete'} option.method
 */
export default async (option) => {
  try {
    return await _instance(option)
  } catch (err) {
    let _msg
    if (err.response) {
      if (err.response.data.code === 401) {
        lst.clear()
        location.href = '/'
      }
      _msg = err.response.data.msg
    }

    if (!option.noNotify) {
      window.ELEMENT.Message.error(_msg || err.message || '系统繁忙，请稍后再试！')
    }
    throw new Error(_msg || err)
  }
}
