
const getDirectParentView = (route) => {
  if (!route) {
    return null
  }
  const matched = route.matched
  if (matched.length <= 1) {
    return null
  }
  return matched[matched.length - 2]
}

const state = {
  cachedViews: []
}

const mutations = {
  ADD_CACHED_VIEW: (state, [toView, fromView]) => {
    if (toView.meta.keepAlive) {
      const toViewParent = getDirectParentView(toView)
      const fromViewParent = getDirectParentView(fromView)
      if (toViewParent && fromViewParent && toViewParent.name === fromViewParent.name) {
        // 在同一个步骤流程内跳转
        if (state.cachedViews.includes(toView.name)) return
        state.cachedViews.push(toView.name)
      } else {
        // 从一个步骤流程跳转到另外一个步骤流程
        // 或从一个步骤流程跳转到非步骤流程
        state.cachedViews = [toView.name]
      }
    } else {
      state.cachedViews = []
    }
  }
}

const actions = {
  addCachedView({ commit }, toView, fromView) {
    commit('ADD_CACHED_VIEW', toView, fromView)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
