import { login, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import Cookies from 'js-cookie'
import { Message } from 'element-ui'
const user = {
  state: {
    token: getToken(),
    name: Cookies.get('name'),
    roles: [],
    id: Cookies.get('id'),
    userId: Cookies.get('userId')
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_userId: (state, userId) => {
      state.userId = userId
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          const data = response.data
          if (data.length === 0 || data.result === '0') {
            Message.error('账号或密码错误，请重新登录')
            this.$router.push({ path: '/login' })
          } else {
            setToken(data[0].角色编号)
            Cookies.set('id', data[0].人员编号, { expires: 1 })
            Cookies.set('name', data[0].姓名, { expires: 1 })
            Cookies.set('userId', data[0].考勤编号, { expires: 1 })
            Cookies.set('session_id', data[0].session_id)
            commit('SET_TOKEN', data[0].角色编号)
            commit('SET_NAME', data[0].姓名)
            commit('SET_ID', data[0].人员编号)
            commit('SET_userId', data[0].考勤编号)
            resolve()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      console.log(state.token)
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          commit('SET_ROLES', 'admin')
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    //  登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        Cookies.remove('name')
        Cookies.remove('id')
        Cookies.remove('userId')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
