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

const user = {
  state: {
    id: '',
    name: '',
    avatar: '',
    menuList: [],
    permissionList: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    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.mgt_token = data.extraInfo.token
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取授权信息，所有接口必须调用此接口后执行
    GetInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
        getAuthorizationInfo().then(res => {
          const info = res.extraInfo
          // 设置ID
          commit('SET_ID', info.id)
          // 设置用户名
          commit('SET_NAME', info.nickName)
          // 设置菜单
          commit('SET_MENU_LIST', info.menuList)
          // 设置按钮权限
          commit('SET_PERMISSIONLIST', info.permissionList)

          // let permissions = _(info.permissionList)
          //   .groupBy(i => {
          //     return i.split(':')[0]
          //   })
          //   .mapValues(i => {
          //     return i.map(j => {
          //       return j.split(':')[1]
          //     })
          //   })
          //   .value()

          // console.log(permissions)

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

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

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

export default user
