import {
  login,
  userProfile
} from '@/api/login'
import router from '../../router'
const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // user login
    Login({
      commit
    }, userInfo) {
      return new Promise((resolve, reject) => {
        // console.log(userInfo, 25)
        // 连接后端接口，根据前端请求的用户信息，后端返回唯一对应的随机token
        login(userInfo).then(response => {
          const data = response
          if (data.code == 200) {
            // commit会触发mutations，存储token
            commit('SET_TOKEN', data.token)
            localStorage.setItem('T_tokey', data.token);
            resolve()
          } else {
            reject(data)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取权限菜单
    GetInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        userProfile().then(res => {
          if (res.code == 200) {
            localStorage.setItem('userList', JSON.stringify(res.data.user));
            const arr = {
              deptId: res.data.user.deptId,
              userType: res.data.user.userType,
            }
            const roles = [{
              action: 'add',
              describe: '新增',
              defaultCheck: false
            }]
            // 存储用户信息，方便用于全局
            commit('SET_ROLES', roles)
            resolve(arr)
          } else {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            commit('setMenu', [])
            localStorage.removeItem('T_tokey');
            localStorage.removeItem('username');
            router.push('/login');
          }
        })
      })
    },
    // 登出
    Logout({
      commit,
      state
    }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('setMenu', [])
        localStorage.removeItem('T_tokey');
        localStorage.removeItem('username');
        resolve()
      })
    }
  }
}

export default user
