
import { useEffect, useState, useRef } from "react";
import '@/utils/styles/App.scss'
import { Route, Routes, useNavigate, Navigate, useLocation } from 'react-router-dom';
import Home from '@/page/Home/index'
import Index from '@/page/Home/Index/index'
import User from '@/page/Home/User/index'
import Login from '@/page/Login/index'
import Meeting from '@/page/Meeting/index'
import NotFound from '@/page/NotFound/index'
import { storage } from '@/utils'
import { Spin, message } from "antd";
import { onInvitation, onInvoke, onReconnected, onStart } from "@/utils/package/signalr";
import JoinMeetingModal from "./components/JoinMeetingModal";
import * as CryptoJS from 'crypto-js';
import { PostLogin } from "@/api/Login";
import { startSignalr } from '@/utils/package/signalr';
import agora from "./utils/package/agora";

const App: React.FC = () => {
  const navigate = useNavigate();
  const { state } = useLocation();
  const joinMeetingModalRef = useRef<any>();
  const [_windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });
  const [spinning, setSpinning] = useState(false);
  const [isState, setIsState] = useState(true);
  useEffect(() => {
    function toLogin() {
      try {
        window.electron.setMainWindowSize({
          width: 752,
          height: 520,
          key: 'login'
        })
      } catch { }
      storage.removeItem('user')
      navigate('/login')
    }
    function toHome() {
      try {
        window.electron.setMainWindowSize({
          width: 1200,
          height: 800,
        })
      } catch { }
      navigate('/home')
    }
    let userInfo = JSON.parse(storage.getItem('user') as string)
    let loginInfo = JSON.parse(storage.getItem('login') as string)
    if (userInfo) {
      if (loginInfo && loginInfo.isAutoLogin) {
        PostLogin({
          account: loginInfo.account,
          pwd: CryptoJS.MD5(loginInfo.password).toString(CryptoJS.enc.Hex)
        }).then(res => {
          if (res.code === 200) {
            storage.setItem('user', JSON.stringify(res.data))
            toHome()
            startSignalr()
          } else {
            toLogin()
          }
        })
      } else {
        toLogin()
      }
    } else {
      toLogin()
    }
    if (import.meta.env.VITE_ENV !== 'development') {
      document.addEventListener('keydown', (event) => {
        if ((event.ctrlKey || event.metaKey) && event.key === 'r') {
          event.preventDefault();
        }
      });
    }
    window.addEventListener('resize', handleResize);
    window.addEventListener('online', handleNetworkChange);
    window.addEventListener('offline', handleNetworkChange);
    const originalSetItem = window.localStorage.setItem;
    window.localStorage.setItem = function (key, value) {
      originalSetItem.call(this, key, value);
      const event = new Event('customStorageChange') as any;
      event.key = key
      event.value = value
      window.dispatchEvent(event);
    };
    window.addEventListener('customStorageChange', handleCustomStorageChange);

    return () => {
      window.removeEventListener('resize', handleResize);
      window.removeEventListener('customStorageChange', handleCustomStorageChange);
      window.removeEventListener('online', handleNetworkChange);
      window.removeEventListener('offline', handleNetworkChange);
    };
  }, []);
  useEffect(() => {
    onInvitation((item: any) => {
      switch (item.key) {
        case 'Invitation':
          window.electron.joinNotification({
            body: item.roomName,
            name: item.InviterName,
          })
          joinMeetingModalRef.current.changeModal(item)
          break;
      }
    })
  }, [navigate])
  useEffect(() => {
    onReconnected(async () => {
      storage.setItem('reconnect', true)
    })
  }, [])
  useEffect(() => {
    if (isState) {
      setIsState(false)
      window.electron.onQuit(async () => {
        if (location.hash.indexOf('/meeting') !== -1) {
          const data = JSON.parse(localStorage.stateInfo);
          await onInvoke('levelChannel', {
            roomNum: data.channelId
          })
          await agora.leaveChannel()
        }
      })
    }
    storage.setItem('stateInfo', JSON.stringify(state))
  }, [state])
  const handleResize = (): void => {
    setWindowSize({
      width: window.innerWidth,
      height: window.innerHeight,
    });
    try {
      window.electron.getIsMaximized().then((res: boolean) => {
        const dom = document.getElementById('root') as HTMLElement;
        dom.style.borderRadius = res ? '0px' : '10px'
      })
    } catch { }
  };
  const handleCustomStorageChange = (e: any): void => {
    if (e.key === 'loading') {
      setSpinning(Boolean(e.value))
    }
  };

  const handleNetworkChange = (): void => {
    if (location.hash.indexOf('/meeting') !== -1) {
      if (navigator.onLine) {
        message.success('网络已恢复。')
        setTimeout(async () => {
          await onStart()
        }, 1000)
      } else {
        message.error('网络已断开!')
      }
    }
  }
  return (
    <>
      <Routes>
        <Route path='/' element={<Home />} />
        <Route path='/home' element={<Home />}>
          <Route path='/home' element={<Navigate to='/home/index' />} />
          <Route path='/home/index' element={<Index />} />
          <Route path='/home/user' element={<User />} />
        </Route>
        <Route path='/login' element={<Login />} />
        <Route path='/meeting' element={<Meeting />} />
        <Route path='*' element={<NotFound />} />
      </Routes>
      <Spin spinning={spinning} fullscreen />
      <JoinMeetingModal ref={joinMeetingModalRef} />
    </>
  )
}

export default App
