import { useAppStore } from '@/store';
import { MessagePlugin } from 'tdesign-vue-next';

export default function () {
  const appStore = useAppStore();

  function checkDocIsFullscreen() {
    return (
      document.fullscreenElement ||
      document.msFullscreenElement ||
      document.mozFullscreenElement ||
      document.webkitFullscreenElement
    );
  }

  async function switchFullscreen() {
    const fullscreenEnabled =
      document.fullscreenEnabled ||
      document.mozFullScreenEnabled ||
      document.webkitFullscreenEnabled ||
      document.msFullscreenEnabled;
    if (!fullscreenEnabled) {
      MessagePlugin.error('当前浏览器不支持全屏！');
      return;
    }
    const de = document.documentElement;
    const requestFullscreen =
      de.requestFullscreen ||
      de.mozRequestFullScreen ||
      de.webkitRequestFullscreen;
    const exitFullscreen =
      document.exitFullscreen ||
      document.mozCancelFullScreen ||
      document.webkitCancelFullScreen;

    if (appStore.isFullscreen) {
      await exitFullscreen.call(document).catch(() => {});
    } else {
      await requestFullscreen.call(de).catch(() => {});
    }
  }

  function registFullscreenChange() {
    document.documentElement.onfullscreenchange = () => {
      const isFullscreen = checkDocIsFullscreen();
      appStore.setIsFullScreen(isFullscreen);
      if (isFullscreen) {
        document.body.className += ' app-fullscreen';
        document.documentElement.setAttribute('theme-mode', 'dark');
      } else {
        document.body.className = document.body.className.replace(
          'app-fullscreen',
          ''
        );
        document.documentElement.removeAttribute('theme-mode');
      }
    };

    document.addEventListener('keydown', (e) => {
      if (e.keyCode === 122 || (e.keyCode === 27 && checkDocIsFullscreen())) {
        e.preventDefault();
        switchFullscreen();
      }
    });

    appStore.setIsFullScreen(checkDocIsFullscreen());
  }

  return {
    switchFullscreen,
    registFullscreenChange,
  };
}
