import { defineStore } from 'pinia';
import { authAPI } from '../services/api.js';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('auth_token'),
    permissions: [],
    isAuthenticated: false,
    loading: false,
    error: null,
  }),

  getters: {
    // 检查用户是否有特定权限
    hasPermission: (state) => (permission) => {
      return state.permissions.includes(permission);
    },

    // 检查用户是否有任一权限
    hasAnyPermission: (state) => (permissions) => {
      return permissions.some(permission => state.permissions.includes(permission));
    },

    // 检查用户是否有所有权限
    hasAllPermissions: (state) => (permissions) => {
      return permissions.every(permission => state.permissions.includes(permission));
    },

    // 获取用户类型
    userType: (state) => state.user?.user_type,

    // 获取用户名
    username: (state) => state.user?.username,

    // 获取真实姓名
    realName: (state) => state.user?.real_name,
  },

  actions: {
    // 用户登录
    async login(credentials) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await authAPI.login(credentials);
        
        if (response.success) {
          const { token, user } = response.data;
          
          // 保存token和用户信息
          this.token = token;
          this.user = user;
          this.isAuthenticated = true;
          
          // 存储到localStorage
          localStorage.setItem('auth_token', token);
          localStorage.setItem('user_info', JSON.stringify(user));
          
          // 获取用户权限
          await this.loadPermissions();
          
          return { success: true };
        } else {
          this.error = response.message || '登录失败';
          return { success: false, message: this.error };
        }
      } catch (error) {
        this.error = error.response?.data?.message || '登录失败，请检查网络连接';
        return { success: false, message: this.error };
      } finally {
        this.loading = false;
      }
    },

    // 获取用户权限
    async loadPermissions() {
      try {
        const response = await authAPI.getPermissions();
        if (response.success) {
          this.permissions = response.data.permissions || [];
        }
      } catch (error) {
        console.error('获取权限失败:', error);
        this.permissions = [];
      }
    },

    // 获取用户信息
    async loadProfile() {
      try {
        const response = await authAPI.getProfile();
        if (response.success) {
          this.user = response.data;
          localStorage.setItem('user_info', JSON.stringify(this.user));
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    },

    // 用户登出
    async logout() {
      try {
        await authAPI.logout();
      } catch (error) {
        console.error('登出失败:', error);
      } finally {
        // 清除本地数据
        this.user = null;
        this.token = null;
        this.permissions = [];
        this.isAuthenticated = false;
        this.error = null;
        
        localStorage.removeItem('auth_token');
        localStorage.removeItem('user_info');
      }
    },

    // 初始化认证状态
    initAuth() {
      const token = localStorage.getItem('auth_token');
      const userInfo = localStorage.getItem('user_info');
      
      if (token && userInfo) {
        try {
          this.token = token;
          this.user = JSON.parse(userInfo);
          this.isAuthenticated = true;
          
          // 重新获取权限
          this.loadPermissions();
        } catch (error) {
          console.error('初始化认证状态失败:', error);
          this.clearAuth();
        }
      }
    },

    // 清除认证状态
    clearAuth() {
      this.user = null;
      this.token = null;
      this.permissions = [];
      this.isAuthenticated = false;
      this.error = null;
      
      localStorage.removeItem('auth_token');
      localStorage.removeItem('user_info');
    },
  },
});