import { GetRoomUser } from '@/api/Meeting';
import { role } from '@/config/role';
import styles from '@/page/Meeting/ShareScreenWindow/index.module.scss'
import { storage } from '@/utils';
import ImageUrl from '@/utils/package/imageUrl';
import { CaretDownOutlined, CaretUpOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from "react";
const { setInterval, clearInterval } = require('timers');
const ShareScreenWindow: React.FC = () => {
  const [footerLists, setFooterLists] = useState<any>([
    {
      title: '静音',
      icon: ImageUrl.icon22,
      iconActive: ImageUrl.icon22Active,
      active: false,
      select: false,
    },
    {
      title: '关闭视频',
      icon: ImageUrl.icon23,
      iconActive: ImageUrl.icon23Active,
      active: false,
      select: false,
    },
    {
      title: '成员',
      icon: ImageUrl.icon30,
      iconSelect: ImageUrl.icon30Select,
      active: false,
      select: false,
    },
    {
      title: '聊天',
      icon: ImageUrl.icon31,
      iconSelect: ImageUrl.icon31Select,
      active: false,
      select: false,
    },
    {
      title: '录制',
      icon: ImageUrl.icon27,
      iconSelect: ImageUrl.icon27Select,
      iconActive: ImageUrl.icon27Active,
      active: false,
      select: false,
    },
  ])
  const [timeStr, setTimeStr] = useState(0)
  const [isExpand, setIsExpand] = useState(false)
  const [roomUserLists, setRoomUserLists] = useState<any>([])
  const channel = new BroadcastChannel('meeting_channel');
  const userInfo = JSON.parse(storage.getItem('user') as string)
  let timeout: NodeJS.Timeout;
  useEffect(() => {
    getRoomUser()
    if (!role.ID.includes(userInfo.roleId)) {
      setFooterLists((res: any) => {
        return res.splice(4, 1)
      })
    }
    channel.onmessage = function (event) {
      let { type, time } = event.data;
      switch (type) {
        case 'time':
          setTimeStr(time)
          timeout = setInterval(() => {
            setTimeStr(time++)
          }, 1000)
          break;
      }
    }
    channel.postMessage({
      type: 'shareScreenWindowGetTime'
    });
    window.electron.windowHandleMessageCallBack((_e: any, data: any) => {
      switch (data.parmes.type) {
        case 'currentSpeakUserMe':
          let domMe = document.getElementById(`micr-item-${userInfo.uid}`) as HTMLDivElement;
          if (domMe) {
            domMe.style.height = `${data.parmes.currentSpeakUserMe}%`
          }
          break;
        case 'footerList':
          const footerListTemplate = [...footerLists];
          footerListTemplate[0].title = data.parmes.footerList[0][0].active ? '解除静音' : '静音';
          footerListTemplate[0].active = data.parmes.footerList[0][0].active;
          footerListTemplate[1].title = data.parmes.footerList[0][1].active ? '开启视频' : '关闭视频';
          footerListTemplate[1].active = data.parmes.footerList[0][1].active;
          if (role.ID.includes(userInfo.roleId)) {
            footerListTemplate[4].title = data.parmes.footerList[1][3].active ? '录制中' : '录制';
            footerListTemplate[4].active = data.parmes.footerList[1][3].active;
          }
          setFooterLists(footerListTemplate)
          break;
        case 'roomUserList':
          setRoomUserLists(data.parmes.roomUserList)
          break;
      }
    })
    return () => {
      clearInterval(timeout)
      channel.close();
    };
  }, []);
  const changeCurrentSeconds = (time: number): string => {
    const duration = dayjs.duration(time, 'seconds');
    const hours = duration.hours(); // 整数小时
    const minutes = duration.minutes(); // 整数分钟
    const secondsRemaining = duration.seconds(); // 剩余的秒数
    return `${hours > 9 ? hours : '0' + hours}:${minutes > 9 ? minutes : '0' + minutes}:${secondsRemaining > 9 ? secondsRemaining : '0' + secondsRemaining}`
  }
  // 获取房间用户
  const getRoomUser = async (): Promise<void> => {
    const data = JSON.parse(storage.getItem('stateInfo') as string)
    await GetRoomUser(data.channelId).then(res => {
      if (res.code === 200) {
        res.data.forEach((item: any) => {
          item.isShow = true;
          item.isRoom = true;
          item.isAdmin = role.ID.includes(item.roleId) || item.isRoomManager
        })
        setRoomUserLists(res.data)
        channel.postMessage({
          type: 'shareScreenWindowGetFooterLists',
        });
      }
    })
  }
  // 底部按钮点击效果
  const changeFooterListSelect = (item: any, index: number, bool: boolean): void => {
    let arr = ['静音', '解除静音', '关闭视频', '开启视频']
    if (arr.indexOf(item.title) === -1) {
      const footerListTemplate = [...footerLists]
      footerListTemplate[index].select = bool;
      setFooterLists(footerListTemplate)
    }
  }
  return (
    <>
      <div className={styles.shareScreenWindow} style={{ width: isExpand ? '100%' : '100%' }}>
        <div className={styles.shareScreenWindowTitle}>
          <span>{changeCurrentSeconds(timeStr)} 共享中</span>
          {isExpand ? <span className='drag' onClick={() => {
            channel.postMessage({
              type: 'shareScreenWindowClose',
              shareScreenWindowClose: timeStr
            });
          }}>结束共享</span> : <span style={{ visibility: 'hidden' }}>结束共享</span>}
        </div>
        {isExpand ? null : <div className={`${styles.shareScreenWindowContent} drag`}>
          <div className={styles.shareScreenWindowContentList}>
            {footerLists.map((item: any, index: number) => {
              return (
                <div
                  onMouseDown={() => changeFooterListSelect(item, index, true)}
                  onMouseUp={() => changeFooterListSelect(item, index, false)}
                  onMouseLeave={() => changeFooterListSelect(item, index, false)}
                  onClick={async () => {
                    switch (item.title) {
                      case '静音':
                      case '解除静音':
                      case '关闭视频':
                      case '开启视频':
                      case '录制':
                      case '录制中':
                        channel.postMessage({
                          type: 'shareScreenWindowfooterListsTitle',
                          shareScreenWindowfooterListsTitle: item.title
                        });
                        break;
                      case '聊天':
                        window.electron.setChildWindowShow({
                          key: 'chatBigWindow',
                        })
                        break;
                      case '成员':
                        window.electron.setChildWindowShow({
                          key: 'userListWindow',
                        })
                        break;
                    }
                  }}
                  key={index}>
                  <div>
                    {!item.active ? <div style={{ backgroundImage: `url(${ImageUrl.icon49})` }} id={`micr-item-${userInfo.uid}`}>
                    </div> : ''}
                    {item.select ? <img src={item.iconSelect} alt="" /> : <img src={item.active ? item.iconActive : item.icon} alt="" />}
                  </div>
                  <span>{item.title}{item.title === '成员' ? `(${roomUserLists.filter((item: any) => item.isRoom).length})` : ''}</span>
                </div>
              )
            })}
          </div>
          <Button type="primary" style={{ backgroundColor: '#FF5219', marginRight: '14px' }} size={'small'} onClick={() => {
            channel.postMessage({
              type: 'shareScreenWindowClose',
              shareScreenWindowClose: timeStr
            });
          }}>
            结束共享
          </Button>
        </div>}
        <div className={`${styles.shareScreenWindowExpand} drag`} onClick={() => {
          setIsExpand(!isExpand)
          window.electron.setChildWindow({
            width: isExpand ? 440 : 440 / 2,
            key: 'shareScreenWindow',
          })
        }}>
          <span>{isExpand ? '展开' : '收起'}</span>
          {isExpand ? <CaretDownOutlined /> : <CaretUpOutlined />}
        </div>
      </div >
    </>
  )
}

export default ShareScreenWindow
