/*
 * @Author: Badguy
 * @Date: 2022-03-08 17:31:03
 * @LastEditTime: 2022-03-09 17:23:46
 * @LastEditors: your name
 * @Description: 页面缓存
 * have a nice day!
 */
const defaultPages = [{ name: 'BaggageManagement' }]
const savedPages = JSON.parse(sessionStorage.getItem('keepAlivePages'))

const state = {
  keepAlivePages: defaultPages || savedPages
}

const mutations = {
  ADD_PAGE(state, { name, fullPath }) {
    if (state.keepAlivePages.every(page => page.name !== name)) {
      state.keepAlivePages = [...state.keepAlivePages, { name, fullPath }]
    }
    sessionStorage.setItem('keepAlivePages', JSON.stringify(state.keepAlivePages))
  },
  EDIT_PAGE(state, { name, fullPath }) {
    state.keepAlivePages = state.keepAlivePages.map(page => {
      if (page.name === name) {
        page.fullPath = fullPath
      }
      return page
    })
    sessionStorage.setItem('keepAlivePages', JSON.stringify(state.keepAlivePages))
  },
  DELETE_PAGE(state, { name }) {
    const index = state.keepAlivePages.findIndex(page => page.name === name)
    if (index > -1) {
      state.keepAlivePages = state.keepAlivePages.slice(0, index + 1)
    } else {
      state.keepAlivePages = defaultPages
    }
    sessionStorage.setItem('keepAlivePages', JSON.stringify(state.keepAlivePages))
  }
}

const actions = {
  addPage({ commit }, page) {
    commit('ADD_PAGE', page)
  },
  deletePage({ commit }, page) {
    commit('DELETE_PAGE', page)
  },
  editPage({ commit }, page) {
    commit('EDIT_PAGE', page)
  }
}

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