import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { isLogOut, notLogOut } from "@/utils/waitLogOut";

const getDefaultState = () => {
  return {
    token: getToken(),
    username: '',
    role: 1,
    adminId: null,
    adminType: null,
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },

  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROLE: (state, role) => {
    state.role = role
  },
  SET_ADMINID: (state, adminId) => {
    state.adminId = adminId
  },
  SET_ADMINTYPE: (state, adminType) => {
    state.adminType = adminType
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, mobilePhone, smsCode } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, mobilePhone: mobilePhone, smsCode: smsCode }).then(response => {
        // 标记登录,开始检测长时间未操作情况
        notLogOut()

        const { data } = response
        commit('SET_USERNAME', data.username)
        commit('SET_TOKEN', data.token)
        commit('SET_ROLE', data.type)
        commit('SET_ADMINID', data.adminId)
        setToken(data.token)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          return reject('验证失效，请重新登录')
        }
        commit('SET_USERNAME', data.username)
        commit('SET_ROLE', data.type)
        commit('SET_ADMINID', data.adminId)
        commit('SET_ADMINTYPE', data.adminType)

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

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 标记已经退出,不用再检测长时间未操作情况
      isLogOut()

      // logout(state.token).then(() => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

