import { addClass, removeClass } from 'element-ui/src/utils/dom'

const state = {
  dialogs: {},
  cachedDialogs: []
}

const mutations = {
  SET_DIALOG: (state, dialog) => {
    if (state.dialogs[dialog.name]) {
      state.dialogs[dialog.name].push(dialog.data)
    } else {
      state.dialogs = { ...state.dialogs, [dialog.name]: [dialog.data] }
    }
  },
  EDIT_DIALOG: (state, dialog) => {
    const index = state.dialogs.findIndex(v => v.name === dialog.name)
    state.dialogs[index].data.splice(0, 1, dialog.data)
  },
  REMOVE_DIALOG: (state, dialog) => {
    state.dialogs[dialog.name].splice(dialog.index, 1)
  },
  ADD_CACHED_DIALOG: (state, route) => {
    if (state.cachedDialogs.includes(route)) return
    state.cachedDialogs.push(route)
  },
  DEL_CACHED_DIALOG: (state, route) => {
    const index = state.cachedDialogs.indexOf(route)
    index > -1 && state.cachedDialogs.splice(index, 1)
  }
}

const actions = {
  setDialog({ commit }, dialog) {
    commit('SET_DIALOG', dialog)
  },
  editDialog({ commit }, dialog) {
    commit('EDIT_DIALOG', dialog)
  },
  removeDialog({ commit }, dialog) {
    commit('REMOVE_DIALOG', dialog)
  },
  addDialogCache({ commit }, route) {
    commit('ADD_CACHED_DIALOG', route)
  },
  delCachedDialog({ commit }, route) {
    commit('DEL_CACHED_DIALOG', route)
  },
  resetClass({ commit, state }, route) {
    removeClass(document.body, 'el-popup-parent--hidden')
    // 移除当前 class
    // 判断 route 是否已在 cached 里，如果在，增加 class
    const index = state.cachedDialogs.indexOf(route.name)
    index > -1 && addClass(document.body, 'el-popup-parent--hidden')
  }
}

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