import { keepAliveRoutesPairs } from "@/constants/enumerate";
import { humpToLowLine } from "@/plugins/utils";
import Vue from "vue";

Vue.mixin({
  beforeRouteEnter(to, from, next) {
    const toName = humpToLowLine(to.name);
    next(vm => {
      const tos = keepAliveRoutesPairs.map(v => v[0]);
      if (
        tos.includes(toName) &&
        vm.$store.state.keepAliveRoutes.length === 0
      ) {
        vm.$store.commit("setRestoreKeepAliveRoutes");
      }
    });
  },
  beforeRouteLeave(to, from, next) {
    const fromName = humpToLowLine(from.name);
    const toName = humpToLowLine(to.name);
    const froms = keepAliveRoutesPairs.map(v => v[0]);
    if (
      (froms.includes(fromName) &&
        keepAliveRoutesPairs[froms.indexOf(fromName)][1].includes(toName)) ||
      (froms.includes(toName) &&
        keepAliveRoutesPairs[froms.indexOf(toName)][1].includes(fromName))
    ) {
      // 减少无谓的commit
      if (this.$store.state.keepAliveRoutes.length === 0)
        this.$store.commit("setRestoreKeepAliveRoutes");
    } else {
      if (this.$store.state.keepAliveRoutes.length > 0)
        this.$store.commit("setEmptyKeepAliveRoutes");
    }
    next();
  }
});
