import config from '@/config'
import Cookies from 'js-cookie'
const { title, cookieExpires, useI18n } = config

export const TOKEN_KEY = 'access_token'
export const TOKEN_TYPE = 'Bearer '
export const REFRESH_TOKEN_KEY = 'refresh_token'

export const setToken = (token) => {
  Cookies.set(TOKEN_KEY, token, { expires: cookieExpires || 1 })
}

export const setRefreshToken = (refresh_token) => {
  Cookies.set(REFRESH_TOKEN_KEY, refresh_token, { expires: cookieExpires || 1 })
}

export const getToken = () => {
  //先从浏览器地址取token,如果没有,那就从缓存里面取
  let token
  token = getTokenFromUrl()
  if (!token) {
    token = Cookies.get(TOKEN_KEY)
  }
  if (token) return token
  else return false
}

export const getRefreshToken = () => {
  const refresh_token = Cookies.get(REFRESH_TOKEN_KEY)
  if (refresh_token) return refresh_token
  else return false
}

/**
 * 获取{token_key:token}json格式的token
 */
export const getTokenParams = () => {
  let params = {}
  const token = Cookies.get(TOKEN_KEY)
  params[TOKEN_KEY] = token
  return params
}

/**
 * 获取登陆用户Authorization
 */
export const getTokenFromUrl = () => {
  let token, refresh_token
  let arrSource
  let paramValue = '',
    isFound = !1
  let i
  if (
    window.location.search.indexOf('?') == 0 &&
    window.location.search.indexOf('=') > 1
  ) {
    ;(arrSource = unescape(window.location.search)
      .substring(1, window.location.search.length)
      .split('&')),
      (i = 0)
    while (i < arrSource.length && !isFound)
      arrSource[i].indexOf('=') > 0 &&
        arrSource[i].split('=')[0].toLowerCase() == 'token'.toLowerCase() &&
        ((paramValue = arrSource[i].split('=')[1]), (isFound = !0)),
        i++

    token = (paramValue == '' && (paramValue = null), paramValue)
    setToken(token)
    if (arrSource.length > 1) {
      refresh_token = arrSource[1].substring(
        arrSource[1].indexOf('=') + 1,
        arrSource[1].length
      )
      setRefreshToken(refresh_token)
    }
  }
  /*if(localStorage.token == null || localStorage.token == "null"){
    window.location.href= config.logout_url;
  }*/
  return token
}
