import {
  login,
  logout,
  getMenu,
  getPermissionTreeAll
} from '@/api/user'
import { constantRoutes } from '@/router/index'
import {
  getToken,
  setToken,
  removeToken,
  getUserInfo,
  setUserInfo,
  removeUserInfo,
  setLocalMenu,
  getLocalMenu,
  removeLocalMenu,
  setLocalMenuAll,
  getLocalMenuAll,
  removeLocalMenuAll
} from '@/utils/auth'
import {
  resetRouter
} from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: getUserInfo(),
    menu: getLocalMenu(),
    allMenus: getLocalMenuAll(),//包含按钮权限的菜单表
    name: '',
    avatar: '',
    permissionTree: [],
    routerList: [], // 动态路由,
    init: false, // 是否完成初始化 // 默认未完成

  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_MENU: (state, menu) => {
    state.menu = menu
  },
  SET_ALL_MENUS: (state, allMenus) => {
    state.allMenus = allMenus
  },
  SET_PERMISSION_TREE_ALL: (state, permissionTree) => {
    state.permissionTree = permissionTree
  },
  SET_ROUTER: (state, routerList) => {
    state.routerList = routerList
  },
  set_init: (state, status) => {
    state.init = status
  },
  set_router: (state, routerList) => {
    state.routerList = routerList
  },
}

const actions = {
  // user login
  login({
    commit
  }, userInfo) {
    const {
      username,
      password,
      captcha
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password,
        captcha: captcha
      }).then(response => {
        const {
          data
        } = response
        commit('SET_TOKEN', data.accessToken)
        commit('SET_NAME', data.username)
        commit('SET_USERINFO', data)
        setToken(data.accessToken)
        setUserInfo(data)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        removeUserInfo()
        removeLocalMenu()//不含有按钮权限的
        removeLocalMenuAll()//含有按钮权限的菜单
        resetRouter()
        commit('RESET_STATE')
        window.location.reload() //刷新路由表
        resolve()
      }).catch(error => {
        console.log('err', error);
        // reject(error)
      })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

  getMenuList({
    commit
  }) {
    return new Promise((resolve, reject) => {
      getMenu().then((res) => {
        const {
          menus
        } = res.data
        let menuObj = getMenuObj(menus)
        function getMenuObj(menu) {
          let obj = {}
          traverseMenuList(menu || []);
          function traverseMenuList(arr) {
            if (arr.length > 0) {
              arr.map((item) => {
                if (item.menuName) {
                  obj[item.menuName] = true;
                }
                if (item.children) {
                  traverseMenuList(item.children);
                }
              });
            }
          }
          return obj
        }

        commit('SET_MENU', menuObj)
        setLocalMenu(menuObj)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取权限树所有
  getPermissionTreeAll({
    commit
  }) {
    return new Promise(resolve => {
      getPermissionTreeAll().then(res => {
        commit('SET_PERMISSION_TREE_ALL', res.data)
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
    })
  },

  // 动态设置路由 此为设置设置途径
  setRouterList({ commit }, routerList) {
    commit('set_router', constantRoutes.concat(routerList)) // 进行路由拼接并存储
  },
  // 设置所有菜单，这个菜单包含了按钮权限按钮，后端将含有按钮权限的数据单独放置在此，menus中不含有按钮权限数据
  setAllMenus({ commit }, allMenus) {
    commit('SET_ALL_MENUS', allMenus) // 进行路由拼接并存储
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
