import { login, getUserInfo } from '@/api/auth'
import {loadDepartmentList, getDepartmentAccount} from '@/api/user.js'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { authDB } from '@/db'

const state = {
  userInfo: {},
  token: authDB.get('token'),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  departments:[],
  articals: {}
}

const mutations = {
  SET_INFO: (state, user) => {
    authDB.set('userId', user.userId)
    authDB.set('nickname', user.nickname)
    state.userInfo = user
  },
  SET_TOKEN: (state, token) => {
    setToken(token)
    authDB.set('token', token)
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_DEPARTMENT( state, deparments){
    state.departments = deparments
  },
  Logout(state) {
    state.userInfo = {}
    state.token = ""
    removeToken()
    router.push({ path: '/login', replace: true })
    // window.location.reload()
  },
  APPEND_ARTICAL: (state, articals) => {
    for( let i in articals){
      let item = articals[i]
      state.articals[item.articalId] = item;
    }
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password }).then(response => {
        const { token, user } = response.data;
        commit('SET_TOKEN', token)
        commit('SET_INFO', user)
        resolve( user )
      }).catch(error => {
        console.log("catch", error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(response => {
        if (!response) {
          reject('Verification failed, please Login again.')
        }

        const { token, roles, ...userInfo } = response;
        commit('SET_TOKEN', token)
        commit('SET_INFO', userInfo)
        commit('SET_ROLES', roles)

        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    commit('SET_TOKEN', '')
    commit('SET_ROLES', [])
	commit('SET_INFO', {})
    removeToken()
    commit("Logout")
  },

  setArticals( {commit}, articals){
    commit('APPEND_ARTICAL', articals )
  },

  loadDepartment( {commit, state} ){
    let userId = authDB.get('userId')||0;
    loadDepartmentList( {userId} ).then( res=>{
      if( res.code == 200){
        commit('SET_DEPARTMENT', res.data)
      }
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}


const getters=  {
  getArticals(state) {
    return state.articals
  },
  userInfo(state){
    if( state.userInfo && state.userInfo.userId ){
      return state.userInfo;
    }
    let userId = authDB.get("userId")
    let nickname = authDB.get("nickname")
    let token = authDB.get("token")
    return {userId, nickname, token}
  },
  userDepartments(state){
    return state.departments
  },
  departmentMap(){
    let departments = {}
    for (let i in state.departments ) {
      let item = state.departments[i]
      departments[item.departmentId] = item.department;
    }
    return departments
  }
}

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