import styles from '@/components/JoinSetting/index.module.scss'
import { storage } from '@/utils';
import ImageUrl from '@/utils/package/imageUrl';
import { GetCheckoutRoomNum, GetRoomRtcToken, GetRoomInfo } from '@/api/Home/Index';
import { Button, Modal, message } from 'antd';
import { useState, useImperativeHandle, forwardRef } from "react";
import { PostRefresh } from '@/api/Login';
import Avatar from '@/components/Avatar';
import { useNavigate } from 'react-router-dom';
import { agora } from '@/utils/package/agora';
import { role } from '@/config/role';
const { setInterval, clearInterval } = require('timers');
let time = null as any;
const JoinSetting = forwardRef((_props: any, ref: any) => {
  useImperativeHandle(ref, () => ({
    changeModal: async (roomNum: string = '') => {
      let userInfo = JSON.parse(storage.getItem('user') as string)
      setUser(userInfo)
      setJoinRoomSettingModal(true)
      if (location.hash.indexOf('/meeting') === -1) {
        await agora.init()
      }
      setJoinRoomSettingForm((res: any) => {
        res.forEach(async (item: any, index: number) => {
          if (index === 0 && role.ID.includes(userInfo.roleId)) {
            await agora.getAudioMediaList().then(res => {
              item.active = res.ecordingList.length ? true : false
            })
          } else {
            item.active = false
          }
        });
        return res
      })
      setRoomNumber(roomNum)
      getDeviceList()
    }
  }))
  const navigate = useNavigate();
  const [user, setUser] = useState<any>({});
  const [roomNumber, setRoomNumber] = useState('')
  const [joinRoomSettingModal, setJoinRoomSettingModal] = useState(false)
  const [joinRoomSettingForm, setJoinRoomSettingForm] = useState(
    [{
      title: '静音',
      icon: ImageUrl.icon22,
      iconActive: ImageUrl.icon22Active,
      active: false,
    },
    {
      title: '关闭视频',
      icon: ImageUrl.icon23,
      iconActive: ImageUrl.icon23Active,
      active: false,
    },]
  )
  const getDeviceList = (): void => {
    time = setInterval(async () => {
      const list = [...joinRoomSettingForm]
      await agora.getAudioMediaList().then(res => {
        if (!res.ecordingList.length) {
          list[0].active = false
          setJoinRoomSettingForm(list)
        }
      })
      await agora.getVideoDeviceManager().then(res => {
        if (!res.list.length) {
          list[1].active = false
          setJoinRoomSettingForm(list)
        }
      })
    }, 1000)
  }
  const isGetCheckoutRoomNum = async (roomNum: string, callBack: Function): Promise<void> => {
    await GetCheckoutRoomNum(roomNum).then(res => {
      if (res.code === 200) {
        callBack(res.data)
      } else {
        storage.setItem('loading', false)
      }
    }).catch(() => {
      storage.setItem('loading', false)
    })
  }
  const getRoomRtcToken = async (roomNum: string, callBack: Function): Promise<void> => {
    Promise.all([GetRoomRtcToken(roomNum), GetRoomRtcToken(roomNum + 'a')]).then(res => {
      if (res[0].code === 200 && res[1].code === 200) {
        callBack({
          token: res[0].data,
          tokenA: res[1].data,
        })
      } else {
        storage.setItem('loading', false)
      }
    }).catch(() => {
      storage.setItem('loading', false)
    })
  }
  const postRefresh = async (callBack: Function): Promise<void> => {
    await PostRefresh(user.refresh_token).then(res => {
      if (res.code === 200) {
        storage.setItem('user', JSON.stringify(res.data))
        storage.setItem('userLogin', true)
        callBack(res.data)
      } else {
        storage.setItem('loading', false)
      }
    }).catch(() => {
      storage.setItem('loading', false)
    })
  }
  return (
    <>
      <Modal title="
      " open={joinRoomSettingModal}
        footer={null}
        centered
        width={'500px'}
        onCancel={() => {
          clearInterval(time)
          agora.release()
          setJoinRoomSettingModal(false)
        }}>
        <div className={styles.joinRoomSettingModal}>
          <div>
            <span>请输入会议号</span>
            <input
              type="text"
              value={roomNumber}
              maxLength={8}
              onChange={(e) => {
                const regex = /^[0-9]*$/;
                if (regex.test(e.target.value)) {
                  setRoomNumber(e.target.value);
                }
              }}
            />
          </div>
          <div>
            <Avatar name={user.userName} />
            {joinRoomSettingForm[1].active ? <div id='videoPreview'>

            </div> : null}
          </div>
          <div>
            <div>
              {
                joinRoomSettingForm.map((item, index) => {
                  return <div key={index} onClick={async () => {
                    if (role.ID.includes(user.roleId)) {
                      let msg = '';
                      if (index === 0) {
                        await agora.getAudioMediaList().then(res => {
                          if (!res.ecordingList.length) {
                            msg = '未检测到麦克风!'
                          }
                        })
                      } else {
                        await agora.getVideoDeviceManager().then(res => {
                          if (!res.list.length) {
                            msg = '未检测到摄像头!'
                          }
                        })
                      }
                      if (msg) {
                        message.error(msg)
                        return
                      }
                      const list = [...joinRoomSettingForm]
                      list[index].active = !list[index].active
                      setJoinRoomSettingForm(list)
                      if (index === 1) {
                        if (list[index].active) {
                          agora.startPreview('videoPreview', Number(user.screenShareId))
                        }
                      }
                    } else {
                      message.error('您不是管理员，无法开启此功能！')
                    }
                  }}>
                    <img src={item.active ? item.icon : item.iconActive} alt="" />
                  </div>

                })
              }
            </div>
            <div>
              <Button type="primary"
                onClick={() => {
                  if (!roomNumber) {
                    message.error('请输入会议号！')
                    return
                  }
                  storage.setItem('loading', true)
                  isGetCheckoutRoomNum(roomNumber, (bool: boolean) => {
                    if (bool) {
                      getRoomRtcToken(roomNumber, (options: any) => {
                        if (options) {
                          postRefresh(() => {
                            clearInterval(time)
                            setJoinRoomSettingModal(false)
                            GetRoomInfo(roomNumber).then(async (res) => {
                              if (res.code === 200) {
                                await agora.release()
                                navigate(`/meeting`, {
                                  state: {
                                    channelId: roomNumber,
                                    token: options.token,
                                    tokenA: options.tokenA,
                                    roomId: res.data.id,
                                    roomName: res.data.roomName,
                                    enableMicr: joinRoomSettingForm[0].active,
                                    enableCamera: joinRoomSettingForm[1].active,
                                  }
                                })
                              }
                            }).finally(() => {
                              storage.setItem('loading', false)
                            })
                          })
                        }
                      })
                    } else {
                      message.error('房间号不存在！')
                    }
                  })
                }}
                className='m-ant-btn'>
                进入会议
              </Button>
            </div>
          </div>
        </div>
      </Modal >
    </>
  )
})

export default JoinSetting