
import styles from '@/page/Login/index.module.scss'
import { useEffect, useState } from "react";
import { useNavigate } from 'react-router-dom';
import { Input, Button, Checkbox, message, Modal } from "antd"
import { storage } from '@/utils'
import { GetCheckUser, PostAnonLogin, PostLogin } from '@/api/Login'
import * as CryptoJS from 'crypto-js';
import ImageUrl from '@/utils/package/imageUrl'
import { v4 as uuidv4 } from 'uuid';
import { GetCheckoutRoomNum, GetRoomInfo, GetRoomRtcToken } from '@/api/Home/Index';
const Login: React.FC = () => {
  const navigate = useNavigate();
  const [accountPasswordStatus, setAccountPasswordStatus] = useState<boolean>(false);
  const [version, setVersion] = useState<string>('')
  const [operation, setOperation] = useState<{
    isRememberPassword: boolean;
    isAutoLogin: boolean;
    account: string;
    password: string;
    options: { label: string; value: string }[];
    optionsValue: string[];
  }>({
    isRememberPassword: false,
    isAutoLogin: false,
    account: '',
    password: '',
    options: [
      { label: '记住密码', value: 'isRememberPassword' },
      { label: '自动登录', value: 'isAutoLogin' },
    ],
    optionsValue: []
  });
  const [anonInfo, setAnonInfo] = useState({
    deviceId: '',
    nickName: '',
    roomNum: '',
  })
  const [nameModal, setNameModal] = useState(false)

  useEffect(() => {
    window.electron.setMainWindowSize({
      width: 752,
      height: 520,
      key: 'login'
    })
    if (storage.getItem('login')) {
      const login = JSON.parse(storage.getItem('login') as string);
      const data = {
        isRememberPassword: login.isRememberPassword,
        isAutoLogin: login.isAutoLogin,
        optionsValue: login.optionsValue,
      }
      if (login.isRememberPassword) {
        setOperation({
          ...operation,
          ...data,
          account: login.account,
          password: login.password,
        })
      } else {
        setOperation({
          ...operation,
          ...data,
        })
      }
    }
    window.electron.getVersion().then(res => {
      setVersion(res)
    })
  }, []);

  // 退出
  const quitClick = (): void => {
    window.electron.setViewStatus('quit')
  }

  // 重置
  const resetClick = (): void => {
    setOperation({
      ...operation,
      account: '',
      password: '',
    })
    setAccountPasswordStatus(false)
  }
  // 继续
  const continueClick = (): any => {
    if (!operation.account) {
      return message.error('请输入账号！')
    }
    if (storage.getItem('login')) {
      const login = JSON.parse(storage.getItem('login') as string);
      if (login.account !== operation.account) {
        setOperation({
          ...operation,
          password: '',
        })
      }
    }
    GetCheckUser(operation.account).then(res => {
      if (res.code === 200) {
        res.data ? setAccountPasswordStatus(true) : message.error('账号不存在!')
      }
    })
  }

  // 设置勾选
  const changeOptionsValue = (checkedValues: string[]): void => {
    if (checkedValues.indexOf('isAutoLogin') >= 0 && checkedValues.indexOf('isRememberPassword') === -1) {
      checkedValues.push('isRememberPassword')
    }
    setOperation({
      ...operation,
      optionsValue: checkedValues,
    })
    storage.setItem('login', JSON.stringify({
      isRememberPassword: checkedValues.includes('isRememberPassword'),
      isAutoLogin: checkedValues.includes('isAutoLogin'),
      account: operation.account,
      password: operation.password,
      optionsValue: checkedValues,
    }))
  };
  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 loginClick = (): void => {
    if (operation.password === '') {
      message.error('请输入密码');
      return;
    }
    PostLogin({
      account: operation.account,
      pwd: CryptoJS.MD5(operation.password).toString(CryptoJS.enc.Hex)
    }).then(res => {
      if (res.code === 200) {
        message.success('登录成功!')
        storage.setItem('login', JSON.stringify({
          isRememberPassword: operation.optionsValue.includes('isRememberPassword'),
          isAutoLogin: operation.optionsValue.includes('isAutoLogin'),
          account: operation.account,
          password: operation.password,
          optionsValue: operation.optionsValue,
        }))
        storage.setItem('user', JSON.stringify(res.data))
        storage.setItem('userLogin', true)
        window.electron.getWindowSize().then((res: any) => {
          window.electron.setMainWindowSize({
            width: Math.ceil(res.width / 1.5),
            height: Math.ceil(res.height / 1.3),
          })
        })
        window.electron.startSignalr(res.data)
        navigate('/home')
      }
    })
  }

  return (
    <>
      <div className={styles.login}>
        <div className={styles.loginBg}>
          <img src={import.meta.env.VITE_ENV === 'xy' ? ImageUrl.icon53 : ImageUrl.icon1} alt="" />
        </div>
        <div className={styles.loginContent}>
          <div>
            <div className={styles.quit}>
              <img src={ImageUrl.icon2} alt="" title='退出' className='drag' onClick={quitClick} />
            </div>
            <div className={styles.logo}>
              <img src={ImageUrl.icon4} alt="" />
            </div>
          </div>
          <div>
            <div>
              <Input
                value={operation.account}
                onChange={e => {
                  setOperation({
                    ...operation,
                    account: e.target.value
                  })
                }}
                disabled={accountPasswordStatus}
                className={`${styles.loginInputIcon} drag`}
                style={{ marginBottom: '12px' }}
                placeholder="请输入账号"
                prefix={<img src={ImageUrl.icon5} alt="" />}
                suffix={
                  (accountPasswordStatus && operation.account ? <span
                    style={{ color: '#47D3D0', cursor: 'pointer' }}
                    onClick={resetClick}
                  >重置
                  </span> : null)
                }
              />

              {!accountPasswordStatus ? <div style={{ marginTop: '36px' }} className={`drag`}>
                <Button type="primary"
                  onClick={continueClick}
                  style={{ width: '100%' }}
                  className={`${styles.loginButton} m-ant-btn`}
                >继续</Button>
              </div> : null}
              {accountPasswordStatus ? <div className={`animate__animated animate__fadeIn`}>
                <Input.Password
                  value={operation.password}
                  onChange={e => {
                    setOperation({
                      ...operation,
                      password: e.target.value
                    })
                  }}
                  className={`${styles.loginInputIcon} drag`}
                  style={{ marginBottom: '36px' }}
                  placeholder="请输入密码"
                  prefix={<img src={ImageUrl.icon6} alt="" />}
                />
                <Button type="primary" className={`${styles.loginButton} drag m-ant-btn`} onClick={loginClick} style={{ width: '100%' }}>登录</Button>
                <div className={`${styles.operation} drag`}>
                  <Checkbox.Group
                    options={operation.options}
                    value={operation.optionsValue}
                    onChange={changeOptionsValue}
                  />
                </div>
              </div> : null}
            </div>
          </div>
          <div>
            <div></div>
            <span>游客登录</span>
            <div></div>
          </div>
          <div className={`drag`}>
            <div>
              <Input
                placeholder="输入会议号"
                style={{ height: '44px' }}
                value={anonInfo.roomNum}
                onChange={e => {
                  setAnonInfo({
                    ...anonInfo,
                    roomNum: e.target.value
                  })
                }} />
            </div>
            <div
              onClick={() => {
                if (!anonInfo.roomNum) {
                  return message.error('请输入房间号!')
                }
                GetCheckoutRoomNum(anonInfo.roomNum).then(res => {
                  if (res.code === 200) {
                    if (res.data) {
                      window.electron.getRegistry().then(async (res: any) => {
                        const uuid = uuidv4();
                        if (!res) {
                          window.electron.setRegistry(uuid)
                        }
                        setAnonInfo({
                          ...anonInfo,
                          deviceId: res ? res.value : uuid,
                          nickName: storage.getItem('nickName') || ''
                        })
                        storage.getItem('nickName')
                        setNameModal(true)
                      })
                    } else {
                      message.error('房间号不存在!')
                    }
                  }
                })
              }}
            ><img src={ImageUrl.icon3} alt="" /></div>
          </div>
          <div>
            版本号：{version}
          </div>
        </div>
      </div>
      <Modal title="参会昵称" open={nameModal} footer={null} closable={false} centered width={'300px'}>
        <div>
          <div>
            <Input
              placeholder="请输入参会昵称"
              value={anonInfo.nickName}
              onChange={(e) => {
                setAnonInfo({
                  ...anonInfo,
                  nickName: e.target.value
                })
                storage.setItem('nickName', e.target.value)
              }}
            />
          </div>
          <div style={{
            display: 'flex', justifyContent: 'center', marginTop: '10px'
          }}>
            <Button type="primary" style={{ backgroundColor: '#31353A', marginRight: '14px' }} onClick={() => setNameModal(false)}>取消</Button>
            <Button type="primary" className='m-ant-btn' onClick={() => {
              if (!anonInfo.nickName) {
                return message.error('请输入参会昵称！')
              }
              storage.setItem('loading', true)
              PostAnonLogin(anonInfo).then(async (res) => {
                if (res.code == 200) {
                  storage.setItem('user', JSON.stringify(res.data))
                  storage.setItem('userLogin', true)
                  await window.electron.startSignalr(res.data)
                  getRoomRtcToken(anonInfo.roomNum, (options: any) => {
                    if (options) {
                      GetRoomInfo(anonInfo.roomNum).then(async (res) => {
                        if (res.code === 200) {
                          setTimeout(() => {
                            storage.setItem('loading', false)
                            window.electron.getWindowSize().then((res: any) => {
                              window.electron.setMainWindowSize({
                                width: Math.ceil(res.width / 1.5),
                                height: Math.ceil(res.height / 1.3),
                              })
                            })
                            navigate(`/meeting`, {
                              state: {
                                channelId: anonInfo.roomNum,
                                token: options.token,
                                tokenA: options.tokenA,
                                roomId: res.data.id,
                                roomName: res.data.roomName,
                                enableMicr: false,
                                enableCamera: false,
                              }
                            })
                          }, 2000)
                        } else {
                          storage.setItem('loading', false)
                        }
                      }).catch(() => {
                        storage.setItem('loading', false)
                      })
                    }
                  })
                }
              }).catch(() => {
                storage.setItem('loading', false)
              })
            }}>进入</Button>
          </div>
        </div>
      </Modal>
    </>
  )
}

export default Login
