import ChatType from '@/utils/ChatType'
import GroupApi from '@/api/GroupApi'
import type User from '@/mode/User'
import UserApi from '@/api/UserApi'
import {ref} from 'vue'
import {useChatStore} from '@/store/chatStore'
import {useUserStore} from '@/store/userStore'
import MessageApi from "@/api/MessageApi";
import type Message from "@/mode/Message";
import {imageLoad} from "@/hooks/useMessageImageLoad";
import type Chat from "@/mode/Chat";
import ChatApi from "@/api/ChatApi";

//用户
const users = ref<Array<User>>()
//群人数
const count = ref(0)

const isValidatedUser = ref(true)
//是否是管理员
const isMaster = ref(false)
//是否是有效用户

function loadMessages(chatId: string, user: User, chatType: string, chat: Chat) {
  MessageApi.list(chatId, user.id, chatType, 100).then((res) => {
    //读取消息
    res.data.forEach((item: Message) => {
      useChatStore().addToMessageList(item, chat,false)
    })
    const messageList = useChatStore().chatMessage.get(chatId)
    if(messageList){
      imageLoad(messageList)
    }
  })
}

const loadUserOrGroup = (chat: Chat, user: User) => {
  const chatId = chat.id;
  const chatType = chat.type;
  useUserStore().storeUser(user.id, {
    name: user.name,
    avatar: user.avatar
  })
  if (chatId && chatType === ChatType.GROUP) {
    GroupApi.users(chatId).then((res) => {
      const chatList: Array<Chat> = []
      res.data.forEach((item: User) => {
        useUserStore().storeUser(item.id, {
          name: item.name,
          avatar: item.avatar
        })
        chatList.push({
          type: ChatType.FRIEND,
          unreadCount: 0,
          id: item.id,
          name: item.name,
          avatar: item.avatar
        })
        useChatStore().updateChat(item.id, item.name, item.avatar,false,false)
      })
      ChatApi.batch(chatList)
      users.value = res.data
      if(users.value){
        isValidatedUser.value = users.value.some((item) => item.id === user?.id)
        if(isValidatedUser.value){
          //第一次加载，从数据库中取100条，有序插入到聊天记录里
          loadMessages(chatId, user, chatType, chat);
        }
      }
      count.value = res.data.length
    })
    GroupApi.get(chatId).then((res) => {
      const group = res.data
      isMaster.value = group.master === user?.id
      useChatStore().updateChat(chatId, group.name, group.avatar)
    })
  } else {
    isValidatedUser.value = true
    UserApi.getUser(chatId).then((res) => {
      const chatUser = res.data
      useChatStore().updateChat(chatUser.id, chatUser.name, chatUser.avatar)
      useUserStore().storeUser(chatUser.id, {
        name: chatUser.name,
        avatar: chatUser.avatar
      })
      loadMessages(chatId, user, chatType, chat);
    })
  }
}

export { loadUserOrGroup, users, count, isMaster, isValidatedUser }
