import router from '@/router/router'
import { uniqueArray } from '@/utils'

const common = {
  state: {
    homeTabs: [],
    homeTabsActiveName: '',
    comModObject: null
  },
  mutations: {
    SET_HOME_TABS: (state, homeTabs) => {
      state.homeTabs = homeTabs
    },
    SET_HOME_TABS_ACTIVE_NAME: (state, homeTabsActiveName) => {
      state.homeTabsActiveName = homeTabsActiveName
    },
    SET_COMMON_OBJECT: (state, comModObject) => {
      state.comModObject = comModObject
    }
  },
  actions: {
    setHomeTabs({ commit }, homeTabs) {
      commit('SET_HOME_TABS', homeTabs)
    },
    setHomeTabsActiveName({ commit }, homeTabsActiveName) {
      commit('SET_HOME_TABS_ACTIVE_NAME', homeTabsActiveName)
    },
    // 添加tab
    addTabs({ commit, state }, tab) {
      let homeTabs = state.homeTabs.slice()
      if (homeTabs.length === 0) {
        tab.closable = false
      } else {
        homeTabs[0].closable = false
      }
      homeTabs.push(tab)
      homeTabs = uniqueArray(homeTabs, 'name')
      commit('SET_HOME_TABS', homeTabs)
      commit('SET_HOME_TABS_ACTIVE_NAME', tab.name)
    },
    // 删除tab(单个)
    removeOneTab({ commit, state }, tabName) {
      logger.warn(tabName)
      const homeTabs = state.homeTabs.slice()
      let name
      for (let i = 0; i < homeTabs.length; i++) {
        let item = homeTabs[i]
        if (item.name === tabName) {
          homeTabs.splice(i, 1)
          item = homeTabs[i]
          if (state.tabsActiveName === tabName) {
            if (item) {
              name = item.name
            } else {
              name = homeTabs[i - 1].name
            }
            commit('SET_HOME_TABS_ACTIVE_NAME', name)
            router.push({ path: name })
          }
          break
        }
      }
      commit('SET_HOME_TABS', homeTabs)
    },

    // 删除tabs(多个)
    removeAllTabs({ commit, state }) {
      const homeTabs = state.homeTabs.slice()
      if (homeTabs.length === 0) {
        return
      }
      const firstTab = [homeTabs.shift()]
      commit('SET_HOME_TABS_ACTIVE_NAME', firstTab[0].name)
      router.push({
        path: firstTab[0].name
      })
      commit('SET_HOME_TABS', firstTab)
    },

    setCommonObjct({ commit, state }) {
      commit('SET_COMMON_OBJECT', state.comModObject)
    }
  }
}

export default common
