import config from '@/config'
import Cookies from 'js-cookie'
import CONSTANT from '../bc-config/constant'
import store from '../bc-store'

const { title, cookieExpires, useI18n } = config

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

var userAgent = navigator.userAgent.toLowerCase()
let isApp=false
 if (userAgent.indexOf('electron/') > -1){
  isApp=true
 }

export const setToken = (token) => {
  //获取token的有效状态
  let token_flag = sessionStorage.getItem(token) || true
  //只要没有被标记为无效的token,默认状态都是有效
  sessionStorage.setItem(token, token_flag)
  Cookies.set(TOKEN_KEY, token, { expires: cookieExpires || 1 })
  //Cookies.set(CONSTANT.TOKEN_START_TIME_KEY,new Date().getTime(),1)
}

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

export const getToken = () => {
  if(isApp&&store){
    if(store.state.user.accessToken==''){
      return false
    } else {
      return store.state.user.accessToken // 如果是桌面应用，直接返回token
    }
  }
  //先从浏览器地址取token,如果没有,那就从缓存里面取
  let token
  token = getTokenFromUrl()
  //获取token的有效状态
  let token_flag = sessionStorage.getItem(token)
  if (!token || !token_flag) {//如果token不存在或者token是无效的.就从缓存中取
    token = Cookies.get(TOKEN_KEY)
    if(!token){
      token = sessionStorage.getItem(TOKEN_KEY)
    }
  }
  //获取token的有效状态
  token_flag = sessionStorage.getItem(token)
  if (token && token_flag) {
    return token
  } else {
    return false
  }
}

/**
 * 刷新token.根据refresh_token来操作
 * @returns {boolean|*}
 */
/*export const refreshToken = () => {
  //判断token的起始时间,超过在2小时上的token,进行刷新更换,保证token剩余时间不小于2小时,
  let token_start_time = Cookies.get(CONSTANT.TOKEN_START_TIME_KEY)

  if (new Date().getTime() - token_start_time > 2*3600*1000){
    const refresh_token = Cookies.get(REFRESH_TOKEN_KEY)
    getNewToken(refresh_token).then(response => {
      setToken(response.access_token);
    }).catch(err => {
      store._vm.$Message.warning("自动刷新token失败,登录到期后请重新登录!")
      reject(err)
    })
  }else {//如果不需要刷新,就直接返回

  }
  return true
}*/

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 = getToken()
  params[TOKEN_KEY] = token
  return params
}

/**
 * 获取登陆用户Authorization
 */
export const getTokenFromUrl = () => {
  let token, refresh_token
  let arrSource
  let tokenValue = '', 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*/) {
      if (arrSource[i].indexOf('=') > 0) {
        let paramName = arrSource[i].split('=')[0]
        let paramValue = arrSource[i].split('=')[1]
        if (paramName.toLowerCase() === 'token') {//token就赋值
          tokenValue = paramValue
          //isFound = !0
        }else {//非token就当普通参数处理
          Cookies.set(paramName,paramValue,{ expires: cookieExpires || 1 });
        }
      }
      i++
    }

    token = (tokenValue == '' && (tokenValue = null), tokenValue)
    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
}
