import { computed, onMounted, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { getClientHello } from 'services/ukeyAuth.js'
import { replaceToken } from 'services'
import { getToken, getTrxToken, getUkeyPassword } from 'utils/auth'

export default function () {
  const store = useStore()
  const router = useRouter()
  const route = useRoute()

  function init() {
    store.commit('SET_OPERATETIME')
    let lockData = localStorage.getItem('lockData')
    if (lockData) {
      lockData = JSON.parse(lockData)
      if ((lockData as any).isLock) router.push({ name: 'LockMe' })
    }
  }
  init()
  // 获取最新token
  async function getLastToken() {
    const token = getToken()
    const trxToken = getTrxToken()
    const params: any = {
      token
    }
    if (trxToken) {
      params.trxToken = trxToken
    }
    console.log('replaceToken开始, 传参:', params)
    const res = await replaceToken(params)
    console.log('replaceToken返回', res)
    if (!res.success) {
      clearTimer()
      store.dispatch('permission/ResetRoutes')
    }
  }
  const operateTime = computed(() => store.state.app.operateTime)
  const lockScreenTime = computed(() => store.getters.systemConfig.lockScreenTime)

  let timer: any = 0
  function clearTimer() {
    clearInterval(timer)
    timer = 0
  }
  onMounted(() => {
    timer = setInterval(() => {
      getLastToken()
      // 锁屏
      const interval = 1000 * 60 * Number(lockScreenTime.value)
      // checkUserStatus()
      if (interval && new Date().getTime() - operateTime.value >= interval) {
        lockScreen()
      }
      // 每 20s 在线检测 ueky 是否存在
      if (getUkeyPassword()) {
        getClientHello(getUkeyPassword()).then((checkRes: any) => {
          console.log('在线检测 ueky 是否存在, ', checkRes)
          if (checkRes.result !== 0) {
            store.dispatch('permission/ResetRoutes')
          }
        })
      }
    }, 1000 * 20)
  })
  onUnmounted(clearTimer)
  // 锁屏
  function lockScreen() {
    localStorage.setItem(
      'lockData',
      JSON.stringify({
        path: route.fullPath,
        isLock: true
      })
    )
    router.push({ name: 'LockMe' })
  }
  return {
    lockScreen
  }
}
