import { useUserStore } from '@/store/user'

/**
 * Tab 页 onShow：刷新登录态后调用子面板 reload（子组件无 onShow 生命周期）
 * @param {import('vue').ComponentPublicInstance} vm 页面实例
 * @param {{ refreshRole: Function, refName: string, shouldReload?: () => boolean }} options
 */
export function refreshTabPanelOnShow(vm, options) {
  const { refreshRole, refName, shouldReload = () => true } = options
  refreshRole.call(vm)

  const finish = () => {
    if (!shouldReload.call(vm)) {
      return
    }
    invokePanelReload(vm, refName)
  }

  const userStore = useUserStore()
  if (userStore.isLoggedIn() && !userStore.state.roles.length) {
    userStore
      .fetchUserInfo()
      .then(() => {
        refreshRole.call(vm)
        finish()
      })
      .catch(() => {})
    return
  }
  finish()
}

function invokePanelReload(vm, refName, retry = 0) {
  vm.$nextTick(() => {
    const panel = vm.$refs[refName]
    if (panel && typeof panel.reload === 'function') {
      panel.reload()
      return
    }
    if (retry < 8) {
      setTimeout(() => invokePanelReload(vm, refName, retry + 1), 50)
    }
  })
}
