import styles from '@/page/Meeting/ChatSmallWindow/index.module.scss'
import { Input } from 'antd';
import { useEffect, useState } from "react";
import { storage } from '@/utils';
const ChatSmallWindow: React.FC = () => {
  const [inputValue, setInputValue] = useState<string>('')
  const [chatLists, setChatLists] = useState<any>([])
  const userInfo = JSON.parse(storage.getItem('user') as string)
  const channel = new BroadcastChannel('meeting_channel');
  useEffect(() => {
    channel.onmessage = function (event) {
      const { type, chatList } = event.data;
      switch (type) {
        case 'chatList':
          setChatLists(chatList.reverse())
          setTimeout(() => {
            const chatSmallWindowView = document.getElementById('chatSmallWindowView') as HTMLElement;
            if (chatSmallWindowView) {
              chatSmallWindowView.scrollTop = chatSmallWindowView.scrollHeight;
            }
          }, 100)
          break;
      }
    }
  }, []);


  return (
    <>
      <div className={styles.chatSmallWindow}>
        <div id='chatSmallWindowView'>
          {chatLists.map((item: any) =>
            <div className={`${item.uid !== userInfo.uid ? styles.chatSmallWindowContentLeft : styles.chatSmallWindowContentRight}`}>
              <div>
                <span>{item.userName}</span>
                <span>：</span>
                <span>{item.message}</span>
              </div>
            </div>
          )}
        </div>
        <div className='drag'>
          <Input
            placeholder="请输入内容"
            style={{ flexGrow: 1 }}
            value={inputValue}
            onChange={(e) => {
              setInputValue(e.target.value)
            }}
            onPressEnter={() => {
              if (inputValue) {
                channel.postMessage({
                  type: 'chatSmallWindowSendChannelMsg',
                  chatSmallWindowSendChannelMsg: {
                    msg: inputValue,
                  }
                });
                setInputValue('')
              }
            }}
            suffix={
              <span
                style={{ color: '#47D3D0', cursor: 'pointer' }}
                onClick={() => {
                  if (inputValue) {
                    channel.postMessage({
                      type: 'chatSmallWindowSendChannelMsg',
                      chatSmallWindowSendChannelMsg: {
                        msg: inputValue,
                      }
                    });
                    setInputValue('')
                  }
                }}
              >发送
              </span>
            }
          />
        </div>
      </div >
    </>
  )
}

export default ChatSmallWindow
