import request from "@/utils/request"
import router, { dynamicRoutes, resetRouter } from '@/router'

const state = {
    token: sessionStorage.getItem("LSUserId"), //已储存的userId作为token
    hasRoute: false, //是否已经生成了路由
    newRouterList: [],
    authorization: null
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_HAS_ROUTE: (state, hasRoute) => {
        state.hasRoute = hasRoute
    },
    SET_NEW_ROUTER_LIST: (state, newRouterList) => {
        state.newRouterList = newRouterList
    },
    SET_AUTHORIZATION: (state, authorization) => {
        state.authorization = authorization
    }
}
const actions = {
    login({ commit, state }, userInfo) {
        const { username, password } = userInfo
        return new Promise((resolve, reject) => {
        request({
            url: "/user/login",
            method: "post",
            params: { username: username.trim(), password: password }
        })
            .then(response => {
            commit('SET_TOKEN', response.data) //这里目前是data 意义为userId
            window.sessionStorage.setItem("LSUserId", response.data);
            resolve()
            })
            .catch(error => {
            reject(error)
            })
        })
    },

    loadRouter({ commit, state }) {
        return new Promise((resolve, reject) => {
            request({
                url: "/user/getRoutesById",
                method: "post"
            })
            .then(response => {
                commit('SET_HAS_ROUTE', true)
                commit('SET_NEW_ROUTER_LIST', dynamicRoutes)
                resolve()
            })
            .catch(error => {
                reject(error)
            })
        resolve()
        })
    },

    // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            commit('SET_TOKEN', null)
            window.sessionStorage.removeItem("LSUserId");
            resetRouter()
            commit('SET_HAS_ROUTE', false)
            resolve()
        })
    },
}

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