
import { computed, nextTick, onActivated, onMounted, ref } from 'vue';
import { onBeforeRouteUpdate, useRoute } from 'vue-router';
import { tagsStore } from "@/store/tags";


export default function useAlivePage(options = {}) {
  const route = useRoute();
  const current = ref()
  const routeName = ref('')
  const routePath = ref(null);
  const { removeTag, subTagClosed, unsubTagClosed } = tagsStore();

  const argName = typeof options.argName == 'string' && options.argName ? options.argName : 'id';
  const callback = typeof options.cb == 'function' && options.cb ? options.cb : () => { };
  const reset = typeof options.reset == 'function' && options.reset ? options.reset : () => { };

  function closePage() {
    removeTag(routePath.value)
  }
  onMounted(() => routeName.value = route.name)

  onActivated(() => {
    const value = route.params[argName] || '';
    if (current.value !== value) {
      current.value = value
      callback(value)
    }
    if (routePath.value !== route.fullPath) {
      if (routePath.value) unsubTagClosed(routePath.value);
      subTagClosed(route.fullPath, () => {
        routePath.value = null
        reset()
      });
      routePath.value = route.fullPath;
    }
  })

  return { current, closePage }
}