import { login, logout, getInfo ,getAvatarsApi} from '@/api/login.js'
import { getToken, setToken, removeToken ,getUserInfo} from '@/utils/auth.js'
import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore(
    'user',
    {
        state: () => ({
            token: getToken(),
            name: '',
            avatar: '',
            roles: '', 
        }),
        actions: {
            // 登录
            async login(userInfo) {
                try {
                    const { username, password } = userInfo;
                    const trimmedUsername = username.trim(); 
                    const res = await login(trimmedUsername, password); 
                    if (res.meta.code !== 200) {
                        ElMessage({ message: res.meta?.message || '登录失败', type: 'error' });
                        return Promise.reject(res);
                    } 
                    if(!res.data.user.is_admin){
                        ElMessage({ message: '暂无权限登录，请联系管理员', type: 'error' });
                        return Promise.reject(res);
                    }
                    const { token, user } = res.data;
                    this.name = user.name;  
                    sessionStorage.setItem('userData', JSON.stringify(user));
                    await this.getAvatars();
                    setToken(token);
                    this.token = token;

                } catch (error) {
                    console.error('登录失败:', error);
                    throw error;
                }
            },
            // 获取用户信息
            getInfo() {
                return new Promise((resolve, reject) => {
                    try {
                        const userData = sessionStorage.getItem('userData');

                        if (!userData) {
                            return reject(new Error('未找到用户数据'));
                        }
                        const parsedData = JSON.parse(userData);
                        if (!parsedData) {
                            return reject(new Error('用户数据格式无效'));
                        }
                        resolve(parsedData);
                    } catch (error) {
                        console.error('获取用户信息失败:', error);
                        reject(error instanceof Error ? error : new Error('解析用户数据失败'));
                    }
                });
            }, 
            // 获取用户头像
            async getAvatars() {
                try {
                    const userData = await getUserInfo() 
                    const res = await getAvatarsApi(userData.uid);  
                    const url = URL.createObjectURL(res); 
                    this.avatar = url;  
                } catch (error) {
                    console.error('获取头像失败:', error);
                    throw error;
                }
            },
            // 退出系统
            async logOut() {
                try {
                    const res = await logout(); 
                    if(res.meta.code !== 200){
                        ElMessage({ message: res.meta?.message || '退出登录失败', type: 'error' });
                        return 
                    } 
                    this.token = '';
                    this.roles = ''; 
                    sessionStorage.removeItem('userData');
                    removeToken();
                } catch (error) {
                    console.error('退出登录失败:', error);
                    throw error;
                }
            },
            //判断是否登录
            checkLogin() {
                return !!getToken();
            }
        }
    })