import {
  getBreadCrumbList,
  setTagNavListInLocalstorage,
  getMenuByRouter,
  getTagNavListFromLocalstorage,
  getHomeRoute,
  getNextRoute,
  routeHasExist,
  routeEqual,
  getRouteTitleHandled,
  localSave,
  localRead
} from '@/libs/util'
import { saveErrorLogger } from '@/api/data'
import { getRouterReq } from '@/api/routers'
import router from '@/router'
import routers from '@/router/routers'
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: [],
    menuListData: [],
    hasReadErrorPage: false,
    mainv3Nav: [
      { name: '首页', path: '/mainv3', icon: 'md-home', state: true },
      { name: '工作台', path: '/workbench', icon: 'ios-book', state: false },
      { name: '收受分离', path: '/separateservice', icon: 'ios-book', state: false },
      { name: '通讯录', path: '/telnote', icon: 'md-contacts', state: false },
      { name: '知识库', path: '/knowledgebase', icon: 'md-book', state: false },
      { name: '通知公告', path: '/message', icon: 'md-megaphone', state: false },
      { name: '事项操作', path: '/itemoption', icon: 'md-book', state: false },
      { name: '统计', path: '/closingratelist', icon: 'md-calculator', state: false },
      { name: '网格一张图', path: '/grid', icon: 'md-book', state: false },
      { name: '咨询', path: '/question', icon: 'md-book', state: false },
      // { name: '代理/预约', path: '/agentreservation', icon: 'md-book', state: false },
      { name: '活动管理', path: '/activitymanagement', icon: 'md-book', state: false },
      // LA00690才显示这个，现在这个账号不再使用
      // { name: '用户信息', path: '/apply_disabled_allowance', icon: 'md-book', state: false },
      { name: '疫情防控', path: '/yi-qing/statistics', icon: 'md-book', state: false }
    ]
  },
  getters: {
    menuList1: (state, getters, rootState) => getMenuByRouter(routers, rootState.user.access),
    menuList: state => state.menuListData,
    errorCount: state => state.errorList.length
  },
  mutations: {
    setBreadCrumb (state, route) {
      state.breadCrumbList = getBreadCrumbList(route, state.homeRoute)
    },
    setMainv3Nav (state, json) {
      if (route) {
        state.mainv3Nav.push(json)
      }
    },
    setHomeRoute (state, routes) {
      state.homeRoute = getHomeRoute(routes, homeName)
    },
    setTagNavList (state, list) {
      // console.log(list, '执行app/setTagNavList')
      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)
        }
        setTagNavListInLocalstorage([...state.tagNavList])
      }
    },
    setLocal (state, lang) {
      localSave('local', lang)
      state.local = lang
    },
    addError (state, error) {
      state.errorList.push(error)
    },
    addRouterData (state, data) {
      state.menuListData = data
    },
    setHasReadErrorLoggerStatus (state, status = true) {
      state.hasReadErrorPage = status
    }
  },
  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)
      })
    },
    getAjaxRouterData ({ commit, rootState }, id) {
      getRouterReq(id).then((ret) => {
        let listData = getMenuByRouter(ret.data.data.list, rootState.user.access)
        commit('addRouterData', listData)
      })
    }
  }
}
