import Store from 'store2'
import global from '../api/config'
export const state = () => ({
  pageTagsList: [],
  btnList: [],
  locales: ['en', 'cn'],
  locale: 'cn',
  // 必须用这个默认颜色，切换颜色才好用？？？
  themeColor: '#409EFF',
  msgNum: 0
})
export const actions = {
  // 服务初始化
  nuxtServerInit({ commit }, { req }) {
    process.__TOKEN__ = this.$cookies.get('uid')
  }
}
export const mutations = {
  // 设置主题
  setThemeColor(state, color) {
    state.themeColor = color
    Store('theme-color', color)
  },
  // 获取主题
  getThemeColor(state) {
    if (Store('theme-color')) {
      state.themeColor = Store('theme-color')
    }
  },
  SET_LANG(state, locale) {
    if (state.locales.indexOf(locale) !== -1) {
      state.locale = locale
    }
  },
  // 显示已添加的tags
  setOpenedList(state) {
    if (Store.session('tagPageList')) {
      state.pageTagsList = Store.session('tagPageList')
    } else {
      // 默认显示
      const tabObj = { name: global.tabName(), uri: '/' }
      state.pageTagsList = [tabObj]
      Store.session('tagPageList', state.pageTagsList)
    }
  },
  // 新增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)
      }
    })
  },
  // 存储按钮权限
  showBtnList(state, data) {
    state.btnList = data || []
  },
  // 监听消息数量的变化
  messageNumber(state, data) {
    state.msgNum = data
  },
  // 设置锁屏
  setLock(state) {
    Store.session('isLock', true)
  },
  // 清除锁屏
  clearLock(state) {
    Store.session('isLock', '')
  }
}
