import { login } from '@/api/user'
import { getToken, setToken, removeToken, setUser, getUser, removeUser } from '@/utils/auth'
import { resetRouter } from '@/router'
const userInfo = getUser() && JSON.parse(getUser())

function formatRoles(userIdentity) {
  let roles = []
  switch (userIdentity) {
    case 1:
      roles = ['admin']
      break
    case 2:
      roles = ['normal']
      break
    default:
      roles = []
      break
  }
  return roles
}

const state = {
  token: getToken(),
  name: userInfo?.name || '',
  roles: formatRoles(userInfo?.userIdentity),
  shopStatus: userInfo?.shopStatus || '',
  authUserId: userInfo?.authUserId || '',
  userIdentity: userInfo?.userIdentity || '',
  proxyInfo: null,
  shopType: userInfo?.shopType || '',
  brandId: userInfo?.brandId || ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USERINFO: (state, userInfo) => {
    state.shopStatus = userInfo.shopStatus
    state.authUserId = userInfo.authUserId
    state.userIdentity = userInfo.userIdentity
    state.shopType = userInfo.shopType
    state.brandId = userInfo.brandId
  },
  SET_PROXY_INFO: (state, proxyInfo) => {
    state.proxyInfo = proxyInfo
  },
  SET_SHOP_TYPE: (state, shopType) => {
    state.shopType = shopType
  }
}

const actions = {
  // 登录操作
  login({ commit, action }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ mobileOrName: username.trim(), password: password })
        .then(response => {
          const { shopStatus, token, authUserId, userIdentity, name, shopType, brandId } = response.data
          const roles = formatRoles(userIdentity)
          commit('SET_TOKEN', token) // 保存token
          commit('SET_USERINFO', { shopStatus, authUserId, userIdentity, shopType, brandId }) // 保存用户信息
          commit('SET_ROLES', roles) // 根据用户类型生成角色列表
          commit('SET_NAME', name) // 保存用户名称
          // commit('app/SET_IS_REFRESH', false)
          setToken(token) // cokies保存token
          setUser(response.data) // cokies保存当前用户信息
          console.log(response)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 退出登录
  logout({ commit, state, dispatch }) {
    commit('SET_TOKEN', '') // 重置token
    commit('SET_ROLES', []) // 重置角色权限表
    commit('SET_PROXY_INFO', null)
    commit('SET_NAME', '')

    removeToken() // 从cokies中移除token
    resetRouter() // 重置路由
    removeUser() // 从cokies中移除用户信息
    dispatch('tagsView/delAllViews', null, { root: true }) // 关闭所有打开的标签页
  },

  // 移除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  }
}

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