import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { message } from 'ant-design-vue';
import { router } from '@/router';
import * as authApi from '@/api/auth';
import { rsaEncrypt } from '@/utils/encryption';

export interface User {
  id: number;
  name: string;
  role: 'admin' | 'school' | 'teacher' | 'parent';
  tenantId?: number;
  tenantName?: string;
  email?: string;
  phone?: string;
  children?: Array<{ id: number; name: string; relationship: string }>;
}

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(localStorage.getItem('token') || '');
  const user = ref<User | null>(
    localStorage.getItem('user')
      ? JSON.parse(localStorage.getItem('user')!)
      : null
  );

  const isLoggedIn = computed(() => !!token.value);
  const userRole = computed(() => user.value?.role || null);

  // 登录（使用 RSA 加密）
  async function login(account: string, password: string, role: string) {
    try {
      // 1. 获取 RSA 公钥
      const { publicKey, keyVersion } = await authApi.getPublicKey();

      // 2. 使用 RSA 公钥加密密码
      const encryptedPassword = rsaEncrypt(password, publicKey);
      if (!encryptedPassword) {
        throw new Error('密码加密失败');
      }

      // 3. 使用加密后的密码登录
      const data = await authApi.loginEncrypted({
        username: account,
        encryptedPassword,
        role,
        keyVersion,
      });

      // 后端返回格式: { token, userId, username, name, role, tenantId }
      token.value = data.token;
      user.value = {
        id: data.userId,
        name: data.name,
        role: data.role,
        tenantId: data.tenantId,
      };

      localStorage.setItem('token', data.token);
      localStorage.setItem('user', JSON.stringify(user.value));
      localStorage.setItem('role', data.role);

      message.success('登录成功');

      // 跳转到对应首页
      const defaultRoute = `/${data.role}/dashboard`;
      router.push(defaultRoute);

      return data;
    } catch (error: any) {
      message.error(error.message || '登录失败');
      throw error;
    }
  }

  // 登出
  async function logout() {
    try {
      await authApi.logout();
    } catch (error) {
      console.error('Logout error:', error);
    } finally {
      token.value = '';
      user.value = null;
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      localStorage.removeItem('role');
      router.push('/login');
      message.success('已退出登录');
    }
  }

  // 获取用户信息
  async function fetchUserInfo() {
    try {
      const data = await authApi.getProfile();
      user.value = data;
      localStorage.setItem('user', JSON.stringify(data));
      return data;
    } catch (error: any) {
      message.error('获取用户信息失败');
      throw error;
    }
  }

  return {
    token,
    user,
    isLoggedIn,
    userRole,
    login,
    logout,
    fetchUserInfo,
  };
});
