gaoluyang
昨天 b64a0deae5b5d33f9e20671a68936b27f0b9b00b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
import type {
  Conversation,
  ConversationDO,
  ConversationRead,
  ConversationReadDO,
  MessageDO
} from '../types'
 
import type { ImConversationReadApi } from '#/api/im/conversation/read'
 
import { acceptHMRUpdate, defineStore } from 'pinia'
 
import { pullMyConversationReadList as apiPullMyConversationReadList } from '#/api/im/conversation/read'
import { getCurrentUserId } from '#/views/im/utils/auth'
 
import { CONVERSATION_RECENT_FORWARD_MAX } from '../../utils/config'
import {
  ImConversationType,
  ImMessageReceiptStatus,
  ImMessageStatus,
  isNormalMessage
} from '../../utils/constants'
import { type DbTransaction, getClientConversationId, getDb, StorageKeys } from '../../utils/db'
import { runIncrementalPull } from '../../utils/pull'
import { useMessageStore } from './messageStore'
 
const PERSIST_DRAFT_DEBOUNCE_MS = 500
const pendingDraftConversations = new Set<Conversation>()
 
/** 创建会话读位置记录 */
function createConversationRead(
  type: number,
  targetId: number,
  messageId: number
): ConversationRead {
  return {
    conversationType: type,
    targetId,
    messageId,
    updateTime: Date.now()
  }
}
 
/** 创建草稿保存防抖函数 */
function createDraftDebounce(fn: () => void, wait: number) {
  let timer: ReturnType<typeof setTimeout> | undefined
 
  const run = () => {
    if (timer) {
      clearTimeout(timer)
      timer = undefined
    }
    fn()
  }
  const debounced = () => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(run, wait)
  }
  debounced.cancel = () => {
    if (timer) {
      clearTimeout(timer)
      timer = undefined
    }
  }
  debounced.flush = run
  return debounced
}
 
/** 会话转 IndexedDB 记录 */
function toConversationDO(conversation: Conversation): ConversationDO {
  const draft = conversation.draft
  return {
    targetId: conversation.targetId,
    type: conversation.type,
    name: conversation.name,
    avatar: conversation.avatar,
    unreadCount: conversation.unreadCount,
    lastContent: conversation.lastContent,
    lastSendTime: conversation.lastSendTime,
    lastSenderId: conversation.lastSenderId,
    lastMessageType: conversation.lastMessageType,
    lastMessageId: conversation.lastMessageId,
    lastClientMessageId: conversation.lastClientMessageId,
    lastMessageStatus: conversation.lastMessageStatus,
    lastReceiptStatus: conversation.lastReceiptStatus,
    lastSelfSend: conversation.lastSelfSend,
    lastSenderDisplayName: conversation.lastSenderDisplayName,
    reportedReadMessageId: conversation.reportedReadMessageId,
    deleted: conversation.deleted,
    top: conversation.top,
    silent: conversation.silent,
    atMe: conversation.atMe,
    atAll: conversation.atAll,
    draft: draft ? { ...draft, reply: draft.reply ? { ...draft.reply } : undefined } : undefined,
    clientConversationId: getClientConversationId(conversation.type, conversation.targetId)
  }
}
 
/** IndexedDB 记录转会话 */
function fromConversationDO(conversation: ConversationDO): Conversation {
  const {
    clientConversationId: _clientConversationId,
    ...rest
  } = conversation
  return rest
}
 
/** 会话读位置转 IndexedDB 记录 */
function toConversationReadDO(record: ConversationRead): ConversationReadDO {
  return {
    conversationType: record.conversationType,
    targetId: record.targetId,
    messageId: record.messageId,
    updateTime: record.updateTime,
    clientConversationId: getClientConversationId(record.conversationType, record.targetId)
  }
}
 
/** IndexedDB 记录转会话读位置 */
function fromConversationReadDO(record: ConversationReadDO): ConversationRead {
  const { clientConversationId: _clientConversationId, ...rest } = record
  return rest
}
 
