import { getUserInfo, login, logout } from '@/api/user'
import {getToken, setToken, getUid, getUsername, setUid, setUsername, removeAll, setPubKey} from '@/utils/auth'
import { encrypt } from '@/utils/jsencrypt'
import router, { resetRouter } from '@/router'
import errorCode from '@/utils/errorCode'

const state = {
  token: getToken(),
  uid: getUid(),
  name: getUsername(),
  avatar: '',
  introduction: '',
  roles: []
}

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

const actions = {
  /**
   * 用户登录
   * @param commit
   * @param userInfo
   * @returns {Promise<unknown>}
   * @constructor
   */
  Login({ commit }, userInfo) {
    const { userName, password, code, uid, publicKey } = userInfo
    setPubKey(publicKey)
    const pwd = encrypt(password, publicKey)
    return new Promise((resolve, reject) => {
      login(userName, pwd, code, uid).then(response => {
        const { token, user } = response.data
        commit('SET_TOKEN', token)
        setToken(token)
        commit('SET_UID', user.userId)
        setUid(user.userId)
        commit('SET_NAME', user.userName)
        setUsername(user.userName)
        // commit('SET_ROLES', user.roleList)
        commit('SET_AVATAR', '')
        // commit('SET_INTRODUCTION', introduction)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    }).catch(error => {
      return Promise.reject(error)
    })
  },

  /**
   * 获取用户信息
   * @param commit
   * @param state
   * @returns {Promise<unknown>}
   */
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const params = {
        'userId': state.uid
      }
      getUserInfo(params).then(response => {
        const { data } = response
        if (!data) {
          reject(errorCode[906])
        }
        const { userId, userName, roleList } = data

        commit('SET_UID', userId)
        setUid(userId)
        commit('SET_NAME', userName)
        setUsername(userName)
        commit('SET_ROLES', roleList)
        commit('SET_AVATAR', '')
        // commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  /**
   * 用户退出登录
   * @param commit
   * @param state
   * @param dispatch
   * @returns {Promise<unknown>}
   * @constructor
   */
  Logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeAll()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

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

  /**
   * 清空用户信息
   * @param commit
   * @returns {Promise<unknown>}
   */
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeAll()
      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 })
  }
}

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