import { login, getAuthorizationInfo, logout } from '@/api/login'

// import { getToken, setToken, removeToken } from '@/utils/auth'
// import _ from 'lodash'
const user = {
  state: {
    // token: getToken(),
    name: '',
    avatar: '',
    menuList: [],
    permissionList: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_MENU_LIST: (state, menuList) => {
      state.menuList = menuList
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(data => {
          localStorage.otaToken = data.data.token || ''
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取授权信息，所有接口必须调用此接口后执行
    GetInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
        getAuthorizationInfo().then(res => {
          let info = res.data.admin || {}
          // 设置用户名
          commit('SET_NAME', info.loginName)
          // 设置菜单
          // commit('SET_MENU_LIST', ['all'] || res.data.resourceList)
          commit('SET_MENU_LIST', res.data.resourceList)
          // 设置按钮权限
          // commit('SET_PERMISSIONLIST', res.data.roleList)
          commit('SET_PERMISSIONLIST', [])

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

    // 登出
    LogOut ({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          localStorage.removeItem('otaToken')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut ({ commit }) {
      return new Promise(resolve => {
        localStorage.removeItem('otaToken')
        resolve()
      })
    }
  }
}

export default user
