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

const state = {
  keepAlivePages: savedPages || defaultPages,
  clickedCells: JSON.parse(sessionStorage.getItem('clickedCells')) || []
}

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))
  },
  ADD_CLICKED_CELL(state, cell) {
    state.clickedCells.some(item =>
      Object.keys(item).every(key => {
        item[key] === cell[key]
      })
    ) || (state.clickedCells.push(cell), sessionStorage.setItem('clickedCells', JSON.stringify(state.clickedCells)))
  }
}

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

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