import axios from 'axios'
import {useToken, useStore, useConfig, useSaveTokenType, useSessionToken} from '~/store'
const $save_token_type = useSaveTokenType()
let $token
let loading_active
const post = axios.create({
  method: 'POST'
})
post.interceptors.request.use(config => {
  if ($save_token_type.value === 'local') {
    $token = useToken()
  } else {
    $token = useSessionToken()
  }
  config.headers['Authorization'] = 'Bearer ' + $token.value
  return config
}, error => Promise.reject(error))
post.interceptors.response.use(response => {
  return (response.status === 200) ? response : Promise.reject('[ERROR] response.status: ' + response.status)
}, error => Promise.reject(error))

const $config = useConfig()
export const $post = async (request, loading = false) => {
  const $store = useStore()
  if (loading) {
    $store.loading++
    if ($store.loading === 1) window.$loading().open()
  }
  const response = await post(request).catch((e) => {
    window.$message().error($config.value.api.error_message)
  })
  if (loading) {
    $store.loading--
    if ($store.loading === 0) window.$loading().close()
  }
  return !!response ? response.data : false
}
