import {
    defineStore
} from 'pinia';
import {
    ElMessage
} from 'element-plus';
import req from "../request"

export const userStore = defineStore('userStore', {
    state: () => ({
        token: "",
        userInfo: {},
        isAdmin: false
    }),
    getters: {
        getToken() {
            return this.token
        },
        getUserInfo() {
            return this.userInfo
        },
        getIsAdmin() {
            return this.userInfo.isAdmin
        }
    },
    actions: {
        setLoginState(state) {
            this.loginState = state;
            localStorage.setItem('isLoggedIn', state); // 将登录状态存储到 localStorage
        },
        setToken(token) {
            this.token = token;
            localStorage.setItem("token", token)
        },
        setUserInfo(data) {
            this.userInfo = data;
            console.log(this.data, "userStoreData")
        },
        updateUserInfo(data) {
            req({
                method: "put",
                url: "/user",
                data,
            }).then(({
                data
            }) => {
                if (data.code === 0) {
                    this.setUserInfo(data.data)
                    ElMessage({
                        message: "修改成功",
                        type: "success"
                    })
                }

            })

        },
        logoutUser() {
            localStorage.removeItem("token")
            location.reload(true);
            ElMessage({
                message: '注销成功',
                type: 'success',
                plain: true,
            })
        },
        setAdmin(value) {
            this.isAdmin = value
        }
    }
});