/*
 * @Author: Badguy
 * @Date: 2022-03-08 17:31:03
 * @LastEditTime: 2022-05-17 20:14:20
 * @LastEditors: your name
 * @Description: 页面缓存
 * have a nice day!
 */

import _ from 'lodash'

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

const mutations = {
  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)))
  },
  SAVE_PAGE(state, { name, query, fullPath }) {
    const savedPages = _.cloneDeep(state.savedPages)
    const index = savedPages.findIndex(savedPage => savedPage.name === name)
    if (index > -1) {
      savedPages[index] = { name, query, fullPath }
    } else {
      savedPages.push({ name, query, fullPath })
    }
    state.savedPages = _.cloneDeep(savedPages)
    sessionStorage.setItem('savedPages', JSON.stringify(state.savedPages))
  }
}

const actions = {
  addClickedCell({ commit }, cell) {
    commit('ADD_CLICKED_CELL', cell)
  },
  savePage({ commit }, page) {
    commit('SAVE_PAGE', page)
  }
}

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