import { DisplayMessage, messageStore } from '@/store/messagesStore'
import { getTargetIdFromDisplayMsg } from '@/utils/chatutils'
import { MyAppDatabase } from './index'

export default class ChatMessageDB extends MyAppDatabase {
  static instance: ChatMessageDB
  static getInstance() {
    if (!ChatMessageDB.instance) {
      ChatMessageDB.instance = new ChatMessageDB()
    }
    return ChatMessageDB.instance
  }

  async saveMsg(message: DisplayMessage, masterId: string) {
    const latestMsg = await this.chatMessage
      .filter((item) => {
        return item.masterId === masterId
      })
      .reverse()
      .first()

    return this.chatMessage.add({
      ...message,
      masterId,
      hideDatetime: messageStore.shouldDisplayMessageDate(
        message.datetime,
        latestMsg?.datetime || 0,
      ),
    })
  }

  async deleteMsg({ uuid, logid }: { uuid?: string; logid?: string }) {
    const updateChatList = async (
      masterId: string,
      target: string,
      deletedMsgDatetime: number,
    ) => {
      const latestedMsg = await this.getLatestedMessage(masterId, target)

      if (latestedMsg) {
        /* 如果和target还有聊天消息 */
        // latestedMsg.content.content
        this.chatListCard
          .filter((i) => i.masterId === masterId && i.targetId === target)
          .modify((i) => {
            i.content = latestedMsg.content.content as string
            i.datetime = latestedMsg.datetime
          })
      } else {
        /* 如果和target没有聊天消息 */
        this.chatListCard
          .filter((i) => i.masterId === masterId && i.targetId === target)
          .modify((i) => {
            i.content = ''
            i.datetime = deletedMsgDatetime
          })
      }
    }

    if (uuid) {
      const item = await this.chatMessage.where('uuid').equals(uuid).first()
      await this.chatMessage.where('uuid').equals(uuid).delete()
      item &&
        updateChatList(
          item?.masterId,
          getTargetIdFromDisplayMsg(item),
          item?.datetime,
        )
    } else if (logid) {
      const item = await this.chatMessage.where('logid').equals(logid).first()
      await this.chatMessage.where('logid').equals(logid).delete()
      item &&
        updateChatList(
          item?.masterId,
          getTargetIdFromDisplayMsg(item),
          item?.datetime,
        )
    } else {
      throw new Error('没有uuid或者logid')
    }
  }
  updateMsg(
    { uuid, logid }: { uuid?: string; logid?: string },
    newMsg: Partial<DisplayMessage>,
  ) {
    if (uuid) {
      return this.chatMessage.where('uuid').equals(uuid).modify(newMsg)
    } else if (logid) {
      return this.chatMessage.where('logid').equals(logid).modify(newMsg)
    } else {
      throw new Error('没有uuid或者logid')
    }
  }

  async thePersonAlreadyInChatList(masterId: string, personId: string) {
    return (
      (await this.chatMessage
        .filter(
          (i) =>
            (i.masterId === masterId &&
             ((i.state === null && i.from === personId) || (i.state !== null && i.target === personId)))
        )
        .count()) !== 0
    )
  }

  /* from表示自己的address，target表示对话人的address */
  getMessage(from: string, target: string) {
    return this.chatMessage
      .filter((item) => {
        return (
          item.masterId === from &&
          ((item.state === null && item.from === target) ||
            (item.state !== null && item.target === target))
        )
      })
      .toArray()
  }

  /* wo获取和ta之间最新的消息 */
  async getLatestedMessage(from: string, target: string) {
    const ret = await this.chatMessage
      .filter((item) => {
        return (
          item.masterId === from &&
          ((item.state === null && target === item.from) ||
            (item.state !== null && target === item.target))
        )
      })
      .count()
    console.log(ret, 'show count')

    return this.chatMessage
      .filter((item) => {
        return (
          item.masterId === from &&
          ((item.state === null && target === item.from) ||
            (item.state !== null && target === item.target))
        )
      })
      .last()
  }

  deleteMsgGroup(masterId: string, targetId: string) {
    this.chatMessage
      .filter((item) => {
        return (
          item.masterId === masterId &&
          (item.from === item.masterId ? item.target : item.from) === targetId
        )
      })
      .delete()
  }
}
