import {nextTick, ref} from "vue"
import type Message from "@/mode/Message";
import MessageType from "@/utils/MessageType";
import MessageApi from "@/api/MessageApi";
import type User from "@/mode/User";
import type Chat from "@/mode/Chat";
import {useChatStore} from "@/store/chatStore";

const last = ref('m-0');
//每页显示多少条数据
const pageSize = ref(100)
//页码
const pageNum = ref(1)
/**
 * 加载图片，确保加载完成，消息滚动到最后。
 */
const preloadImages = (arr: any) => {
    let loadedImage = 0
    return new Promise((resolve, reject) => {
        if (arr.length > 0) {
            for (let i = 0; i < arr.length; i++) {
                uni.getImageInfo({
                    src: arr[i],
                    success() {
                        loadedImage++
                        if (loadedImage === arr.length) {
                            resolve(0)
                        }
                    },
                    fail() {
                        reject()
                    }
                })
            }
        } else {
            resolve(0)
        }
    })
}

/**
 * 加载图片，确保加载完成，消息滚动到最后。
 */
const imageLoad = (messageList:Array<Message>) => {
    let srcArr: string[] = []
    if (messageList) {
        messageList.forEach((item) => {
            if (item.messageType === MessageType.image && item.extend && item.extend.url) {
                srcArr.push(item.extend.url)
            }
        })
    }
    preloadImages(srcArr).finally(()=>{
        toBottom()
    })
}

/**
 * 聊天记录滚动到最下面
 */
const toBottom = () => {
    last.value = ''
    nextTick().then(r =>{
        last.value = 'm-last'
    })
}



export  {last, imageLoad,toBottom}