import { login, logout } from '@/api/admin'
import { getToken, setToken, removeToken, getAvatar, setAvatar, removeAvatar, setName, setId, getId, removeId, getName, removeName } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { Message } from 'element-ui'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  id: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      let params = {
        username: username.trim(),
        password: password
      }
      login(params).then(response => {
        const { data } = response
        if (data.code === 200) {
          localStorage.removeItem('count')
          setToken(data.data.token)
          setName(data.data.adminInfoVo.nickName)
          setAvatar(data.data.adminInfoVo.avatar)
          setId(data.data.adminInfoVo.id)
          Message({
            message: '登录成功',
            type: "success",
            duration: 3000,
          });
        } else if (data.code === 505) {
          Message({
            message: data.msg,
            type: "error",
            duration: 3000,
          });
        }else{
          Message({
            message: data.msg,
            type: "error",
            duration: 3000,
          });
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const data = {
        roles: ['admin'],
        token: getToken(),
        nickName: getName(),
        id: getId(),
        avatar: getAvatar()
      }
      // roles must be a non-empty array
      if (!data.roles || data.roles.length <= 0) {
        reject('没有权限')
      }
      commit('SET_TOKEN', data.token)
      commit('SET_ROLES', data.roles)
      commit('SET_NAME', data.nickName)
      commit('SET_AVATAR', data.avatar)
      commit('SET_ID', data.id)
      resolve(data)
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then((response) => {
        console.log(response.data)
        if (response.data.code === 200) {
          removeId()
          removeName()
          removeToken()
          resetRouter()
          removeAvatar()
          // reset visited views and cached views
          dispatch('tagsView/delAllViews', null, { root: true })
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 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 = getToken()

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

    const { roles } = await dispatch('getInfo')
    console.log('sb')
    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 })
  }
}

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