import { fetchMenusApi, getWardsApi, loginApi } from '@/api/login'
import router from '@/router'

const state = () => ({
  token: '', // 登录token
  sid: '', // 用户websocket id
  info: {}, // 用户信息
  wards: {}, // 病房列表
  menus: [], // 用户菜单
  routes: [], // 用户所以可访问路由
  ward: '', // 用户当前选择的病房
  paths: [], // 装载path的string数组
  flatRoutes: [] // 用户可访问路由的扁平列表
})

// getters
const getters = {
  token(state) {
    return state.token
  },
  sid(state) {
    return state.sid
  },
  info(state) {
    return state.info
  },
  wards(state) {
    return state.wards
  },
  menus(state) {
    return state.menus
  },
  routes(state) {
    return state.routes
  },
  ward(state) {
    return state.ward
  },
  pahts(state) {
    return state.paths
  },
}

// mutations
const mutations = {
  tokenChange(state, token) {
    state.token = token
  },
  closeSid(state, sid) {
    state.sid = ''
  },
  sidChange(state, sid) {
    state.sid = sid
  },
  infoChange(state, info) {
    state.info = info
  },
  wardsChange(state, wards) {
    state.wards = wards
  },
  menusChange(state, menus) {
    state.menus = menus
  },
  routesChange(state, routes) {
    state.routes = routes
  },
  wardChange(state, ward) {
    state.ward = ward
  },
  pathsChange(state, paths) {
    state.paths = paths
  },
  flatRoutesChange(state, flatRoutes) {
    state.flatRoutes = flatRoutes
  },
}

// actions
const actions = {
  // login by login.vue
  login({ commit, dispatch }, params) {
    return new Promise((resolve, reject) => {
      loginApi(params).then((res) => {
        commit('tokenChange', res.token)
        commit('sidChange', res.sid)
        commit('infoChange', res)
        dispatch('getWards').then((infoRes) => {
          resolve(res)
        })
      })
    })
  },
  // get user info after user logined
  getWards({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      getWardsApi().then((res) => {
        commit('wardsChange', res)
        dispatch('getMenus').then((menusRes) => {
          resolve(res)
        })
      })
    })
  },

  getMenus({ commit }) {
    return new Promise((resolve, reject) => {
      fetchMenusApi().then((res) => {
        commit('menusChange', res.routes)
        commit('routesChange', res.routes)
        commit('pathsChange', res.paths)
        commit('flatRoutesChange', res.flatRoutes)
        resolve(res)
      })
    })
  },

  // login out the system after user click the loginOut button
  loginOut({ commit }) {
    localStorage.clear()
    router.push('/login')
  },
}

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