
// import { getUserAuthInfo } from "@/api";
import store from "@/store/index";
// import { isPcOrH5 } from "@/utils/index";
import { computed, isRef, onBeforeMount, onBeforeUnmount, ref, watch } from "vue";

export function useHasAuth(auth) {
  const authIds = ref()
  const authorityIdList = computed(() => store.getters.authorityIdList.map(v => String(v)));
  const hasAuth = computed(() => {
    return checkAuthIds(authIds.value, authorityIdList.value)
  });

  function setAuthIds(val) {
    if (val === undefined) return;
    else if (val === null || val === '') authIds.value = []
    else if (Array.isArray(val)) authIds.value = val.map(v => String(v) || '')
    else if (typeof val === 'string') authIds.value = val.split(',').map(v => String(v) || '')
    else authIds.value = [val].map(v => String(v) || '')
  }

  onVisible(() => {
    const token = store.state.token;
    if (!token) return;
    // getUserAuthInfo({
    //   cookie: token.split("_")[0],
    //   clientType: isPcOrH5(),
    // }).then((res) => {
    //   store.commit("setAuthorityList", res.data);
    // }).catch(() => { });
  })

  if (typeof auth === 'function') {
    watch(auth, setAuthIds, { immediate: true })
  } else if (isRef(auth)) {
    watch(() => auth.value, setAuthIds, { immediate: true })
  }

  return { setAuthIds, hasAuth };
}

export function checkAuthIds(authIds, authorityIdList) {
  if (!authIds) return false;
  else if (authIds.length === 0) return true;
  else if (authorityIdList.length === 0) return false;
  return authorityIdList.some(auth => authIds.includes(auth))
}

export function onVisible(callback) {
  function handleVisibilityChange() {
    if (document.visibilityState === 'visible') {
      console.log('页面变为可见');
      callback();
    } else {
      console.log('页面变为不可见');
      // 执行页面变为不可见时的保存操作 
    }
  }

  onBeforeMount(() => {
    document.addEventListener('visibilitychange', handleVisibilityChange);
  })

  onBeforeUnmount(() => {
    document.removeEventListener('visibilitychange', handleVisibilityChange);
  })
}
