import { login } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, removeToken, removeUserInfo, setToken, setUserInfo } from '@/utils/auth'

// 处理角色权限
const formatRoles = userIdentity => {
  if (userIdentity === 1) {
    return ['admin']
  }
  if (userIdentity === 2) {
    return ['normal']
  }
  return []
}

// 角色状态
const state = {
  token: getToken(),
  name: '',
  roles: [],
  shopStatus: '',
  authUserId: '',
  userIdentity: '',
  shopType: '',
  brandId: '',
  userInfo: null,
  proxyInfo: null
}

const mutations = {
  // 重置用户信息
  SAVE_USER_INOF: (state, playload) => {
    const userInfo = playload
    state.name = userInfo.name || ''
    state.shopStatus = userInfo.shopStatus || ''
    state.authUserId = userInfo.authUserId || ''
    state.userIdentity = userInfo.userIdentity || ''
    state.shopType = userInfo.shopType || ''
    state.brandId = userInfo.brandId || ''
  },
  // 设置token
  SET_TOKEN: (state, playload) => {
    state.token = playload
  },
  // 设置用户角色
  SET_ROLES: (state, playload) => {
    state.roles = playload
  }
}

const actions = {
  // 登录操作
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return login({ mobileOrName: username.trim(), password: password })
      .then(res => {
        console.log(res)
        setToken(res.data.token)
        setUserInfo(res.data)
        commit('SAVE_USER_INOF', res.data)
        commit('SET_TOKEN', res.data.token)
        // 处理路由
      }).catch(() => {
        commit('SAVE_USER_INOF', {})
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
      })
  },
  // 获取用户角色
  getRoles({ commit, state }) {
    const roles = formatRoles(state.userIdentity)
    commit('SET_ROLES', roles)
    return roles
  },
  // 退出登录
  logout({ commit }) {
    removeToken()
    removeUserInfo()
    resetRouter()
    commit('SAVE_USER_INOF', {})
    commit('SET_TOKEN', '')
    commit('SET_ROLES', [])
  }
}

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