
import styles from '@/components/UserVideo/index.module.scss'
import { GetPolling } from '@/api/Meeting';
import { agora } from '@/utils/package/agora';
import { Button, Empty, Select, message } from 'antd';
import { useEffect, useState } from "react";
import { useLocation } from 'react-router';
import { VideoStreamType } from 'agora-electron-sdk';
const { setInterval, clearInterval } = require('timers');
const UserVideo: React.FC = () => {
  const { state } = useLocation();
  const [from, setFrom] = useState<any>({
    cycleIntervalList: [
      { value: 30, label: '30秒' },
      { value: 60, label: '1分钟' },
      { value: 120, label: '2分钟' },
      { value: 180, label: '3分钟' },
    ],
    cycleIntervalValue: 30,
    viewPeople: [
      { value: 6, label: '6人' },
      { value: 12, label: '12人' },
      // { value: 20, label: '20人' },
    ],
    viewPeopleValue: 6,
  })
  const [timeNumber, setTimeNumber] = useState(30);
  const [timeStatus, setTimeStatus] = useState(false);
  const [userList, setUserList] = useState([]);
  useEffect(() => {
    window.addEventListener('customStorageChange', handleCustomStorageChange);
    return () => {
      window.removeEventListener('customStorageChange', handleCustomStorageChange);
    }
  }, []);
  useEffect(() => {
    let time = null as any;
    if (timeStatus) {
      time = setInterval(() => {
        setTimeNumber((timeNumber: number) => {
          if (timeNumber === 1) {
            getPolling()
            message.success('刷新成功！')
            return from.cycleIntervalValue
          } else {
            return timeNumber - 1
          }
        })
      }, 1000)
    } else {
      clearInterval(time)
    }
    return () => {
      clearInterval(time)
    }
  }, [timeStatus])

  useEffect(() => {
    getPolling()
  }, [from.viewPeopleValue])

  useEffect(() => {
    userList.forEach(async (item: any) => {
      await agora.destroyRendererByConfig(Number('1' + item.screenShareId), state.channelId + 'a')
      await agora.setupRemoteVideoEx({
        uid: Number('1' + item.screenShareId),
        view: document.getElementById(`video-${item.screenShareId}`),
        channelId: state.channelId + 'a',
      })
      await agora.setRemoteVideoStreamType(Number('1' + item.screenShareId), VideoStreamType.VideoStreamLow, false)
    })
  }, [userList])
  // 监听缓存变化
  const handleCustomStorageChange = async (e: any): Promise<void> => {
    switch (e.key) {

    }
  };
  // 获取轮训用户
  const getPolling = async (): Promise<void> => {
    setUserList([])
    setFrom((res: any) => {
      GetPolling(state.channelId?.split('a')[0] as string, res.viewPeopleValue).then((res: any) => {
        if (res.code === 200) {
          setUserList(res.data)
        }
      })
      return res
    })
  };
  return (
    <>
      <div className={styles.userVideo}>
        <div className={`${styles.userVideoContent}`}>
          <div className={styles.userVideoContentHeader}>
            <div>
              <div>
                <span>循环间隔</span>
                <Select
                  placeholder='请选择循环间隔'
                  options={from.cycleIntervalList}
                  size={'small'}
                  value={from.cycleIntervalValue} onChange={(e) => {
                    setFrom({ ...from, cycleIntervalValue: e })
                    setTimeNumber(e)
                  }} />
              </div>
              <div>
                <span>查看人数</span>
                <Select
                  placeholder='请选择查看人数'
                  options={from.viewPeople}
                  size={'small'}
                  value={from.viewPeopleValue} onChange={(e) => {
                    setFrom({ ...from, viewPeopleValue: e })
                  }} />
              </div>
            </div>
            <div>
              <span>{timeNumber}秒后刷新</span>
              {timeStatus ? <Button
                type="primary"
                size={'small'}
                onClick={() => {
                  setTimeStatus(!timeStatus)
                }}
                style={{ backgroundColor: '#EC3C3C' }}
              >暂停循环</Button> :
                <Button
                  type="primary"
                  className='m-ant-btn'
                  size={'small'}
                  onClick={() => {
                    setTimeStatus(!timeStatus)
                  }}
                >开始循环</Button>}
            </div>
          </div>
          {userList.length ? <div className={styles.userVideoContentList}>
            {
              userList.map((item: any, index: number) => {
                return <div className={styles.userVideoContentListItem} key={index}>
                  <div className={styles.userVideoContentListItemVideo} id={`video-${item.screenShareId}`}>
                    <div>{item.userName}{item.isRoomManager ? '(发言中)' : ''}</div>
                  </div>
                </div>
              })
            }
          </div> :
            <Empty style={{ margin: 'auto' }} />}
        </div>
      </div>
    </>
  )
}

export default UserVideo
