import { login, logout, getMenuList, getPermissionList, checkToken, getUserInfo } from '@/api/login/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  roles: [],
  tokenValid: false,
  userInfo: {
    departmentName: null,
    realName: null,
    loginTime: null,
    logoutTime: null,
    loginIp: null,
    mobile: null,
    roleName: null,
    userId: null,
    account: null,
    email: null,
    status: null,
    lastLoginIp: null,
    lastLoginTime: null,
    userSystemList: []
  }
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_TOKEN_VALID: (state, valid) => {
    state.tokenValid = valid
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, id, captcha } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: username.trim(), password, id, captcha: captcha.trim() }).then(response => {
        const { data, code } = response
        if (code !== 200) {
          resolve({ message: data })
        }
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then(res => {
          const {
            departmentName,
            realName,
            loginTime,
            logoutTime,
            loginIp,
            mobile,
            roleName,
            userId,
            account,
            email,
            status,
            lastLoginIp,
            lastLoginTime,
            userSystemList
          } = res.data

          const roles = roleName.split(',')
          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            reject('至少赋予用户一个角色')
          }
          commit('SET_ROLES', roles)
          commit('SET_NAME', realName)
          commit('SET_USER_INFO', {
            departmentName,
            realName,
            loginTime,
            logoutTime,
            loginIp,
            mobile,
            roleName,
            userId,
            account,
            email,
            status,
            lastLoginIp,
            lastLoginTime,
            userSystemList
          })
          resolve()
        })
        .catch(err => reject(err))
    })
  },

  getMenuList({ commit, state }) {
    return new Promise((resolve, reject) => {
      getMenuList()
        .then(res => {
          const { data } = res
          let menuList = []
          data.forEach(v => {
            menuList = menuList.concat(v.menuList)
          })
          resolve({ data: menuList })
        })
        .catch(err => reject(err))
    })
  },

  getPermissionList({ commit, state }) {
    return getPermissionList()
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout({}).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        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)
      })
    })
  },

  // 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 })

    return {}
  },

  // 检查token有效性
  checkToken({ commit }) {
    return new Promise((resolve, reject) => {
      checkToken()
        .then(res => {
          commit('SET_TOKEN_VALID', res.code === 200)
          resolve()
        })
        .catch(err => reject(err))
    })
  }
}

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