import styles from '@/page/Home/Index/index.module.scss'
import { useEffect, useState, useRef } from "react";
import Operation from '@/components/Operation';
import { Button, Input, Modal, Pagination, Empty, message } from "antd";
import { GetRoom, PostRomm, GetCheckoutRoomNum } from '@/api/Home/Index';
import ImageUrl from '@/utils/package/ImageUrl'
import { ReloadOutlined } from '@ant-design/icons';
import JoinSetting from '@/components/JoinSetting';
const Index: React.FC = () => {
  const [list, setList] = useState({
    data: [],
    total: 0,
    pageIndex: 1,
    pageSize: 12,
  })
  const [createRoomModal, setCreateRoomModal] = useState(false)
  const [createRoomFrom, setCreateRoomFrom] = useState<{ roomName: string, roomNum: string }>({
    roomName: "",
    roomNum: ""
  })
  const joinSettingRef = useRef<any>();
  useEffect(() => {
    let time = null as any
    if (time) {
      clearInterval(time)
    } else {
      time = setInterval(() => {
        getRoomList()
      }, 1000 * 30)
    }
    getRoomList()
    return () => {
      clearInterval(time)
    }
  }, [list.pageIndex]);
  const getRoomList = async (): Promise<void> => {
    await GetRoom({
      pageIndex: list.pageIndex,
      pageSize: list.pageSize,
    }).then(res => {
      if (res.code === 200) {
        setList({
          ...list,
          total: res.data.total,
          data: res.data.items,
        })
      }
    })
  }

  const copyRoomNum = (roomNum: string): void => {
    window.electron.setWriteText(roomNum)
    message.success('复制成功')
  }

  const isGetCheckoutRoomNum = async (roomNum: string, callBack: Function): Promise<void> => {
    await GetCheckoutRoomNum(roomNum).then(res => {
      if (res.code === 200) {
        callBack(res.data)
      }
    })
  }

  return (
    <>
      <div className={styles.index}>
        <div className={styles.indexOperation}>
          <Operation></Operation>
        </div>
        <div className={styles.indexBtns}>
          <Button type="primary"
            icon={<img src={ImageUrl.icon8} alt="" />}
            className='m-ant-btn drag'
            onClick={() => {
              setCreateRoomFrom({
                roomName: "",
                roomNum: ""
              })
              setCreateRoomModal(true)
            }}
          >
            新建会议室
          </Button>
          <Button type="primary" onClick={() => {
            joinSettingRef.current.changeModal()
          }}
            icon={<img src={ImageUrl.icon8} alt="" />}
            className={`${styles.indexBtnsJoin} drag`}>
            加入会议
          </Button>
        </div>
        <div className={styles.indexContent}>
          <div className={`drag ${styles.indexContentTitle}`}>
            <span>会议室列表</span>
            <ReloadOutlined
              title='刷新'
              style={{
                cursor: 'pointer',
              }}
              onClick={() => {
                message.success('刷新成功')
                getRoomList()
              }}
            />
          </div>
          {list.data.length ? <div className={`drag ${styles.indexContentList}`}>
            {list.data.map((item: any, index: number) => {
              return (
                <div className={`${styles.indexContentListItem}`} key={index}>
                  <div>
                    <div>{item.roomName}</div>
                    <div>
                      <img src={ImageUrl.icon11} alt="" />
                      <span>{item.onlineUserCount}人</span>
                    </div>
                  </div>
                  <div>
                    <div onClick={() => copyRoomNum(item.roomNum)} title='复制房间号'>
                      <span>{item.roomNum}</span>
                      <img src={ImageUrl.icon10} alt="" />
                    </div>
                    <div>

                      {/* <Button type="primary" danger>设置</Button> */}
                      <Button type="primary"
                        iconPosition={'end'}
                        onClick={() => {
                          // window.electron.oepnWindow({
                          //   url: location.origin + '/#/userVideo'
                          // })
                          joinSettingRef.current.changeModal(item.roomNum)
                        }}
                        icon={<img src={ImageUrl.icon9} alt="" />}
                        className='m-ant-btn'>
                        进入
                      </Button>
                    </div>
                  </div>
                </div>
              )
            })}
            <div style={{ display: 'none' }} className={`${styles.indexContentListItem} drag`}></div>
            <div style={{ display: 'none' }} className={`${styles.indexContentListItem} drag`}></div>
          </div> :
            <div className={styles.indexContentEmpty}>
              <Empty />
            </div>
          }
          <div className={styles.indexContentPagination}>
            <Pagination size="small" total={list.total} onChange={(e) => {
              setList({
                ...list,
                pageIndex: e
              })
            }} pageSize={list.pageSize} />
          </div>
        </div>
      </div>
      <Modal title="新建会议室" open={createRoomModal} footer={null} closable={false} centered width={'400px'}>
        <div>
          <div>
            <Input
              placeholder="请输入房间号"
              style={{ marginBottom: '14px' }}
              className={styles.letterSpacing}
              showCount
              maxLength={8}
              value={createRoomFrom.roomNum}
              onChange={(e) => {
                const regex = /^[0-9]*$/;
                if (regex.test(e.target.value)) {
                  setCreateRoomFrom({
                    ...createRoomFrom,
                    roomNum: e.target.value
                  })
                }
              }}
              suffix={
                <span
                  style={{ color: '#47D3D0', cursor: 'pointer' }}
                  onClick={() => {
                    function generateTimestampWithRandom(): string {
                      const timestamp = new Date().getTime();
                      const lastSixDigits = timestamp.toString().slice(-6);
                      const randomTwoDigits = ('0' + Math.floor(Math.random() * 100)).slice(-2);
                      return lastSixDigits + randomTwoDigits;
                    }
                    setCreateRoomFrom({
                      ...createRoomFrom,
                      roomNum: generateTimestampWithRandom(),
                    })
                  }}
                >获取随机房间号
                </span>
              }
            />
            <Input.TextArea
              placeholder="请输入房间名字"
              style={{ marginBottom: '14px' }}
              showCount
              maxLength={30}
              value={createRoomFrom.roomName}
              onChange={(e) => {
                setCreateRoomFrom({
                  ...createRoomFrom,
                  roomName: e.target.value
                })
              }}
              autoSize />
          </div>
          <div style={{
            display: 'flex', justifyContent: 'center'
          }}>
            <Button type="primary" style={{ backgroundColor: '#31353A', marginRight: '14px' }} onClick={() => setCreateRoomModal(false)}>取消</Button>
            <Button type="primary" className='m-ant-btn' onClick={() => {
              if (!createRoomFrom.roomName) {
                return message.error('请输入房间名字！')
              }
              if (!createRoomFrom.roomNum) {
                return message.error('请输入房间号！')
              }
              isGetCheckoutRoomNum(createRoomFrom.roomNum, (bool: boolean) => {
                if (bool) {
                  message.error('房间号已存在！')
                } else {
                  PostRomm(createRoomFrom).then(res => {
                    if (res.code === 200) {
                      message.success('创建成功！')
                      setCreateRoomModal(false)
                      getRoomList()
                    }
                  })
                }
              })
            }}>创建</Button>
          </div>
        </div>
      </Modal>
      <JoinSetting ref={joinSettingRef} />
    </>
  )
}

export default Index
