import { loginUrl, logoutUrl, getInfoUrl } from '@/api/loginnew'
import http from '@/utils/request'
import Cookies from 'js-cookie'

const user = {
  state: {
    userid: '',
    name: '',
    account: ''
  },
  mutations: {
    SET_USERID: (state, userid) => {
      state.userid = userid
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_COUNT: (state, account) => {
      state.account = account
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        http.post(loginUrl, userInfo, (response) => {
          if (response.success) {
            if (response.data) {
              const dataS = response.data
              if (dataS.actived) {
                commit('SET_USERID', dataS.id)
                commit('SET_NAME', dataS.name)
                Cookies.set('userid', dataS.id)
              }
            }
          }
          resolve(response)
        }, (error) => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        http.get(getInfoUrl, '', response => {
          if (response.success) {
            if (response.data) {
              const dataS = response.data
              if (dataS.actived) {
                commit('SET_USERID', dataS.id)
                commit('SET_NAME', dataS.name)
                commit('SET_COUNT', dataS.account)
                Cookies.set('userid', dataS.id)
              }
            }
          }
          resolve(response)
        }, error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        http.get(logoutUrl, '', (response) => {
          commit('SET_USERID', '')
          commit('SET_NAME', '')
          Cookies.remove('userid')
          resolve(response)
        }, error => {
          reject(error)
        })
      })
    }
  }
}

export default user
