import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
// @ts-ignore
import createMutationsSharer, { LocalStorageStratery } from 'vuex-shared-mutations'
import { sdSessionStorage } from '../services/storage-service'
import dispatchActionForAllModules from './dispatch-action-for-all-modules'

import modules from './modules'
import { state } from './root'

// 身份隔离
// 通过window.open打开的tab页，保持同一个id；用户手动打开的tab页，用不同的id
let windowId = sdSessionStorage.getItem('windowId')
if (!windowId) {
  windowId = Math.random().toString()
  sdSessionStorage.setItem('windowId', windowId)
}

Vue.use(Vuex)

const store = new Vuex.Store({
  state,
  modules,
  // 数据持久化到 sessionStorage，页面刷新时能留存
  plugins: [
    // eslint-disable-next-line no-restricted-globals
    createPersistedState({ storage: sessionStorage }),
    // 多个tab页同步vuex state
    createMutationsSharer({
      predicate: [
        'sd/login/setTokens',
        'sd/common/setUserInfo',
        'sd/common/setUserPerms',
        'sd/common/clearUserInfo',
        'sd/common/clearUserPerms',
      ],
      strategy: new LocalStorageStratery({ key: windowId }),
    }),
  ],
  // 直接写 store 时发出警告
  // https://vuex.vuejs.org/guide/strict.html
  strict: process.env.NODE_ENV !== 'production',
})

export default store

// 触发通知所有模块的init action
dispatchActionForAllModules('init')
