import request from '../utils/request'
import apis from '../config/api'

export default {
  state: {
    app: {
      logo: '',
      name: '知与行',
      version: 1.0,
    },
    menus: [],
    user: {},
    buildings: [],
  },
  mutations: {
    updateUser(state, user) {
      state.user = {
        ...state.user,
        ...user,
      }
    },
    updateBuildings(state, buildings) {
      state.buildings = buildings || []
    }
  },
  actions: {
    checkLogin({ state, commit }) {
      return new Promise((resolve, reject) => {
        if (state.user.username) {
          resolve()
          return
        }

        request(apis.system.currentUser).then((data) => {
          commit('updateUser', data)
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    login({ commit }, payload) {
      return new Promise((resolve, reject) => {
        request({
          ...apis.system.signin,
          data: payload,
        }).then((data) => {
          localStorage.setItem('x-token', data.token)
          commit('updateUser', data)
          resolve()
        }).catch((err) => {
          reject(err)
        })
      })
    },
    logout({ commit }) {
      request(apis.system.signoff).then(() => {
        localStorage.removeItem('x-token')
        commit('updateUser', {})
      })
    },
    getBuildings ({ commit }) {
      return new Promise((resolve, reject) => {
        request({
          ...apis.building.list,
          params: { pageSize: 999 },
        }).then((data) => {
          commit('updateBuildings',  data.records)
          resolve(data)
        }).catch(({ message }) => {
          if (typeof message === 'string') {
            reject(message)
          }
        })
      })
    },
  }
}
