import { TokenKey } from '@/utils/auth'
import router from './../router'
import CryptoJS from 'crypto-js'
import config from '@/config/index'

function changeToken(token) {
  if (!token) return
  const encJson = CryptoJS.AES.encrypt(JSON.stringify({ token }), config.secretKey)
  const encData = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(encJson))
  router.push('/accept?t=' + encData)
}

function listener(event) {
  const { key, newValue } = event
  switch (key) {
    case TokenKey:
      changeToken(newValue)
      break
  }
}

export const registerEvent = () => window.addEventListener('storage', listener)
