import { reactive, ref, computed, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useSocketStore, useMessageStore } from "@/store";
import { RONGIMCALL_OPEN, RONGIMCALL_HISTORY, RONGIMCALL_SEND } from '@/api';
import { Toast, format } from '@/utils';


function useMessageData() {

	const useScoket = useSocketStore();
	const useMessage = useMessageStore();
	const { messageMap } = storeToRefs(useMessage);

	const lowerThreshold = ref(80)
	const distanceFromBottom = ref(0)

	const newMessageCount = ref(0)
	const dataList = ref([]);
	const loadedAll = ref(false);
	const isLoading = ref(false);
	const historyMessageQuery = reactive({
		page: 1,
		pagesize: 20,
		type: 'service'
	})

	const isOpenning = ref(false)

	const channel = ref('')
	const channelData = ref(null)

	watch(
		() => (messageMap.value),
		(newVal, oldVal) => {
			if (channel.value) {
				const info = newVal[channel.value]
				channelData.value = info
				console.log("messageMap.value[channel.value]", info)
				dataList.value = info.messageList
				newMessageCount.value =
					distanceFromBottom.value > lowerThreshold.value ?
						info.unreadCount : 0;
				console.log('newMessageCount.value', newMessageCount.value)
			}
		},
		{
			deep: true
		}
	)


	function resetHistoryQuery() {
		historyMessageQuery.page = 1
		historyMessageQuery.pagesize = 20
		historyMessageQuery.type = 'service'
		loadedAll.value = false
		isLoading.value = false
	}

	// 获取历史消息列表
	function fetchHistoryMessageList() {
		return new Promise(async (resolve, reject) => {
			if (loadedAll.value) return;
			if (isLoading.value) return;
			isLoading.value = true;

			try {
				const result = await RONGIMCALL_HISTORY(historyMessageQuery, { isLoading: true });
				const { lists, total } = result.data;
				for (let i = 0; i < lists.length; i++) {
					const msgInfo = {
						...lists[i],
						msg: JSON.parse(lists[i].msg)
					}
					useMessage.updateMessageList(channel.value, msgInfo, 'unshift')
				}
				loadedAll.value = lists.length < historyMessageQuery.pagesize;
				historyMessageQuery.page = historyMessageQuery.page + 1;
				isLoading.value = false;
				resolve(result.data);
			}
			catch (err) {
				isLoading.value = false;
				reject(err);
			}
		})
	}


	function openService() {
		if (isOpenning.value) return;
		isOpenning.value = true;
		resetHistoryQuery();
		useMessage.openChannel({
			type: 'service',
			socket_id: useScoket.socketId
		}).then(async (res) => {
			channel.value = res.data.auth.channel
			try {
				const data = await fetchHistoryMessageList();
				if (data.total < 1) {
					const val = { ...res.data }
					delete val.auth
					dataList.push(val)
					useMessage.updateMessageList(channel.value, val, 'unshift')
				}
				if (data.lists.length > 0) {
					let result = data.lists[0]
					let lastTime = result ? result.indate : (Date.now() / 1000).toFixed(0) - 0
					useMessage.updateGlobalMapLasttime(`serviceChannel`, lastTime)
				}
			}
			catch (err) { }
			finally {
				isOpenning.value = false;
			}
		})
			.catch(() => {
				isOpenning.value = false;
			})
	}
	openService()



	return {
		useMessage,
		channel,
		channelData,
		dataList,
		newMessageCount,
		lowerThreshold,
		distanceFromBottom,
		isLoading,
		fetchHistoryMessageList,
		openService
	}
}



export default useMessageData