import { useRef, useState, useEffect, } from 'react';
import useConversationStore from '@/stores/ConversationStore';
import { useShallow } from 'zustand/react/shallow';
import { Image, Modal, Button } from 'antd';
import MessagesList from './MessagesList';
import { fetchCleanUnreadMsgCount, fetchMessages, MESSAGE_PAGE_SIZE, UNREAD_MARK } from '@/actions/ConversationActions';
import useAuthStore from '@/stores/AuthStore';
import { useVisibilityState } from '@/hooks/useVisibilityState';
import ConversationNewItem from './ConversationsNewItem';
// import EmailEditor from './Input/bak/EmailEditor';
import EmailEditorPopup from './Input/EmailEditorPopup';
import EmailDetail from './Components/EmailDetail';
import { useOrderStore, } from "@/stores/OrderStore";
import { isEmpty } from '@/utils/commons';
import useStyleStore from '@/stores/StyleStore';
import EmailListDrawer from './Components/EmailListDrawer';
const MessagesWrapper = ({ updateRead = true, forceGetMessages }) => {
const userId = useAuthStore((state) => state.loginUser.userId);
const [mobile] = useStyleStore(state => [state.mobile]);
const [currentConversation, updateCurrentConversation, setCurrentConversation] = useConversationStore((state) => [state.currentConversation, state.updateCurrentConversation, state.setCurrentConversation]);
// const conversationsList = useConversationStore((state) => state.conversationsList);
const activeMessages = useConversationStore(useShallow((state) => (state.currentConversation.sn && state.activeConversations[state.currentConversation.sn] ? state.activeConversations[state.currentConversation.sn]: [])));
// const addToConversationList = useConversationStore((state) => state.addToConversationList);
const receivedMessageList = useConversationStore((state) => state.receivedMessageList);
const setMsgLoading = useConversationStore((state) => state.setMsgLoading);
const refreshTotalNotify = useConversationStore(useShallow((state) => state.refreshTotalNotify));
const currentConversationSN = useConversationStore(useShallow((state) => state.currentConversation.sn));
const currentConversationColiSN = useConversationStore(useShallow((state) => state.currentConversation.coli_sn));
const [orderDetail, customerDetail] = useOrderStore(state => [state.orderDetail, state.customerDetail ]);
const isVisible = useVisibilityState();
const [longList, setLongList] = useState([]);
const [longListLoading, setLongListLoading] = useState(false);
const [shouldScrollBottom, setShouldScrollBottom] = useState(true);
const prevSN = useRef(currentConversationSN);
const prevColiSN = useRef(currentConversationColiSN);
useEffect(() => {
if (!mobile) {
prevSN.current = currentConversationSN
prevColiSN.current = currentConversationColiSN
}
return () => {}
}, [])
useEffect(() => {
// console.log('effect sn', currentConversationSN, prevSN);
// if (isEmpty(prevSN) || currentConversationSN === prevSN) {
// return () => {};
// }
// console.log('effect sn', currentConversationSN, prevSN.current, 'llllllllllllllllll');
// console.log('if fetch', (activeMessages.length))
if (currentConversationSN && (mobile || prevSN.current !== currentConversationSN) && (activeMessages.length < 20 || forceGetMessages !== undefined)) {
// console.log('effect sn NOT empty GO fetch', currentConversationSN);
getFirstPageMessages(currentConversation);
} else if (currentConversationSN) {
// console.log('--------------------- set ref longlist', currentConversationSN, currentConversationColiSN)
prevSN.current = currentConversationSN;
prevColiSN.current = currentConversationColiSN;
}
setShouldScrollBottom(true);
return () => {};
}, [currentConversationSN]);
useEffect(() => {
// console.log('effect coli_sn', currentConversationSN, currentConversationColiSN, prevColiSN.current, 'xxxxxxxxxxxx');
// console.log('effect coli_sn After if', currentConversationSN, currentConversationNeedLoaded);
if (currentConversation.sn && (mobile || prevColiSN.current !== currentConversationColiSN)) {
// console.log('effect coli_sn NOT empty GO fetch', currentConversationSN);
getFirstPageMessages({...currentConversation, });
}
setShouldScrollBottom(true);
return () => {};
}, [currentConversationColiSN]);
useEffect(() => {
setLongList(activeMessages);
const thisLastTime = activeMessages.length > 0 ? activeMessages[0].msgtime : '';
const loadNextPage = !(activeMessages.length === 0 || activeMessages.length < MESSAGE_PAGE_SIZE);
updateCurrentConversation({ lasttime: thisLastTime, loadNextPage, });
return () => {};
}, [activeMessages, currentConversationSN]);
useEffect(() => {
const cleanCurrent = currentConversation.unread_msg_count < UNREAD_MARK; // || currentConversation?.last_message?.actionId; // todo: 取direction, msg_direction === 'outbound' ?? after send
// if (updateRead === true && isVisible && currentConversation.opi_sn && activeMessages.length > 0) {
if (updateRead === true && isVisible && currentConversation.opi_sn && cleanCurrent) {
fetchCleanUnreadMsgCount({ opisn: currentConversation.opi_sn, conversationid: currentConversation.sn });
updateCurrentConversation({ unread_msg_count: 0 });
refreshTotalNotify();
}
return () => {};
}, [activeMessages.length, isVisible, currentConversationSN]);
let refreshing = false;
const getFirstPageMessages = async (item) => {
if (refreshing !== false) {
return false;
}
refreshing = true;
setMsgLoading(true);
setLongList([]);
const data = await fetchMessages({
conversationid: item.sn,
opisn: forceGetMessages ? item.opi_sn || '' : userId,
whatsappid: item.whatsapp_phone_number,
lasttime: '',
coli_sn: item.coli_sn || '',
})
prevSN.current = item.sn;
prevColiSN.current = item.coli_sn;
const thisLastTime = data.length > 0 ? data[0].msgtime : ''; // orgmsgtime
const loadNextPage = !(data.length === 0 || data.length < MESSAGE_PAGE_SIZE);
updateCurrentConversation({ lasttime: thisLastTime, loadNextPage, });
// setPrevSN(item.sn);
setMsgLoading(false);
receivedMessageList(item.sn, data);
refreshing = false;
};
const getMoreMessages = async () => {
setShouldScrollBottom(false);
setLongListLoading(true);
const data = await fetchMessages({
conversationid: currentConversation.sn,
opisn: currentConversation.opi_sn,
whatsappid: currentConversation.whatsapp_phone_number,
lasttime: currentConversation?.lasttime || '',
coli_sn: currentConversation.coli_sn || '',
})
setLongListLoading(false);
setLongList(prevValue => data.concat(prevValue));
const thisLastTime = data.length > 0 ? data[0].msgtime : '';
const loadNextPage = !(data.length === 0 || data.length < MESSAGE_PAGE_SIZE);
updateCurrentConversation({ lasttime: thisLastTime, loadNextPage, });
return data.length;
};
const reference = useRef(null);
const [previewVisible, setPreviewVisible] = useState(false);
const [previewSrc, setPreviewSrc] = useState();
const onPreviewClose = () => {
setPreviewSrc('');
setPreviewVisible(false);
};
const handlePreview = (msg) => {
switch (msg.whatsapp_msg_type) {
case 'image':
setPreviewVisible(true);
setPreviewSrc(msg.data.uri);
return false;
case 'document':
window.open(msg.data.link || msg.data.uri, '_blank', 'noopener,noreferrer');
return false;
default:
return false;
}
};
const [contactsModalVisible, setContactsModalVisible] = useState(false);
const [contactListData, setContactListData] = useState([]);
const [newChatModalVisible, setNewChatModalVisible] = useState(false);
const [newChatFormValues, setNewChatFormValues] = useState({});
const handleContactItemClick = (contact) => {
setNewChatFormValues(prev => ({...prev, phone_number: contact.wa_id, name: contact.name }));
setNewChatModalVisible(true);
return ;
}
const handleContactListClick = (data) => {
setContactListData(data);
setContactsModalVisible(true);
}
const handleContactClick = (data) => {
return data.length > 1 ? handleContactListClick(data) : handleContactItemClick(data[0]);
}
// EmailEditor
const [setEditorOpen, setEditorProps] = useConversationStore((state) => [state.setEditorOpen, state.setEditorProps]);
const [openEmailEditor, setOpenEmailEditor] = useState(false);
const [fromEmail, setFromEmail] = useState('');
const [ReferEmailMsg, setReferEmailMsg] = useState('');
const [action, setAction] = useState('')
const onOpenEditor = (emailMsgContent, action='reply') => {
const { from, to } = emailMsgContent; // msgtext
console.log('emailMsgContent', emailMsgContent);
setOpenEmailEditor(true);
// setFromEmail(to);
setFromEmail(action === 'edit' ? from : to)
setReferEmailMsg({...emailMsgContent, order_opi: Number(orderDetail?.opi_sn || userId)});
setAction(action)
setEditorProps({
action,
fromEmail: action === 'edit' ? from : to,
fromUser: Number(orderDetail?.opi_sn || userId),
fromOrder: currentConversation.coli_sn,
oid: orderDetail?.order_no || emailMsgContent?.coli_id,
receiverName: customerDetail.name,
quoteid: emailMsgContent.mai_sn || emailMsgContent.id,
conversationid: currentConversation.sn,
subject: emailMsgContent.subject,
});
// setEditorOpen(true);
};
const [openEmailDetail, setOpenEmailDetail] = useState(false);
const [emailDetail, setEmailDetail] = useState({});
const [initialPosition, setInitialPosition] = useState({})
const [initialSize, setInitialSize] = useState({})
const [emailItem, setEmailItem] = useState({});
const onOpenEmail = (emailMsg) => {
// setOpenEmailDetail(true);
// setEmailDetail({...emailMsg, order_opi: Number(orderDetail?.opi_sn || userId)});
setEmailItem({ MAI_SN: emailMsg.msgtext?.email?.mai_sn, MAI_Subject: emailMsg.msgtext?.email?.subject, SenderReceiver: '', MAI_SendDate: '' })
}
const [emailList, setEmailList] = useState([]);
useEffect(() => {
const _emailList = longList
.filter((item) => item.msg_source === 'email')
.map((ele) => ({
...ele,
MAI_SN: ele.msgtext?.email?.mai_sn,
MAI_Subject: ele.msgtext?.email?.subject,
SenderReceiver: ele.from,
MAI_SendDate: ele.msgtime,
Direction: ele.msg_direction === 'inbound' ? '收' : '发',
}))
.reverse()
setEmailList(_emailList);
setEmailItem({});
}, [longList]);
return (
<>
setContactsModalVisible(false)} footer={null}>
{contactListData.map((contact) => (
))}
{
setNewChatModalVisible(false)
setContactsModalVisible(false)
}}
onCancel={() => setNewChatModalVisible(false)}
/>
{/* */}
{/* */}
>
)
};
export default MessagesWrapper;