import { computed, ref } from 'vue';

import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', () => {
  const currentUser = ref();
  const isLoggedIn = computed(() => !!currentUser.value);

  // 预设用户数据
  const presetUsers = ref([
    {
      id: '1',
      room_id: '10001',
      name: '张三',
      avatar: 'avatar1',
      color: '#4cc9f0',
    },
    {
      id: '2',
      room_id: '10002',
      name: '李四',
      avatar: 'avatar2',
      color: '#ff6b6b',
    },
    {
      id: '3',
      room_id: '10003',
      name: '王五',
      avatar: 'avatar3',
      color: '#6a0dad',
    },
    {
      id: '4',
      room_id: '10004',
      name: '赵六',
      avatar: 'avatar4',
      color: '#20b2aa',
    },
    {
      id: '5',
      room_id: '10005',
      name: '钱七',
      avatar: 'avatar5',
      color: '#ffa500',
    },
    {
      id: '6',
      room_id: '10006',
      name: '孙八',
      avatar: 'avatar6',
      color: '#9acd32',
    },
    {
      id: '7',
      room_id: '10007',
      name: '周九',
      avatar: 'avatar7',
      color: '#ff1493',
    },
    {
      id: '8',
      room_id: '10008',
      name: '吴十',
      avatar: 'avatar8',
      color: '#4682b4',
    },
    {
      id: '9',
      room_id: '10009',
      name: '郑十一',
      avatar: 'avatar9',
      color: '#c71585',
    },
    {
      id: '10',
      room_id: '100010',
      name: '王十二',
      avatar: 'avatar10',
      color: '#2e8b57',
    },
  ]);

  const login = (user: any) => {
    currentUser.value = user;
    currentUser.value.id = `doctor-${user.id}`;
    localStorage.setItem('chatUser', JSON.stringify(user));
  };

  const logout = () => {
    currentUser.value = null;
    localStorage.removeItem('chatUser');
    localStorage.removeItem('token');
  };

  const checkSession = () => {
    const savedUser = localStorage.getItem('chatUser');
    if (savedUser) {
      currentUser.value = JSON.parse(savedUser);
    }
  };

  const setClientId = (clientId: number | string) => {
    currentUser.value.clientId = clientId;
  };

  return {
    currentUser,
    isLoggedIn,
    presetUsers,
    login,
    logout,
    checkSession,
    setClientId,
  };
});
