import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    isLoggedIn: false, // 登录状态
    userInfo: {
      userid: 0, // 用户 ID
      username: '', // 用户名
      avatar: '', // 用户头像
      email: '', // 用户邮箱
      phone: '', // 用户手机号
      college: '', // 学院
      gender: 0, // 性别,0-未知,1-男,2-女
      role: 1, // 角色，1-普通用户，2-管理员，3-超级管理员
      status: 1, // 状态，1-正常，2-冻结
    },
  }),
  actions: {
    login(userData) {
      this.isLoggedIn = true;
      this.userInfo = {
        userid: userData.userid || 0,
        username: userData.userName || '',
        avatar: userData.avatar || '',
        email: userData.email || '',
        phone: userData.phone || '',
        college: userData.college || '',
        gender: userData.gender || 0,
        role: userData.role || 1,
        status: userData.status || 1
      };
      
      // 保存令牌到本地存储（如果有的话）
      if (userData.accessToken) {
        localStorage.setItem('accessToken', userData.accessToken);
      }
      if (userData.refreshToken) {
        localStorage.setItem('refreshToken', userData.refreshToken);
      }
      
      // 保存基本用户信息到localStorage，用于页面刷新时恢复
      localStorage.setItem('userId', this.userInfo.userid);
      localStorage.setItem('username', this.userInfo.username);
      localStorage.setItem('avatar', this.userInfo.avatar || '');
      localStorage.setItem('role', this.userInfo.role);
      
      console.log('用户登录成功，状态已更新:', this.userInfo);
    },
    
    // 更新用户信息
    updateUserInfo(userData) {
      this.userInfo = {
        ...this.userInfo,
        username: userData.username || this.userInfo.username,
        avatar: userData.avatar || this.userInfo.avatar,
        email: userData.email || this.userInfo.email,
        phone: userData.phone || this.userInfo.phone,
        college: userData.college || this.userInfo.college,
        gender: userData.gender !== undefined ? userData.gender : this.userInfo.gender,
        role: userData.role || this.userInfo.role,
        status: userData.status || this.userInfo.status
      };
      
      // 更新localStorage中的用户信息
      localStorage.setItem('username', this.userInfo.username);
      localStorage.setItem('avatar', this.userInfo.avatar || '');
      
      console.log('用户信息已更新:', this.userInfo);
    },
    
    logout() {
      this.isLoggedIn = false;
      this.userInfo = {
        userid: 0,
        username: '',
        avatar: '',
        email: '',
        phone: '',
        college: '',
        gender: 0,
        role: 1,
        status: 1
      };
      
      // 清除本地存储的令牌和用户信息
      localStorage.removeItem('accessToken');
      localStorage.removeItem('refreshToken');
      localStorage.removeItem('userId');
      localStorage.removeItem('username');
      localStorage.removeItem('avatar');
      localStorage.removeItem('role');
      
      console.log('用户已登出');
    },
  },
});