/*
 * @Author: Zp 用户模块 仓库 store
 * @Desc: 这里存储用户数据、登录操作、权限查找、设置token等功能
 * @Date: 2020-03-11 16:59:43
 * @Last Modified by: Zp
 * @Last Modified time: 2020-04-29 20:47:02
 */
import { login, checkRole, userGetRole } from 'api'
import { getToken, setToken, getUserName, setUserName, getRoleList, setRoleList, setAdmin } from 'libs/token'

export default {
  state: {
    token: getToken(),
    userName: getUserName(),
    roleList: getRoleList(),
    // 可操作权限角色数组
    access: [],
    // 判断是否存入权限角色数组
    hasAccess: false
  },
  getters: {
    userName: state => state.userName,
    access: state => state.access
  },
  mutations: {
    // 设置角色名
    setName(state, userName) {
      state.userName = userName
      setUserName(userName)
    },
    // 设置权限列表
    setRoles(state, roleList) {
      state.roleList = roleList
      setRoleList(roleList)
    },
    // 设置权限角色数组
    setAccess(state, access) {
      state.access = access
    },
    // 设置写入权限角色数组状态
    setHasAccess(state, status) {
      state.hasAccess = status
    }
  },
  actions: {
    // 登录相关动作
    login({ commit }, { phoneNum, password }) {
      return new Promise((resolve, reject) => {
        login({ phoneNum, password }).then(
          res => {
            const { data } = res
            setToken(data.token)
            setAdmin(data)
            commit('setName', data.admin.name || data.user.userName)
            resolve(res)
          }
        ).catch(error => {
          reject(error)
        })
      })
    },
    // 退出登录相关动作
    logout({ commit }) {
      return new Promise((resolve, reject) => {
        setToken('')
        commit('setHasAccess', false)
        resolve()
      })
    },
    // 获取角色相关列表
    userGetRole({ state, commit }) {
      return new Promise((resolve, reject) => {
        userGetRole().then(
          res => {
            const roleList = res.data
            commit('setRoles', JSON.stringify(roleList))
            resolve(roleList)
          }
        ).catch(error => {
          reject(error)
        })
      })
    },
    // 检查用户相关信息
    checkRole({ state, commit }) {
      return new Promise((resolve, reject) => {
        checkRole(state.token).then(
          res => {
            const access = res.data
            commit('setAccess', access)
            commit('setHasAccess', true)
            resolve({ access })
          }
        ).catch(error => {
          reject(error)
        })
      })
    }
  },
  modules: {}
}
