import {$post} from '~/tool/axios'
import {useConfig, useSessionToken, useSaveTokenType, useToken} from "~/store";
import $router from "~/router";

const $save_token_type = useSaveTokenType()
const $session_token = useSessionToken()
const $token = useToken()
const $config = useConfig()
const admin_api = 'Admin'
export const yo = async (data) => await $post({url: `${$config.value.api.url}/api/yo`, data}, true)
export const ConfigGetAction = async (label_arr) => await $post({
  url: `${$config.value.api.url}/api/${admin_api}/Config/get`, data: {label_arr}
}, true)
export const $headers = () => {
  let $token
  if ($save_token_type.value === 'local') {
    $token = useToken()
  } else {
    $token = useSessionToken()
  }
  return {
    'Authorization': 'Bearer ' + $token.value
  }
}
export const $image = (path) => {
  const path_ret = ['http://', 'https://', ';base64,']
  for (let i = 0; i < path_ret.length; i++) {
    if (path.indexOf(path_ret[i]) !== -1) {
      return path
    }
  }
  return `${$config.value.api.url}${path}`
}
export const $base64 = (file) => {
  let reader = new FileReader()
  reader.readAsDataURL(file)
  return new Promise(resolve => (reader.onloadend = () => resolve(reader.result)))
}
export const $response = (res, then, next = false) => {
  if (res) {
    if ($config.value.api.login.indexOf(res.code) !== -1) {
      $session_token.value = null
      $token.value = null
      if (!!next) {
        next('/login')
      } else {
        $router.push('/login')
      }
    }
    if (res.code !== $config.value.api.success) return window.$message().error(res.message)
    then()
  }
}
