import Cookies from 'js-cookie'

const TokenKey = getKeyWordKey()
const host = location.hostname
const ip = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
function getCookieDomain() {
  let host = location.hostname
  if (ip.test(host) === true || host === 'localhost') return host
  const regex = /([^]*).*/
  const match = host.match(regex)
  if (typeof match !== 'undefined' && match !== null) host = match[1]
  if (typeof host !== 'undefined' && host !== null) {
    const strAry = host.split('.')
    if (strAry.length > 1) {
      host = strAry[strAry.length - 2] + '.' + strAry[strAry.length - 1]
    }
  }
  return '.' + host
}

// 获取关键字
function getKeyWordKey() {
  const origin = window.location.origin
  return origin.indexOf('online.') >= 0 ? 'dy_admin_token' : 'dy_admin_token_test'
}

export function getToken() {
  // console.log(location.origin, TokenKey)
  if (!(ip.test(host) === true) && !host === 'localhost') {
    Cookies.remove('dy_admin_token')
  }
  return Cookies.get(TokenKey, { domain: getCookieDomain() })
}


export function setToken(token) {
  if (!(ip.test(host) === true) && !host === 'localhost') {
    Cookies.remove('dy_admin_token')
  }
  return Cookies.set(TokenKey, token, { domain: getCookieDomain() })
}

export function removeToken() {
  Cookies.remove('dy_admin_token')
  return Cookies.remove(TokenKey, { domain: getCookieDomain() })
}
