import Store from 'store2'
import global from '../api/config'
export const state = () => ({
  pageTagsList: []
})
export const actions = {
  // 服务初始化
  nuxtServerInit({ commit }, { req }) {
    process.__TOKEN__ = this.$cookies.get('uid')
  }
}
export const mutations = {
  // 显示已添加的tags
  setOpenedList(state) {
    if (Store.session('tagPageList')) {
      state.pageTagsList = Store.session('tagPageList')
    } else {
      // 默认显示
      state.pageTagsList = [{ name: global.tabName(), uri: '' }]
    }
  },
  // 新增tag标签
  createTag(state, tagObj) {
    if (state.pageTagsList.length === 0) {
      // 为空时
      state.pageTagsList.push(tagObj)
      Store.session('tagPageList', state.pageTagsList)
    } else {
      let index = ''
      for (let i = 0; i < state.pageTagsList.length; i++) {
        if (tagObj.uri === state.pageTagsList[i].uri) {
          index = i
        }
      }
      if (index === '') {
        // 没有相同的tag
        state.pageTagsList.push(tagObj)
        Store.session('tagPageList', state.pageTagsList)
      }
    }
  },
  // 关闭所有tag
  clearAllTags(state) {
    if (state.pageTagsList.length > 0) {
      state.pageTagsList.splice(1)
      Store.session('tagPageList', state.pageTagsList)
    }
  },
  // 关闭其他tag
  clearOtherTags(state, vm) {
    const currentPath = vm.$route.path
    let currentIndex = ''
    for (let i = 0; i < state.pageTagsList.length; i++) {
      if (currentPath === state.pageTagsList[i].uri) {
        currentIndex = i
      }
    }

    if (currentIndex === 0) {
      state.pageTagsList.splice(1)
    } else {
      state.pageTagsList.splice(currentIndex + 1) // 关闭当前页之后的tag
      state.pageTagsList.splice(1, currentIndex - 1) // 关闭当前页之前的tag
    }
    Store.session('tagPageList', state.pageTagsList)
  },
  // 关闭当前tag
  removeTag(state, name) {
    state.pageTagsList.map((item, index) => {
      if (item.uri === name) {
        state.pageTagsList.splice(index, 1)
      }
    })
  }
}
