import { defineStore } from 'pinia'; import { ref, h } from 'vue'; import { b as useUserStore, a as useConfigStore, u as useRouter$1, a3 as fetchUserChats, s as supabase, a2 as api, O as Button, a4 as fetchOneChat } from './server.mjs'; const useChatStore = defineStore("chat", () => { const userStore = useUserStore(); const config = useConfigStore(); const chats = ref([]); const loading = ref(false); const currentPage = ref(0); const router = useRouter$1(); const limit = ref(10); const endPage = ref(false); const setChat = (_chat) => { const index = chats.value.findIndex((item) => item.chat_id === _chat.chat_id); if (index >= 0) { Object.assign(chats.value[index], { ..._chat }); } else { chats.value.push(_chat); } }; const setChats = (_chats) => { _chats.map((item) => setChat(item)); }; const request = async () => { try { if (!endPage.value) { loading.value = true; const res = await fetchUserChats(userStore.user.id, ++currentPage.value, limit.value); setChats(res); if (res?.length < limit.value) { endPage.value = true; } } } catch (e) { console.log("e ===>", e); } finally { loading.value = false; } }; const getChatWithId = async (chat_id) => { return await fetchOneChat(chat_id); }; const addChatWithId = async (chat_id) => { chats.value.unshift(getChatWithId(chat_id)); }; const runChannel = () => { supabase.channel("realtime:chats").on( "postgres_changes", { event: "*", schema: "public", table: "chats" }, async (payload) => { if (userStore.user?.id && (payload.new.user1_id == userStore.user.id || payload.new.user2_id == userStore.user.id)) { if (payload.eventType === "INSERT") { await addChatWithId(payload.new.chat_id); } else if (payload.eventType === "UPDATE") { const chat = payload.new; setChat(chat); if (chat?.last_message?.sender_id && chat?.last_message?.sender_id !== userStore.user?.id && !chat?.last_message?.is_read) { const key = `open${Date.now()}`; const getChat = await getChatWithId(chat.chat_id); api.open({ message: config.useString("newMessage"), description: `${config.useString("YouHaveNewMessageFrom")}: ${userStore.user?.id === chat.user1_id ? getChat?.user2?.name : getChat?.user1?.name}`, btn: () => h( Button, { type: "primary", size: "small", onClick: async () => { api.close(key); await router.push({ name: "message-detail_message", query: { id: chat.chat_id } }); } }, { default: () => config.useString("show") } ), key, onClose: close }); } } } } ).subscribe(); }; return { chats, runChannel, request }; }); export { useChatStore as u }; //# sourceMappingURL=chatStore-DDPca5FN.mjs.map