import styles from '@/components/InvitingPersonnelModal/index.module.scss'
import { Button, Checkbox, Input, Modal, Pagination, Radio, message } from 'antd';
import { useState, useImperativeHandle, forwardRef, useEffect } from "react";
import { SearchOutlined } from '@ant-design/icons';
import { GetUserList } from '@/api/Home/User';
import { useLocation } from 'react-router-dom';
import { GetRoomUser, PostRoomInvite } from '@/api/Meeting';
import { storage } from '@/utils';
import Avatar from '@/components/Avatar';
const InvitingPersonnelModal = forwardRef((props: any, ref: any) => {
  useImperativeHandle(ref, () => ({
    changeInvitingPersonnelModal: () => {
      let userInfo = JSON.parse(storage.getItem('user') as string)
      setUser(userInfo)
      setCheckedList([])
      getUserList()
      setIsInvitingPersonnelModal(true)
    }
  }))
  const { state } = useLocation();
  const [isInvitingPersonnelModal, setIsInvitingPersonnelModal] = useState(false);
  const [isFirstRender, setIsFirstRender] = useState(true);
  const [user, setUser] = useState<any>('');
  const [optionsValue, setOperationValue] = useState<number>(1);
  const [list, setList] = useState<any>({
    data: [],
    searchKeywod: '',
    total: 0,
    pageIndex: 1,
    pageSize: 5,
    roomList: []
  })
  const [checkedList, setCheckedList] = useState<any>([])

  useEffect(() => {
    if (isFirstRender) {
      setIsFirstRender(false);
    } else {
      getUserList()
    }
  }, [list.pageIndex]);

  useEffect(() => {
    if (isFirstRender) {
      setIsFirstRender(false);
    } else {
      if (list.pageIndex === 1) {
        getUserList()
      } else {
        setList({
          ...list,
          pageIndex: 1
        })
      }
    }
  }, [optionsValue]);

  useEffect(() => {
    setList((res: any) => {
      res.data.forEach((item: any) => {
        item.checked = checkedList.find((checkedItem: any) => checkedItem.id === item.id) ? true : false;
        item.disabled = res.roomList.find((row: any) => row.account === item.account) ? true : false;
      });
      return {
        ...res,
        data: res.data,
      }
    })
  }, [list.data]);
  // 获取用户列表
  const getUserList = async (): Promise<void> => {
    Promise.all([
      GetRoomUser(state.channelId),
      GetUserList({
        pageIndex: list.pageIndex,
        pageSize: list.pageSize,
        searchKeywod: list.searchKeywod,
        isOnline: optionsValue === 1 ? true : false,
      })
    ]).then(res => {
      if (res[0].code === 200 && res[1].code === 200) {
        setList({
          ...list,
          total: res[1].data.total,
          data: res[1].data.items,
          roomList: res[0].data
        })
      }
    })
  }
  return (
    <>
      <Modal
        title="邀请成员"
        open={isInvitingPersonnelModal}
        footer={null}
        onCancel={() => setIsInvitingPersonnelModal(false)}
        centered
        destroyOnClose={true}
        width={'700px'}
      >
        <div className={styles.invitingPersonnelModal}>
          <div className={styles.invitingPersonnelModalContent}>
            <div className={styles.invitingPersonnelModalContentLeft}>
              <Input
                placeholder="请输入成员名称"
                style={{ width: '100%', flexShrink: 0 }}
                prefix={<SearchOutlined style={{ color: 'white' }} />}
                value={list.searchKeywod}
                onChange={(e) => {
                  setList({
                    ...list,
                    searchKeywod: e.target.value,
                  })
                }}
                onPressEnter={() => {
                  if (list.pageIndex === 1) {
                    getUserList()
                  } else {
                    setList({
                      ...list,
                      pageIndex: 1
                    })
                  }
                }}
              />
              <Radio.Group onChange={(e: any) => {
                setOperationValue(e.target.value)
              }} style={{ flexShrink: 0, margin: '10px 0' }} value={optionsValue}>
                <Radio value={1}>在线</Radio>
                <Radio value={2}>离线</Radio>
              </Radio.Group>
              <div className={styles.invitingPersonnelModalContentLeftUserList}>
                {list.data.length ? list.data.map((item: any, index: number) => <div key={item.id}>
                  <div >
                    <Checkbox onChange={(e) => {
                      const newData = [...list.data] as any;
                      newData[index].checked = e.target.checked
                      setList({
                        ...list,
                        data: newData,
                      })
                      setCheckedList((checkedList: any) => {
                        if (newData[index].checked) {
                          return [...checkedList, newData[index]]
                        } else {
                          checkedList.splice(checkedList.findIndex((item: any) => item.id === newData[index].id), 1);
                          return checkedList
                        }
                      })
                    }} disabled={!item.isOnline || item.account === user.account || item.disabled} checked={item.checked}></Checkbox>
                    <div><Avatar name={item.userName} /></div>
                    <span>{item.userName}{item.account === user.account ? '(我)' : ''}{item.disabled ? '(已入会)' : ''}</span>
                  </div>
                  <div style={{ color: item.isOnline ? '#02B188' : 'rgb(221 11 11)' }}>{item.isOnline ? '在线' : '离线'}</div>
                </div>) : <span style={{ display: 'block', textAlign: 'center', color: 'white', padding: '30px 0' }}>暂无数据</span>}
              </div>
              <Pagination size="small" total={list.total} style={{ flexShrink: 0, margin: '10px 0 0' }} onChange={(e) => {
                setList({
                  ...list,
                  pageIndex: e
                })
              }} pageSize={list.pageSize} current={list.pageIndex} hideOnSinglePage={true} showLessItems={true} />
            </div>
            <div className={styles.invitingPersonnelModalContentRight}>
              <span>已选成员</span>
              <div>
                {checkedList.map((item: any, index: number) => <div key={item.id + index}>
                  <div><Avatar name={item.userName} /></div>
                  <span>{item.userName}</span>
                </div>)}
              </div>
            </div>
          </div>
          <div className={styles.invitingPersonnelModalFooter}>
            <Button type="primary" onClick={() => { setIsInvitingPersonnelModal(false) }} style={{ backgroundColor: '#31353A', marginRight: '14px' }}>取消</Button>
            <Button type="primary" className='m-ant-btn' onClick={() => {
              if (checkedList.length) {
                PostRoomInvite(state.roomId, checkedList.map((item: any) => item.id)).then(res => {
                  if (res.code === 200) {
                    message.success('邀请成功')
                    setIsInvitingPersonnelModal(false)
                  }
                })
              } else {
                message.error('请选择人员')
              }
            }}>呼叫</Button>
          </div>
        </div>
      </Modal>
    </>
  )
})


export default InvitingPersonnelModal