/** 是否为有效会话读位置 */
function isValidConversationReadRecord(record: ImConversationReadApi.ConversationReadRespVO): boolean {
  return !!record.conversationType && !!record.targetId && !!record.messageId
}
 
/** 获取对方普通消息最大编号 */
function getMaxIncomingNormalMessageId(
  messages: Array<Pick<MessageDO, 'id' | 'selfSend' | 'status' | 'type'>>
): number {
  let maxMessageId = 0
  for (const message of messages) {
    if (
      message.id &&
      !message.selfSend &&
      isNormalMessage(message.type) &&
      message.status !== ImMessageStatus.RECALL &&
      message.id > maxMessageId
    ) {
      maxMessageId = message.id
    }
  }
  return maxMessageId
}
 
export const useConversationStore = defineStore('imConversationStore', {
  state: () => ({
    conversations: [] as Conversation[], // 全量会话列表(私聊 + 群聊 + 频道)
    conversationReads: {} as Record<string, ConversationRead>, // 会话读位置
    activeConversation: null as Conversation | null, // 当前激活的会话
    loading: false, // 是否正在批量加载
    recentForwardConversationKeys: [] as string[] // 最近转发会话 key 列表
  }),
 
  getters: {
    /** 排序后的会话列表 */
    getSortedConversationList(state): Conversation[] {
      return state.conversations
        .filter((conversation) => !conversation.deleted)
        .toSorted((a, b) => {
          const aTop = a.top ? 1 : 0
          const bTop = b.top ? 1 : 0
          if (aTop !== bTop) {
            return bTop - aTop
          }
          return (b.lastSendTime || 0) - (a.lastSendTime || 0)
        })
    },
 
    /** 未读总数 */
    getTotalUnreadCount(state): number {
      return state.conversations
        .filter((conversation) => !conversation.deleted && !conversation.silent)
        .reduce((sum, conversation) => sum + (conversation.unreadCount || 0), 0)
    },
 
    /** 查找会话 */
    getConversation:
      (state) =>
      (type: number, targetId: number): Conversation | undefined =>
        state.conversations.find(
          (conversation) => conversation.type === type && conversation.targetId === targetId
        ),
 
    /** 查找会话读位置 */
    getConversationRead:
      (state) =>
      (type: number, targetId: number): ConversationRead | undefined =>
        state.conversationReads[getClientConversationId(type, targetId)]
  },
 
  actions: {
    /** 加载会话 */
    async loadConversationList() {
      // 1. 清理旧账号内存
      const userId = getCurrentUserId()
      if (!userId) {
        this.clear()
        return
      }
      const previousActiveKey = this.activeConversation
        ? getClientConversationId(this.activeConversation.type, this.activeConversation.targetId)
        : null
      this.clear()
      // 2. 从 IndexedDB 读取会话和轻量设置
      const db = getDb()
      const [conversations, conversationReads, recent] = await Promise.all([
        db.getAll<ConversationDO>('conversations'),
        db.getAll<ConversationReadDO>('conversationReads'),
        db.getSetting<string[]>(StorageKeys.settings.recentForwardConversationKeys)
      ])
      const nextConversationReads: Record<string, ConversationRead> = {}
      for (const record of conversationReads) {
        const item = fromConversationReadDO(record)
        nextConversationReads[getClientConversationId(item.conversationType, item.targetId)] = item
      }
      const nextConversations = conversations.map((conversation) => fromConversationDO(conversation))
      this.conversationReads = nextConversationReads
      await this.applyLocalConversationReads(nextConversations)
      this.conversations = nextConversations
      if (Array.isArray(recent)) {
        this.recentForwardConversationKeys = recent.slice(0, CONVERSATION_RECENT_FORWARD_MAX)
      }
      // 3. 恢复当前激活会话
      if (previousActiveKey) {
        this.activeConversation =
          this.conversations.find(
            (conversation) =>
              !conversation.deleted &&
              getClientConversationId(conversation.type, conversation.targetId) ===
                previousActiveKey
          ) ?? null
      }
    },
 
    /** 清空会话内存 */
    clear() {
      saveDraftConversationListDebounced.cancel()
      pendingDraftConversations.clear()
      this.conversations = []
      this.conversationReads = {}
      this.activeConversation = null
      this.recentForwardConversationKeys = []
    },
 
    /** 持久化会话读位置 */
    async saveConversationReadRecord(
      target: ConversationRead | ConversationRead[] | null | undefined,
      tx?: DbTransaction
    ): Promise<void> {
      let targets: ConversationRead[] = []
      if (Array.isArray(target)) {
        targets = target
      } else if (target) {
        targets = [target]
      }
      const records = targets.map((record) => toConversationReadDO(record))
      if (records.length === 0) {
        return
      }
      const db = getDb()
      if (tx) {
        for (const record of records) {
          await db.put('conversationReads', record, tx)
        }
        return
      }
      await db.transaction(['conversationReads'], 'readwrite', async (tx) => {
        for (const record of records) {
          await db.put('conversationReads', record, tx)
        }
      })
    },
 
    /** 应用本地会话读位置 */
    async applyLocalConversationReads(conversations?: Conversation[]) {
      const targetConversations = conversations || this.conversations
      const changedConversations: Conversation[] = []
      for (const conversation of targetConversations) {
        const record = this.getConversationRead(conversation.type, conversation.targetId)
        if (!record) {
          continue
        }
        if (this.applyReadToConversation(conversation, record.messageId)) {
          changedConversations.push(conversation)
          continue
        }
        if (conversation.unreadCount === 0 && !conversation.atMe && !conversation.atAll) {
          continue
        }
        const messages = await getDb().getAllByIndex<MessageDO>(
          'messages',
          'clientConversationId',
          getClientConversationId(conversation.type, conversation.targetId)
        )
        const maxIncomingMessageId = getMaxIncomingNormalMessageId(messages)
        if (maxIncomingMessageId > 0 && maxIncomingMessageId <= record.messageId) {
          conversation.unreadCount = 0
          conversation.atMe = false
          conversation.atAll = false
          changedConversations.push(conversation)
        }
      }
      if (changedConversations.length > 0) {
        await this.saveConversationRecord(changedConversations)
      }
    },
 
    /** 判断消息是否已被会话读位置覆盖 */
    isMessageCoveredByReadPosition(
      conversation: Pick<Conversation, 'targetId' | 'type'>,
      message?: null | { id?: number }
    ): boolean {
      if (!message?.id) {
        return false
      }
      const record = this.getConversationRead(conversation.type, conversation.targetId)
      return !!record && message.id <= record.messageId
    },
 
    /** 判断会话读位置是否覆盖消息编号 */
    isReadPositionCovered(type: number, targetId: number, messageId?: number): boolean {
      if (!messageId) {
        return false
      }
      const record = this.getConversationRead(type, targetId)
      return !!record && record.messageId >= messageId
    },
 
    /** 判断服务端已读位置是否覆盖消息编号 */
    isReportedReadPositionCovered(type: number, targetId: number, messageId?: number): boolean {
      if (!messageId) {
        return false
      }
      const conversation = this.getConversation(type, targetId)
      return (conversation?.reportedReadMessageId || 0) >= messageId
    },
 
    /** 应用读位置到会话 */
    applyReadToConversation(conversation: Conversation, messageId: number): boolean {
      if (!conversation.lastMessageId || conversation.lastMessageId > messageId) {
        return false
      }
      if (conversation.unreadCount === 0 && !conversation.atMe && !conversation.atAll) {
        return false
      }
      conversation.unreadCount = 0
      conversation.atMe = false
      conversation.atAll = false
      return true
    },
 
    /** 应用会话读位置 */
    async applyConversationReadList(
      records: ImConversationReadApi.ConversationReadRespVO[],
      isActive?: () => boolean
    ): Promise<void> {
      if (records.length === 0) {
        return
      }
      const changedReads = new Map<string, ConversationRead>()
      const changedConversations = new Map<string, Conversation>()
      const changedMessages = new Map<string, MessageDO>()
      const db = getDb()
      const messageStore = useMessageStore()
 
      // 1. 按读位置更新会话未读和频道已读态
      for (const record of records) {
        if (isActive && !isActive()) {
          return
        }
        if (!isValidConversationReadRecord(record)) {
          continue
        }
        const clientConversationId = getClientConversationId(
          record.conversationType,
          record.targetId
        )
        let storedMessages: MessageDO[] | undefined
        const getStoredMessages = async () => {
          if (!storedMessages) {
            storedMessages = await db.getAllByIndex<MessageDO>(
              'messages',
              'clientConversationId',
              clientConversationId
            )
          }
          return storedMessages
        }
        const current = this.conversationReads[clientConversationId]
        const messageId = Math.max(record.messageId, current?.messageId || 0)
        const conversation = this.getConversation(record.conversationType, record.targetId)
        if (conversation && record.messageId > (conversation.reportedReadMessageId || 0)) {
          conversation.reportedReadMessageId = record.messageId
          changedConversations.set(clientConversationId, conversation)
        }
        if (!current || messageId > current.messageId) {
          const next = {
            conversationType: record.conversationType,
            targetId: record.targetId,
            messageId,
            updateTime: record.updateTime
          }
          this.conversationReads[clientConversationId] = next
          changedReads.set(clientConversationId, next)
        }
 
        if (conversation && this.applyReadToConversation(conversation, messageId)) {
          changedConversations.set(clientConversationId, conversation)
        } else if (conversation) {
          const maxIncomingMessageId = getMaxIncomingNormalMessageId(await getStoredMessages())
          if (maxIncomingMessageId > 0 && maxIncomingMessageId <= messageId) {
            conversation.unreadCount = 0
            conversation.atMe = false
            conversation.atAll = false
            changedConversations.set(clientConversationId, conversation)
          }
        }
        if (record.conversationType !== ImConversationType.CHANNEL) {
          continue
        }
        const memoryMessages = messageStore.getMessages(clientConversationId)
        for (const message of memoryMessages) {
          if (
            message.id &&
            message.id <= messageId &&
            message.receiptStatus !== ImMessageReceiptStatus.DONE
          ) {
            message.receiptStatus = ImMessageReceiptStatus.DONE
          }
        }
        for (const message of await getStoredMessages()) {
          if (
            message.id &&
            message.id <= messageId &&
            message.receiptStatus !== ImMessageReceiptStatus.DONE
          ) {
            message.receiptStatus = ImMessageReceiptStatus.DONE
            changedMessages.set(message.messageKey, message)
          }
        }
      }
 
      // 2. 持久化本轮变更
      if (
        changedReads.size === 0 &&
        changedConversations.size === 0 &&
        changedMessages.size === 0
      ) {
        return
      }
      if (isActive && !isActive()) {
        return
      }
      const stores: Array<'conversationReads' | 'conversations' | 'messages'> = []
      if (changedReads.size > 0) {
        stores.push('conversationReads')
      }
      if (changedConversations.size > 0) {
        stores.push('conversations')
      }
      if (changedMessages.size > 0) {
        stores.push('messages')
      }
      await db.transaction(stores, 'readwrite', async (tx) => {
        if (changedReads.size > 0) {
          await this.saveConversationReadRecord([...changedReads.values()], tx)
        }
        if (changedConversations.size > 0) {
          await this.saveConversationRecord([...changedConversations.values()], tx)
        }
        for (const message of changedMessages.values()) {
          await db.put('messages', message, tx)
        }
      })
    },
 
    /** 增量拉取会话读位置 */
    async pullConversationReads(isActive?: () => boolean): Promise<void> {
      await runIncrementalPull(
        StorageKeys.settings.conversationReadPullCursor,
        apiPullMyConversationReadList,
        async (records) => {
          if (isActive && !isActive()) {
            return false
          }
          await this.applyConversationReadList(records, isActive)
          if (isActive && !isActive()) {
            return false
          }
          return true
        },
        isActive
      )
    },
 
    /** 执行会话记录持久化 */
    async saveConversationRecord(
      target: Conversation | Conversation[] | null | undefined,
      tx?: DbTransaction
    ): Promise<void> {
      const db = getDb()
      const conversations = (Array.isArray(target) ? target : (target ? [target] : [])).map(
        (conversation) => toConversationDO(conversation)
      )
      if (conversations.length === 0) {
        return
      }
      if (tx) {
        for (const conversation of conversations) {
          await db.put('conversations', conversation, tx)
        }
        return
      }
      await db.transaction(['conversations'], 'readwrite', async (tx) => {
        for (const conversation of conversations) {
          await db.put('conversations', conversation, tx)
        }
      })
    },
 
    /** 持久化单个会话 */
    saveConversation(conversation: Conversation | null | undefined, tx?: DbTransaction): void {
      if (!conversation) {
        return
      }
      void this.saveConversationRecord(conversation, tx).catch((error) =>
        console.warn('[IM conversationStore] 会话写入失败', error)
      )
    },
 
    /** 持久化会话列表 */
    saveConversationList(conversations?: Conversation[] | null, tx?: DbTransaction): void {
      if (this.loading && !tx) {
        return
      }
      void this.saveConversationRecord(conversations || this.conversations, tx).catch((error) =>
        console.warn('[IM conversationStore] 会话写入失败', error)
      )
    },
 
    /** 确保会话存在 */
    ensureConversation(info: {
      avatar: string
      name: string
      silent?: boolean
      targetId: number
      type: number
    }): Conversation {
      // 1. 创建不存在的会话
      let conversation = this.getConversation(info.type, info.targetId)
      if (!conversation) {
        conversation = this.createEmptyConversation(
          info.type,
          info.targetId,
          info.name,
          info.avatar,
          info.silent
        )
        this.conversations.unshift(conversation)
      } else if (conversation.deleted) {
        // 2. 恢复软删除会话
        conversation.deleted = false
        conversation.name = info.name || conversation.name
        conversation.avatar = info.avatar || conversation.avatar
        if (info.silent !== undefined) {
          conversation.silent = info.silent
        }
      } else {
        // 3. 同步会话展示元数据
        if (info.name) {
          conversation.name = info.name
        }
        if (info.avatar) {
          conversation.avatar = info.avatar
        }
        if (info.silent !== undefined) {
          conversation.silent = info.silent
        }
      }
      return conversation
    },
 
    /** 打开或创建会话 */
    openConversation(
      targetId: number,
      type: number,
      name: string,
      avatar: string,
      options?: { silent?: boolean }
    ): Conversation {
      // 1. 确保会话在列表中
      const conversation = this.ensureConversation({
        type,
        targetId,
        name,
        avatar,
        silent: options?.silent
      })
      // 2. 激活会话并保存
      this.setActiveConversation(conversation)
      this.saveConversation(conversation)
      return conversation
    },
 
    /** 设置当前会话 */
    setActiveConversation(conversation: Conversation | null) {
      this.activeConversation = conversation
      if (!conversation) {
        return
      }
      // 懒加载消息并保存会话摘要
      void useMessageStore().ensureConversationMessageListLoaded(conversation)
      this.saveConversation(conversation)
    },
 
    /** 创建空会话 */
    createEmptyConversation(
      type: number,
      targetId: number,
      name: string,
      avatar: string,
      silent = false
    ): Conversation {
      return {
        targetId,
        type,
        name,
        avatar,
        lastContent: '',
        lastSendTime: 0,
        unreadCount: 0,
        deleted: false,
        top: false,
        silent,
        atMe: false,
        atAll: false
      }
    },
 
    /** 设置置顶 */
    setConversationTop(type: number, targetId: number, top: boolean) {
      const conversation = this.getConversation(type, targetId)
      if (!conversation) {
        return
      }
      conversation.top = top
      this.saveConversation(conversation)
    },
 
    /** 设置免打扰 */
    setConversationSilent(type: number, targetId: number, silent: boolean) {
      const conversation = this.getConversation(type, targetId)
      if (!conversation) {
        return
      }
      conversation.silent = silent
      this.saveConversation(conversation)
    },
 
    /** 删除会话 */
    removeConversation(type: number, targetId: number) {
      // 1. 标记会话删除
      const conversation = this.getConversation(type, targetId)
      if (!conversation) {
        return
      }
      if (this.activeConversation === conversation) {
        this.activeConversation = null
      }
      conversation.deleted = true
      // 2. 删除会话关联的消息和草稿
      useMessageStore().deleteConversationMessageList(type, targetId)
      this.clearConversationDraft(conversation)
      this.saveConversation(conversation)
    },
 
    /** 删除私聊会话 */
    removePrivateConversation(friendId: number) {
      this.removeConversation(ImConversationType.PRIVATE, friendId)
    },
 
    /** 删除群聊会话 */
    removeGroupConversation(groupId: number) {
      this.removeConversation(ImConversationType.GROUP, groupId)
    },
 
    /** 标记会话已读 */
    markConversationRead(type: number, targetId: number, messageId?: number): void {
      const conversation = this.getConversation(type, targetId)
      if (!conversation) {
        return
      }
      const key = getClientConversationId(type, targetId)
      const current = this.conversationReads[key]
      const readMessageIdAdvanced = !!messageId && messageId > (current?.messageId || 0)
      if (
        conversation.unreadCount === 0 &&
        !conversation.atMe &&
        !conversation.atAll &&
        !readMessageIdAdvanced
      ) {
        return
      }
      conversation.unreadCount = 0
      conversation.atMe = false
      conversation.atAll = false
      if (readMessageIdAdvanced) {
        const record = createConversationRead(type, targetId, messageId)
        this.conversationReads[key] = record
        void getDb()
          .transaction(['conversations', 'conversationReads'], 'readwrite', async (tx) => {
            await this.saveConversationRecord(conversation, tx)
            await this.saveConversationReadRecord(record, tx)
          })
          .catch((error) =>
            console.warn(
              '[IM conversationStore] 会话已读写入失败',
              {
                conversationType: type,
                targetId,
                messageId,
                conversationKey: key
              },
              error
            )
          )
        return
      }
      this.saveConversation(conversation)
    },
 
    /** 标记会话已上报服务端读位置 */
    markConversationReadReported(type: number, targetId: number, messageId?: number): void {
      if (!messageId) {
        return
      }
      const conversation = this.getConversation(type, targetId)
      if (!conversation || messageId <= (conversation.reportedReadMessageId || 0)) {
        return
      }
      conversation.reportedReadMessageId = messageId
      this.saveConversation(conversation)
    },
 
    // ==================== 最近转发 ====================
 
    /** 推送最近转发会话 */
    pushRecentForwardConversationKeyList(keys: string[]) {
      if (!keys || keys.length === 0) {
        return
      }
      const merged = [...keys, ...this.recentForwardConversationKeys]
      this.recentForwardConversationKeys = [...new Set(merged)].slice(
        0,
        CONVERSATION_RECENT_FORWARD_MAX
      )
      this.saveRecentForwardConversationKeyList()
    },
 
    /** 移除最近转发会话 */
    removeRecentForwardConversationKey(key: string) {
      const index = this.recentForwardConversationKeys.indexOf(key)
      if (index === -1) {
        return
      }
      this.recentForwardConversationKeys.splice(index, 1)
      this.saveRecentForwardConversationKeyList()
    },
 
    /** 保存最近转发会话 */
    saveRecentForwardConversationKeyList() {
      void getDb()
        .setSetting(
          StorageKeys.settings.recentForwardConversationKeys,
          this.recentForwardConversationKeys.slice(0, CONVERSATION_RECENT_FORWARD_MAX)
        )
        .catch((error) => console.warn('[IM conversationStore] 最近转发列表写入失败', error))
    },
 
    // ==================== 会话维护 ====================
 
    /** 重排会话 */
    sortConversationList() {
      this.conversations.sort((a, b) => (b.lastSendTime || 0) - (a.lastSendTime || 0))
      this.saveConversationList(this.conversations)
    },
 
    /** 同步会话展示元数据 */
    updateConversation(
      type: number,
      targetId: number,
      info: { avatar?: string; name?: string; silent?: boolean }
    ) {
      const conversation = this.getConversation(type, targetId)
      if (!conversation) {
        return
      }
      let changed = false
      if (info.name && conversation.name !== info.name) {
        conversation.name = info.name
        changed = true
      }
      if (info.avatar !== undefined && conversation.avatar !== info.avatar) {
        conversation.avatar = info.avatar || ''
        changed = true
      }
      if (info.silent !== undefined && conversation.silent !== info.silent) {
        conversation.silent = info.silent
        changed = true
      }
      if (changed) {
        this.saveConversation(conversation)
      }
    },
 
    // ==================== 草稿 ====================
 
    /** 获取草稿 */
    getConversationDraft(conversation: { targetId: number; type: number; }): Conversation['draft'] | undefined {
      return this.getConversation(conversation.type, conversation.targetId)?.draft
    },
 
    /** 设置草稿 */
    setConversationDraft(
      conversation: { targetId: number; type: number; },
      snapshot: NonNullable<Conversation['draft']>
    ): void {
      if (!snapshot.plain.trim() && !snapshot.reply) {
        this.clearConversationDraft(conversation)
        return
      }
      const target = this.getConversation(conversation.type, conversation.targetId)
      if (!target) {
        return
      }
      target.draft = snapshot
      this.scheduleConversationDraftSave(target)
    },
 
    /** 清除草稿 */
    clearConversationDraft(conversation: { targetId: number; type: number; }): void {
      const target = this.getConversation(conversation.type, conversation.targetId)
      if (!target?.draft) {
        return
      }
      target.draft = undefined
      this.scheduleConversationDraftSave(target)
    },
 
    /** 设置回复草稿 */
    setConversationReplyDraft(
      conversation: { targetId: number; type: number; },
      quote: NonNullable<Conversation['draft']>['reply']
    ) {
      if (!quote) {
        return
      }
      const existing = this.getConversationDraft(conversation)
      this.setConversationDraft(conversation, {
        html: existing?.html ?? '',
        plain: existing?.plain ?? '',
        reply: quote
      })
    },
 
    /** 清除回复草稿 */
    clearConversationReplyDraft(conversation: { targetId: number; type: number; }): void {
      const existing = this.getConversationDraft(conversation)
      if (!existing?.reply) {
        return
      }
      this.setConversationDraft(conversation, { ...existing, reply: undefined })
    },
 
    /** 调度草稿保存 */
    scheduleConversationDraftSave(conversation: Conversation): void {
      pendingDraftConversations.add(conversation)
      saveDraftConversationListDebounced()
    },
 
    /** 立即保存草稿 */
    flushConversationDraftSave(): void {
      saveDraftConversationListDebounced.flush()
    }
  }
})
 
export const useConversationStoreWithOut = () => useConversationStore()
 
/** 合并草稿写入 */
const saveDraftConversationListDebounced = createDraftDebounce(() => {
  const conversations = [...pendingDraftConversations]
  pendingDraftConversations.clear()
  if (conversations.length === 0) {
    return
  }
  void useConversationStoreWithOut()
    .saveConversationRecord(conversations)
    .catch((error) => console.warn('[IM conversationStore] 草稿写入失败', error))
}, PERSIST_DRAFT_DEBOUNCE_MS)
 
if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useConversationStore, import.meta.hot))
}