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

const $save_token_type = useSaveTokenType()
const $config = useConfig()
const app_name = 'Zero'
let url = ''
const urlPick = () => {
  if ($config.value.api.url.length > 0) {
    url = $config.value.api.url[0].url
    for (let i in $config.value.api.url) {
      if (!!$config.value.api.url[i].active) {
        url = $config.value.api.url[i].url
        break
      }
    }
  }
}
urlPick()
export const ConfigGetAction = async (data) => await $post({
  url: `${url}/api/${app_name}/Config/get?client=user`,
  data
}, true)
export const yo = async (data) => await $post({url: `${url}/api/yo`, data}, 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 `${url}${path}`
}
export const $base64 = async (file) => {
  let reader = new FileReader()
  reader.readAsDataURL(file)
  return await new Promise(resolve => (reader.onloadend = () => resolve(reader.result)))
}
export const $response = (res, then, next = false) => {
  if (res) {
    if (res.code !== $config.value.api.success_code) return window.$message().error(res.message)
    then()
  }
}
