import { login, logout, getInfo } from '@/api/me'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    username: '',
    adminId: '',
    yearHoliday: 0,
    department: {},
    role: [],
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLE: (state, role) => {
    state.role = role
  },
  SET_ADMIN_ID: (state, id) => {
    state.adminId = id
  },
  SET_YEAR_HOLIDAY: (state, day) => {
    state.yearHoliday = day
  },
  SET_DEPARTMENT: (state, department) => {
    state.department = department
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        console.log(response)
        const { access_token, expires_in } = response
        commit('SET_TOKEN', access_token)
        setToken(access_token, expires_in / 60 / 24)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {

        const { name, avatar, id, role, department, username, year_holiday } = response

        commit('SET_DEPARTMENT',department)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_ADMIN_ID', id)
        commit('SET_ROLE', role)
        commit('SET_USERNAME', username)
        commit('SET_YEAR_HOLIDAY', year_holiday??0)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      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
}

