import { keepAliveRoutesPairs } from "@/constant/constants";
import Vue from "vue";

// keepAliveRoutesPairs = [ [A, [B, C]], [D, [B]]] // mainRoute secondaryRoute
Vue.mixin({
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      const mainRoutes = keepAliveRoutesPairs.map((v) => v[0]);
      if (
        // 当进入 A 时，将 A 缓存
        mainRoutes.includes(to.name) &&
        vm.$store.state.keepAliveRoutes.length === 0
      ) {
        vm.$store.commit("setRestoreKeepAliveRoutes");
      }
    });
  },
  beforeRouteLeave(to, from, next) {
    const mainRoutes = keepAliveRoutesPairs.map((v) => v[0]);
    if (
      // 当离开 A 到 [B, C] 时，确保 A 缓存了
      (mainRoutes.includes(from.name) &&
        keepAliveRoutesPairs[mainRoutes.indexOf(from.name)][1].includes(
          to.name
        )) ||
      // 当 [B, C] 回到 A 时，确保 A 缓存了
      (mainRoutes.includes(to.name) &&
        keepAliveRoutesPairs[mainRoutes.indexOf(to.name)][1].includes(
          from.name
        ))
    ) {
      // 减少无谓的commit
      if (this.$store.state.keepAliveRoutes.length === 0)
        this.$store.commit("setRestoreKeepAliveRoutes");
    } else {
      // 其他情况的 leave 都清空缓存。至于在下个页面是否缓存，交给 beforeRouteEnter 判断
      if (this.$store.state.keepAliveRoutes.length > 0)
        this.$store.commit("setEmptyKeepAliveRoutes");
    }
    next();
  },
});
