<template>
  <keep-alive>
  <el-scrollbar height="100%" :noresize="true" ref="scrollContainer" class="bg-gray-50 overflow-x-hidden" @scroll="handleScroll">
    <MessageContent :message="item" v-for="item in list" :key="item.id" @recallMessage="recallMessage"/>
  </el-scrollbar>
  </keep-alive>
</template>

<script setup lang="ts">
import MessageContent from './MessageContent.vue'
import {nextTick, onMounted, ref} from 'vue'
import {useMessageLoadStatus, useUserInfoListStore, useUserInfoStore} from '@/stores/counter'
import type {Message} from '@/types/global';
import {listMessage} from "@/api/user";
import {updateReadStatus} from '@/api/content'
const userInfoStore = useUserInfoStore()
const messageLoadStatus = useMessageLoadStatus()
const userInfoListStore = useUserInfoListStore()

const scrollContainer = ref()

const list = ref<Message[]>([])

const emits = defineEmits(['recallMessage', 'onSendSuccess'])

const addMessageToList = (msg:Message) => {
  const type = msg.type
  if (type < 50) {
    console.log('添加消息到列表中')
    list.value.push(msg)
    // 修改最后一个用户的消息体
    const currentUser = userInfoListStore.getUserInfo(msg.customerId as number)
    currentUser.lastMessage = msg.content
    currentUser.loginDate = msg.createTime
    userInfoListStore.setUserInfoList(msg.customerId as number, currentUser)
    return
  }
  if (type === 98) {
    console.log('更新消息为已读')
    list.value.forEach((item:Message) => {
      if (item.cid === msg.cid) {
        item.isRead = true
        item.id = msg.id
      }
    })
  }
  if (type === 100) {
    console.log('撤回消息')
    list.value.forEach((item:Message) => {
      if (item.cid === msg.cid) {
        item.isRetracted = true
        item.id = msg.id
      }
    })
  }
}

// 服务器已收到消息
const onServerConfirmMessage = (msg:Message) => {
  console.log('服务器已收到消息', msg)
  addMessageToList(msg)
  scrollToBottom()
  // 调用父组件清楚footer的消息内容
  emits('onSendSuccess')

}

const addMessage = (msg: Message) => {
  console.log('添加消息，消息的类型是', msg.type,'添加之前的大小', list.value.length)
  const customerId = msg.customerId
  const currentUser = userInfoStore.getUserInfo();
  if (customerId == currentUser.id) {
    console.log('选中的是当前用户，把消息加入到聊天框中')
    list.value.push(msg)
  }
  scrollToBottom()
  console.log('添加之后的大小', list.value.length)
  // 标记未读消息数量 TODO
  const userInfo = userInfoListStore.getUserInfo(customerId as number)
  if (Object.keys(userInfo).length === 0) {
    return
  }
  if (!userInfo.unreadCount) {
    userInfo.unreadCount = 0
  }
  userInfo.unreadCount += 1
  userInfoListStore.setUserInfoList(customerId as number, userInfo)
  scrollToBottom()
}

const addServiceMessage = (msg: Message) => {
  const type = msg.type
  if (type < 50) {
    console.log('添加消息到列表中')
    // 判断消息是否存在了
    const isExist = list.value.some((item:Message) => item.id === msg.id)
    if (!isExist) {
      // 只有当选中的客户是当前客户时，才添加消息
      const currentUser = userInfoStore.getUserInfo();
      if (msg.customerId == currentUser.id) {
        list.value.push(msg)
        scrollToBottom()
      }
      // 修改最后一个用户的消息体
      const receiver = userInfoListStore.getUserInfo(msg.customerId as number)
      receiver.lastMessage = msg.content
      receiver.loginDate = msg.createTime
      if (!receiver.unreadCount) {
        receiver.unreadCount = 0
      }
      receiver.unreadCount += 1
      userInfoListStore.setUserInfoList(msg.customerId as number, receiver)
      return
    }
  }
  if (type === 100) {
    // 修改消息状态
    list.value.map(item => {
      if (item.id === msg.id) {
        item.isRetracted = true
      }
      return item
    })
  }
}

// 客户已读消息
const onCustomerRead = (msg: Message) => {
  list.value.forEach(item => {
    if (item.id == msg.id) {
      item.isRead = true
    }
  })
}
const scrollToBottom = () => {
  nextTick(() => {
    const container = scrollContainer.value.$el.querySelector('.el-scrollbar__wrap')
    container.scrollTop = container.scrollHeight
  })
}


const switchUser = async () => {
  const userInfo = userInfoStore.getUserInfo()
  console.log('char Content switchUser',userInfo)
  resetParams()
  params.value.userIds.push(userInfo.id as number)
  list.value = []
  disabledScroll.value = false
  await loadMoreData()
  const unreadCount = userInfo.unreadCount
  if (unreadCount && unreadCount > 0) {
    await updateReadStatus(userInfo.id as number)
    userInfo.unreadCount = 0
    userInfoListStore.setUserInfoList(userInfo.id as number, userInfo)
  }
  scrollToBottom()
}

const recallMessage = (msg: Message) => {
  emits('recallMessage', msg)
}

const disabledScroll = ref(false)
const isTop = () => {
  const { scrollTop } = scrollContainer.value.wrapRef
  return scrollTop <= 150
}
// 查询消息
const params = ref({
  pageNo: 0,
  pageSize: 30,
  userIds:[] as number[],
})
const resetParams = () => {
  params.value.pageNo = 0
  params.value.pageSize = 30
  params.value.userIds = []
}

// 更新页面消息
const updateListValue = (userId:number, messageList:Message[]) => {
  nextTick(() => {
    list.value = messageList.reverse().concat(list.value)
    scrollToBottom()
  })
}

const userLoadStatus = ref(false)

const loadMoreData = async () => {
  const userId = params.value.userIds[0]
  params.value.pageNo += 1
  try {
    userLoadStatus.value = true
    const result = await listMessage(params.value)
    console.log('当前点击的userId', userId,'消息总数为：', result.total)
    const messageList = result.list as Array<Message>
    console.log('本次用远程服务器加载消息')
    if (messageList.length === result.total) {
      disabledScroll.value = true
    }
    if (messageList.length > 0) {
      updateListValue(userId,messageList)
    }else {
      console.log('消息都加载完了')
      disabledScroll.value = true
    }
  } catch (error) {
    console.error('Error fetching message list:', error)
  }finally {
    userLoadStatus.value = false
  }
}

const setLoadComplete = (userId:number) => {
  disabledScroll.value = true
  messageLoadStatus.setLoadStatus(userId, true)
}

const handleScroll = async (_:any) => {
  console.log('handleScroll','loadMessage: ',userLoadStatus.value,'is top:', isTop())
  if (userLoadStatus.value || disabledScroll.value || !isTop()) {
    return
  }
  // 加载数据
  const container = scrollContainer.value.$el.querySelector('.el-scrollbar__wrap')
  // 计算滚动条距离底部的距离
  const originalScrollBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
  await loadMoreData()
  // 重新计算滚动条的位置
  container.scrollTop = container.scrollHeight - container.clientHeight - originalScrollBottom;
}

defineExpose({
  addMessage,
  switchUser,
  addMessageToList,
  onServerConfirmMessage,
  addServiceMessage,
  onCustomerRead
})

onMounted(() => {
  scrollToBottom()
})
</script>
