import styles from '@/page/Meeting/ChatBigWindow/index.module.scss'
import ImageUrl from '@/utils/package/imageUrl';
import { useEffect, useState, useRef } from "react";
import { storage } from '@/utils';
import { setKeyOpenChildWindow } from '@/utils/package/public';
import { Button, Input, Modal, Popover } from 'antd';
import { role } from '@/config/role';
import { GetRoomUserItem } from '@/api/Meeting';
import Avatar from '@/components/Avatar';
import dayjs from 'dayjs';
import { ExclamationCircleFilled } from '@ant-design/icons';
import EquipmentManagement from '@/components/EquipmentManagement';
const { confirm } = Modal;
const ChatBigWindow: React.FC = () => {
  const [inputValue, setInputValue] = useState<string>('')
  const [chatLists, setChatLists] = useState<any>([])
  const [user, setUser] = useState<any>({});
  const [roomUserItem, setRoomUserItem] = useState<any>(null)
  const [commonlyChatList] = useState<any>([
    '能听到我说话吗？',
    '听得到',
    '听不到',
    '我要发言',
  ])
  const equipmentManagementRef = useRef<any>();
  const userInfo = JSON.parse(storage.getItem('user') as string)
  const stateInfo = JSON.parse(storage.getItem('stateInfo') as string)
  const channel = new BroadcastChannel('meeting_channel');
  useEffect(() => {
    setUser(userInfo)
    channel.onmessage = function (event) {
      const { type, chatList, showDriverList } = event.data;
      switch (type) {
        case 'chatList':
          setChatLists(chatList)
          setTimeout(() => {
            const chatBigWindowView = document.getElementById('chatBigWindowView') as HTMLElement;
            if (chatBigWindowView) {
              chatBigWindowView.scrollTop = chatBigWindowView.scrollHeight;
            }
          }, 100)
          break;
        case 'showDriverList':
          equipmentManagementRef.current.setData(showDriverList)
          break;
      }
    }
    channel.postMessage({
      type: 'chatBigWindowSendChannelMsg',
      chatBigWindowSendChannelMsg: {
        msg: '',
      }
    });
    return () => {
      channel.close();
    }
  }, []);

  return (
    <>
      <div className={`${styles.chatBigWindow}`}>
        <div className={styles.chatBigWindowTitle}>
          <span>聊天</span>
          <img src={ImageUrl.icon18} className='drag' alt="" onClick={() => {
            window.electron.closeChildWindow('chatBigWindow')
            setKeyOpenChildWindow('chatBigWindow', false)
          }} />
        </div>
        <div className={`${styles.chatBigWindowContent} drag`} id='chatBigWindowView'>
          {chatLists.map((item: any, index: number) =>
            <div
              key={index}
              className={`${item.uid !== user.uid ? styles.chatBigWindowContentLeft : styles.chatBigWindowContentRight}`}>
              {role.ID.includes(user.roleId) ? <Popover
                placement="bottom"
                title={''}
                onOpenChange={(e: boolean) => {
                  if (e) {
                    GetRoomUserItem(stateInfo.channelId, item.uid).then((res: any) => {
                      if (res.code === 200) {
                        setRoomUserItem(res.data)
                      }
                    })
                  } else {
                    setRoomUserItem(null)
                  }
                }}
                content={
                  roomUserItem ? <div className={styles.chatBigWindowInputPopover}>
                    {roomUserItem.isRoomManager || role.ID.includes(roomUserItem.roleId) ? <Button
                      type="primary"
                      className='m-ant-btn'
                      size={'small'}
                      onClick={(event) => {
                        event.stopPropagation();
                        channel.postMessage({
                          type: 'chatBigWindowSetAllUserLook',
                          chatBigWindowSetAllUserLook: {
                            roomUserItem,
                          }
                        });
                      }}
                    >全员看Ta</Button> : null}
                    {roomUserItem.uid !== user.uid && !role.ID.includes(roomUserItem.roleId) ? <Button
                      type="primary"
                      className='m-ant-btn'
                      size={'small'}
                      onClick={async (event) => {
                        event.stopPropagation();
                        if (roomUserItem.isRoomManager) {
                          channel.postMessage({
                            type: 'chatBigWindowDeleteRoomManager',
                            chatBigWindowDeleteRoomManager: {
                              uid: roomUserItem.uid
                            }
                          });
                        } else {
                          channel.postMessage({
                            type: 'chatBigWindowPostRoomManager',
                            chatBigWindowPostRoomManager: {
                              uid: roomUserItem.uid
                            }
                          });
                        }
                        await GetRoomUserItem(stateInfo.channelId, item.uid).then((res: any) => {
                          if (res.code === 200) {
                            setRoomUserItem(res.data)
                          }
                        })
                      }}
                    >{roomUserItem.isRoomManager ? '取消发言' : '允许发言'}</Button> : null}
                    {roomUserItem.isRoomManager ? <Button
                      type="primary"
                      className='m-ant-btn'
                      size={'small'}
                      onClick={async (event) => {
                        event.stopPropagation();
                        channel.postMessage({
                          type: 'chatBigWindowPostOpenMicr',
                          chatBigWindowPostOpenMicr: {
                            uid: roomUserItem.uid,
                            enableMicr: !roomUserItem.enableMicr
                          }
                        });
                        await GetRoomUserItem(stateInfo.channelId, item.uid).then((res: any) => {
                          if (res.code === 200) {
                            setRoomUserItem(res.data)
                          }
                        })
                      }}
                    >{roomUserItem.enableMicr ? '静音' : '解除静音'}</Button> : null}
                    {roomUserItem.isRoomManager ? <Button
                      type="primary"
                      className='m-ant-btn'
                      size={'small'}
                      onClick={async (event) => {
                        event.stopPropagation();
                        channel.postMessage({
                          type: 'chatBigWindowPostOpenCamera',
                          chatBigWindowPostOpenCamera: {
                            uid: roomUserItem.uid,
                            enableMicr: !roomUserItem.enableCamera
                          }
                        });
                        await GetRoomUserItem(stateInfo.channelId, item.uid).then((res: any) => {
                          if (res.code === 200) {
                            setRoomUserItem(res.data)
                          }
                        })
                      }}
                    >{roomUserItem.enableCamera ? '关闭视频' : '打开视频'}</Button> : null}
                    {roomUserItem.uid !== user.uid ? <Button
                      type="primary"
                      className='m-ant-btn'
                      size={'small'}
                      onClick={() => {
                        equipmentManagementRef.current.changeModal(item.uid, item.userName)
                      }}
                    >设备管理</Button> : null}
                    {roomUserItem.uid !== user.uid ? <Button
                      type="primary"
                      style={{ backgroundColor: '#EC3C3C' }}
                      size={'small'}
                      onClick={(event) => {
                        event.stopPropagation();
                        confirm({
                          title: '移出会议',
                          icon: <ExclamationCircleFilled />,
                          content: `确定将用户${item.userName}移出会议？`,
                          centered: true,
                          okText: '确定',
                          cancelText: '取消',
                          async onOk() {
                            channel.postMessage({
                              type: 'chatBigWindowGetRoomKickout',
                              chatBigWindowGetRoomKickout: {
                                uid: item.uid
                              }
                            });
                          },
                          onCancel() {

                          },
                        });
                      }}
                    >移出会议</Button> : null}
                  </div> : <div style={{ color: 'white' }}>用户不在房间内</div>
                }>
                <div>
                  <div><Avatar name={item.userName} /></div>
                  {item.uid !== user.uid ?
                    <span>{item.userName} <span style={{ fontSize: '12px', color: '#ccc', marginLeft: '4px' }}>{dayjs(item.timestamp).format('HH:mm:ss')}</span></span> :
                    <span> <span style={{ fontSize: '12px', color: '#ccc', marginRight: '4px' }}>{dayjs(item.timestamp).format('HH:mm:ss')} </span>{item.userName}</span>
                  }

                </div>
              </Popover> : <div>
                <div><Avatar name={item.userName} /></div>
                {item.uid !== user.uid ?
                  <span>{item.userName}<span style={{ fontSize: '12px', color: '#ccc', marginLeft: '4px' }}>{dayjs(item.timestamp).format('HH:mm:ss')}</span></span> :
                  <span><span style={{ fontSize: '12px', color: '#ccc', marginRight: '4px' }}>{dayjs(item.timestamp).format('HH:mm:ss')} </span>{item.userName}</span>
                }
              </div>}
              <div>{item.message}</div>
            </div>
          )}
        </div>
        <div className={`${styles.chatBigWindowButton} drag`}>
          {
            commonlyChatList.map((item: string, index: number) => {
              return <Button
                key={index}
                type="primary"
                className='m-ant-btn'
                onClick={() => {
                  channel.postMessage({
                    type: 'chatBigWindowSendChannelMsg',
                    chatBigWindowSendChannelMsg: {
                      msg: item,
                    }
                  });
                }}
              >{item}</Button>
            })
          }
        </div>
        <div className={`${styles.chatBigWindowInput} drag`}>
          <Input.TextArea
            placeholder="请输入内容"
            style={{ flexGrow: 1 }}
            value={inputValue}
            onChange={(e) => {
              setInputValue(e.target.value)
            }}
            autoSize={{ minRows: 3, maxRows: 3 }} />
          <Button type="primary" className='m-ant-btn' style={{ flexShrink: 0, marginTop: '4px' }} onClick={() => {
            channel.postMessage({
              type: 'chatBigWindowSendChannelMsg',
              chatBigWindowSendChannelMsg: {
                msg: inputValue,
              }
            });
            setInputValue('')
          }}>发送</Button>
        </div>
      </div>
      <EquipmentManagement ref={equipmentManagementRef} getDriver={(uid: string) => {
        channel.postMessage({
          type: 'userListWindowEquipmentManagement',
          userListWindowEquipmentManagement: {
            uid
          }
        });
      }} setDriver={(data: any) => {
        channel.postMessage({
          type: 'userListWindowSetEquipmentManagement',
          userListWindowSetEquipmentManagement: data
        });
      }} />
    </>
  )
}

export default ChatBigWindow
