import {
    getCookie,
    setToken,
    setUserId,
    removeToken,
    removeUserId,
    setName,
    removeName,
} from "@/utils/auth";
// import { Message } from "element-plus";
import { Login, loginRequest, getUserinfo, logout } from "@/api/api";
const state = {
    authToken: getCookie("accessToken") || "", //
    username: getCookie("userName") || "",
    userId: getCookie("userId") || "",
    roles: [],
    permissions: [],
};
const mutations = {
    REMOVE_TOKEN(state) {
        removeToken();
        removeUserId();
        removeName();
        state.roles = [];
        state.permissions = [];
        state.username = "";
        state.userId = "";
        state.authToken = "";
    },
    SET_TOKEN: (state, data) => {
        state.authToken = data.accessToken;
        state.userId = data.userId;
        setToken(data.accessToken);
        setUserId(data.userId);
    },
    SET_LOGINSTATE: (state, login) => {
        state.loginState = login;
        setLoginState(login);
    },
    SET_NAME: (state, name) => {
        state.username = name;
        setName(name);
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
        state.permissions = permissions;
    },
};
const actions = {
    // 获取用户信息
    GetInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getUserinfo()
                .then((res) => {
                    if (res) {
                        if (res.data.roles && res.data.roles.length > 0) {
                            // 验证返回的roles是否是一个非空数组
                            commit("SET_ROLES", res.data.roles);
                            commit("SET_NAME", res.data.user.nickname);
                            commit("SET_PERMISSIONS", res.data.permissions);
                        } else {
                            commit("SET_ROLES", ["ROLE_DEFAULT"]);
                        }
                        resolve(res.data);
                    }
                })
                .catch((error) => {
                    reject(error);
                });
        });
    },
    LogOut({ commit, state }) {
        return new Promise((resolve, reject) => {
            logout({ token: state.authToken, userId: state.userId })
                .then((res) => {
                    if (res.code == 200) {
                        commit("REMOVE_TOKEN");
                        resolve();
                    }
                })
                .catch((error) => {
                    reject(error);
                });
        });
    },
};
export default {
    namespaced: true,
    state,
    mutations,
    actions,
};