import { defineStore } from 'pinia'
import myAxios from "../api/myAxios";
import { message } from 'ant-design-vue';

export const userStore = defineStore('user', {
    state: () => ({
        loginUser: {
            username: '未登录',
            avatarUrl: '',
            userRole: 'notLogin',
            phone: ''
        }
    }),
    persist: true,

    actions: {
        // 获取登录用户信息
        async getLoginUser() {
            try {
                const storedToken = localStorage.getItem('token');
                if (!storedToken) {
                    message.warning('请先登录');
                    return;
                }

                const res:any = await myAxios.get('/userInfo/get/jwt/web', {
                    headers: {
                        Authorization: storedToken
                    }
                });

                if (res.code === 1) {
                    console.log(res)
                    this.updateUser({
                        username: res.data.userAccount,
                        avatarUrl: res.data.userAvatar,
                        userRole: res.data.userRole,
                        phone: res.data.phoneNumber
                    });
                } else {
                    message.error(res.message || '获取用户信息失败');
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
                message.error('获取用户信息失败，请检查网络连接');
                this.clearUser();
            }
        },

        // 更新用户信息
        updateUser(payload: any) {
            this.loginUser = {
                ...this.loginUser,
                ...payload
            };
        },

        // 清除用户信息
        clearUser() {
            this.loginUser = {
                username: '未登录',
                avatarUrl: '',
                userRole: 'notLogin',
                phone: ''
            };
            localStorage.removeItem('token');
        }
    }
})