import Cookies from 'js-cookie'
import { checkSSOLogin } from '../api/user'
import { isMenHu } from '@/utils/utils'

const TokenKey = process.env.VUE_APP_TOKEN_KEY
const publicPath = process.env.VUE_APP_PUBLICPATH
const key = TokenKey + publicPath
export function getToken() {
  const token = Cookies.get(key)
  if (isMenHu()) {
    // 信创的如果是chrome这种存在跨域的则使用sessionStorage
    return token || sessionStorage.getItem(key)
  } else {
    return token
  }
}

export function setToken(token) {
  // token过期时间
  const inFifteenMinutes = 2 / 24 // 2小时
  if (isMenHu()) {
    sessionStorage.setItem(key, token)// 信创门户接入
  }
  return Cookies.set(key, token, { path: publicPath, expires: inFifteenMinutes })
}

export function removeToken() {
  sessionStorage.removeItem(key)// 信创门户接入
  return Cookies.remove(key, { path: publicPath })
}

export function setSsoToken(ssoToken) {
  sessionStorage.setItem('ssoToken', ssoToken)// 信创门户接入
}
export function getSsoToken() {
  return sessionStorage.getItem('ssoToken')// 信创门户接入
}

export function getSsoToken_CK() {
  return Cookies.get('ssoToken')
}

// 单点登录
export function validateSSOToken() {
  return new Promise((resolve, reject) => {
    checkSSOLogin().then(response => {
      resolve(response.code === 0)
    }).catch(error => {
      reject(error)
    })
  })
}
