import { useCache, CACHE_KEY } from '@/hooks/web/useCache'
import { TokenType } from '@/api/login/types'
import { decrypt, encrypt } from '@/utils/jsencrypt'

const { wsCache: localCache } = useCache()
const { wsCache: sessionCache } = useCache('sessionStorage')

const AccessTokenKey = 'ACCESS_TOKEN'
const RefreshTokenKey = 'REFRESH_TOKEN'

// 获取token
export const getAccessToken = () => {
  return sessionCache.get(AccessTokenKey)
}

// 刷新token
export const getRefreshToken = () => {
  return sessionCache.get(RefreshTokenKey)
}

// 设置token
export const setToken = (token: TokenType) => {
  sessionCache.set(RefreshTokenKey, token.refreshToken)
  sessionCache.set(AccessTokenKey, token.accessToken)
}

// 删除token
export const removeToken = () => {
  sessionCache.delete(AccessTokenKey)
  sessionCache.delete(RefreshTokenKey)
  localCache.delete(AccessTokenKey)
  localCache.delete(RefreshTokenKey)
}

/** 格式化token（jwt格式） */
export const formatToken = (token: string): string => {
  return 'Bearer ' + token
}
// ========== 账号相关 ==========

export type LoginFormType = {
  tenantName: string
  username: string
  password: string
  rememberMe: boolean
}

export const getLoginForm = () => {
  const loginForm: LoginFormType = localCache.get(CACHE_KEY.LoginForm)
  if (loginForm) {
    loginForm.password = decrypt(loginForm.password) as string
  }
  return loginForm
}

export const setLoginForm = (loginForm: LoginFormType) => {
  loginForm.password = encrypt(loginForm.password) as string
  localCache.set(CACHE_KEY.LoginForm, loginForm, { exp: 30 * 24 * 60 * 60 })
}

export const removeLoginForm = () => {
  localCache.delete(CACHE_KEY.LoginForm)
}

// ========== 租户相关 ==========

export const getTenantId = () => {
  return localCache.get(CACHE_KEY.TenantId)
}

export const setTenantId = (username: string) => {
  localCache.set(CACHE_KEY.TenantId, username)
}
