import {
  getBreadCrumbList,
  setTagNavListInLocalstorage,
  setRouteListInLocalstorage,
  getMenuByRouter,
  getTagNavListFromLocalstorage,
  getHomeRoute,
  getNextRoute,
  routeHasExist,
  routeEqual,
  getRouteTitleHandled,
  localSave,
  localRead
} from '../../bc-libs/util'
//import {saveErrorLogger} from '@/api/data'
import allRoutes from '../../bc-router/routers'
import router from '../../bc-router'
import config from '@/config'

const {homeName} = config

const closePage = (state, route) => {
  const nextRoute = getNextRoute(state.tagNavList, route)
  state.tagNavList = state.tagNavList.filter(item => {
    return !routeEqual(item, route)
  })
  router.push(nextRoute)
}


export default {
  state: {
    breadCrumbList: [],
    tagNavList: [],
    homeRoute: {},
    local: localRead('local'),
    errorList: [],
    hasReadErrorPage: false,
    realRoutes: [],
    menuList: [],
    isInit: false
  },
  getters: {
    menuList: (state, getters, rootState) => {
      if (state.realRoutes.length == 0) {//初始化一下属性中的路由集合
        state.realRoutes = allRoutes;
      }
      //异步添加菜单路由
      return getMenuByRouter(state.realRoutes, rootState.user.access)
    },
    errorCount: state => state.errorList.length,
    isInit: state => state.isInit
  },
  mutations: {
    // 动态添加主界面路由，需要缓存
    updateAppRouter(state, routes) {
      if (!this.isInit) {
        state.realRoutes.push(...routes);
        for(let i of routes){
          router.addRoute(i)
        }
        this.isInit = true;
      }
      //将当前的路由集存入缓存,在浏览器刷新或突发情况下可以先取出来用
      //setRouteListInLocalstorage(routes)
    },
    // 动态添加全局路由404、500等页面，不需要缓存
    updateDefaultRouter(state, routes) {
      for(let i of routes){
        router.addRoute(i)
      }
    },
    updateMenulist(state, routes) {
      state.menuList = routes;
    },
    setBreadCrumb(state, route) {
      state.breadCrumbList = getBreadCrumbList(route, state.homeRoute)
    },
    setHomeRoute(state, routes) {
      state.homeRoute = getHomeRoute(routes, homeName)
    },
    setTagNavList(state, list) {
      let tagList = []
      if (list) {
        tagList = [...list]
      } else tagList = getTagNavListFromLocalstorage() || []
      if (tagList[0] && tagList[0].name !== homeName) tagList.shift()
      let homeTagIndex = tagList.findIndex(item => item.name === homeName)
      if (homeTagIndex > 0) {
        let homeTag = tagList.splice(homeTagIndex, 1)[0]
        tagList.unshift(homeTag)
      }
      state.tagNavList = tagList
      setTagNavListInLocalstorage([...tagList])
    },
    closeTag(state, route) {
      let tag = state.tagNavList.filter(item => routeEqual(item, route))
      route = tag[0] ? tag[0] : null
      if (!route) return
      closePage(state, route)
    },
    addTag(state, {route, type = 'unshift'}) {
      let router = getRouteTitleHandled(route)
      if (!routeHasExist(state.tagNavList, router)) {
        if (type === 'push') state.tagNavList.push(router)
        else {
          if (router.name === homeName) state.tagNavList.unshift(router)
          else state.tagNavList.splice(1, 0, router)
        }
        //console.log(state.tagNavList)
        setTagNavListInLocalstorage([...state.tagNavList])
      } else if (routeHasExist(state.tagNavList, router) && router.name === homeName) {//如果缓存已经包含首页,直接刷新缓存的tag,因为token可能不一样
        state.tagNavList.splice(0, 1, router)
      }
    },
    setLocal(state, lang) {
      localSave('local', lang)
      state.local = lang
    },
    addError(state, error) {
      state.errorList.push(error)
    },
    setHasReadErrorLoggerStatus(state, status = true) {
      state.hasReadErrorPage = status
    },
    updateIsInit(state, flag){
      this.isInit = flag
    },
  },
  actions: {
    addErrorLog({commit, rootState}, info) {
      if (!window.location.href.includes('error_logger_page')) commit('setHasReadErrorLoggerStatus', false)
      const {user: {token, userId, userName}} = rootState
      let data = {
        ...info,
        time: Date.parse(new Date()),
        token,
        userId,
        userName
      }
      /*saveErrorLogger(info).then(() => {
        commit('addError', data)
      })*/
    }
  }
}
