import React, { useEffect, useState } from 'react';
import { InterDataType, InterListType } from '~/api/interface';
import { selectUserListType, selectUserMessageType } from '~/api/interface/systemManageType';
import { SystemManageAPI } from '~/api';
import MessageChatActionView from '~/pages/messageManage/messageChat/comp/messageChatAction';
import { Image } from 'antd';

// 当前消息类型
type DataType = InterDataType<selectUserListType>;
// 列表类型
type ListType = InterListType<selectUserMessageType>;

// 定时任务
let getMessageTimer: NodeJS.Timer;

const MessageChatContentView: React.FC<{ currentData: DataType[0]; userAccountId: number }> = ({
  currentData,
  userAccountId,
}) => {
  // 消息列表
  const [messageList, setMessageList] = useState<ListType>();
  // 获取用户头像
  const getUserContentShow = () => {
    const { companyInfoVO, userAccountId, userImg, userName, nickName } = currentData;
    // 用户对商家聊天
    if (companyInfoVO?.id && companyInfoVO?.companyBindUserId === userAccountId) {
      return {
        icon: `${companyInfoVO?.brandLogo}?x-oss-process=image/quality,q_25`,
        name: companyInfoVO?.brandName || companyInfoVO?.companyName || '与商家的聊天',
      };
    }
    // 商家对用户聊天
    if (companyInfoVO?.id && companyInfoVO?.companyBindUserId !== userAccountId) {
      return {
        icon: `${userImg}?x-oss-process=image/quality,q_25`,
        name: nickName || userName || '与用户的聊天',
      };
    }
    // 用户对用户聊天
    return {
      icon: `${userImg}?x-oss-process=image/quality,q_25`,
      name: nickName || userName || '与用户的聊天',
    };
  };
  // 获取当前对话列表
  const getMessageList = async () => {
    const res = await SystemManageAPI.selectUserMessage({
      pageNo: 1,
      pageSize: 9999,
      receiverUserId: currentData?.userAccountId,
      backUserId: currentData?.companyInfoVO?.backUserId,
      sendUserId: userAccountId,
    });
    if (res && res.code === '200') {
      setMessageList(res.result?.list?.reverse() || []);
      // console.log('对话列表 --->', currentData);
    }
  };
  // 转换图片数据
  const getImgUrlList = (data: ListType[0]): string[] => {
    if (data?.imgUrl) {
      try {
        return JSON.parse(data?.imgUrl);
      } catch (e) {
        return ['https://file.iuav.com/file/error.png'];
      }
    } else {
      return [];
    }
  };
  // 组件挂载
  useEffect(() => {
    if (!currentData?.userAccountId) return;
    getMessageList().then();
    getMessageTimer = setInterval(() => {
      getMessageList().then();
    }, 5000);
    return () => {
      clearInterval(getMessageTimer as any);
    };
  }, [currentData]);
  // 消息列表副作用
  useEffect(() => {
    if (!messageList?.length) return;
    const contentScroll: any = document.querySelector('.content-scroll');
    const contentList: any = document.querySelector('.content-scroll .content-list');
    if (contentList?.offsetHeight > contentScroll?.offsetHeight) {
      setTimeout(() => {
        contentScroll.scrollTop = contentList.scrollHeight;
      }, 500);
    }
  }, [messageList]);
  return (
    <div className='message-chat-content-view'>
      <div className='content-head flex-start'>
        <img className='image' src={getUserContentShow()?.icon} alt={getUserContentShow()?.name} />
        <div className='title'>{getUserContentShow()?.name}</div>
      </div>
      <div className='content-scroll'>
        <div className='content-list'>
          {messageList?.map((i, j) => (
            <div className='list-item flex-center' key={j}>
              <div className='item-date'>{i?.createTime}</div>
              <div
                className={`item-content ${
                  i?.senderUserId !== userAccountId ? 'flex-start' : 'flex-end'
                }`}
              >
                <div className='detail'>
                  {i?.content && <div className='text'>{i?.content}</div>}
                  {getImgUrlList(i)?.length > 0 &&
                    getImgUrlList(i)?.map((n, m) => <Image key={m} src={n} width={200} />)}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
      <MessageChatActionView
        currentData={currentData}
        userAccountId={userAccountId}
        onRefresh={getMessageList}
      />
    </div>
  );
};

export default MessageChatContentView;
