<template>
  <div class="app-wrapper">
    <v-sidebar />
    <v-header />
    <div class="main-container">
      <div class="app-main" :class="{ 'content-collapse': sidebar.collapse }">
        <router-view v-slot="{ Component }">
          <transition name="move" mode="out-in">
            <keep-alive :include="[]">
              <component :is="Component"></component>
            </keep-alive>
          </transition>
        </router-view>
      </div>
    </div>
    <Alarm ref="alarmRef" />
    <audio ref="audioPlayer" hidden>
      <source src="../assets/audio/alarm.mp3" type="audio/mpeg" />
    </audio>
  </div>
</template>
<script setup lang="ts">
import { useSidebarStore } from "@/store/sidebar";
import vHeader from "@/components/header.vue";
import vSidebar from "@/components/sidebar.vue";
import { inject, onBeforeUnmount, onMounted, ref } from "vue";
import { format } from "@/utils";
import Alarm from "@/components/alarm.vue";
import { ElMessageBox } from "element-plus";

const ws: any = inject("ws");
const sidebar = useSidebarStore();
const audioPlayer = ref(null);
const alarmRef = ref();

const handleBeforeUnload = (event: any) => {
  localStorage.removeItem("isReload");
};

const onMessage = (res) => {
  if (res.cmd == "warning") {
    alarmRef.value.visible = true;
    alarmRef.value.warningList.unshift({ ...res, createTime: format(new Date(), "HH:mm:ss") });
    if (audioPlayer.value) {
      audioPlayer.value.play().catch((error) => {
        console.error("自动播放被阻止:", error);
      });
    }
  }
};

onMounted(() => {
  const isReload = localStorage.getItem("isReload");
  if (isReload !== "true") {
    ElMessageBox.alert("由于浏览器安全策略，用户必须点击屏幕才能播放告警声音", "提示", {
      confirmButtonText: "OK",
      callback: () => {
        localStorage.setItem("isReload", "true");
      },
    });
  }

  if (ws.socket == null) {
    ws.connect();
  }
  ws.onMessage(onMessage);

  window.addEventListener("beforeunload", handleBeforeUnload);
});

onBeforeUnmount(() => {
  window.removeEventListener("beforeunload", handleBeforeUnload);
});
</script>

<style scoped lang="less">
// @media screen and (max-width: 800px) {
//   .main-container {
//     margin-left: 0 !important;
//   }
//   .sidebar-container {
//     width: 0 !important;
//   }
//   .app-wrapper-header {
//     width: 100% !important;
//   }
// }
.app-wrapper {
  position: relative;
  width: 100%;
  height: 100vh;
  background: #f0f2f5;
  overflow: hidden;
  .main-container {
    height: 100vh;
    margin-left: 210px;
    min-height: 100%;
    position: relative;
    transition: 0.3s;
    background-color: #f2f4fa;
  }
  .app-main {
    // height: 100vh;
    height: calc(100vh - 90px);
    position: relative;
    width: 100%;
    display: flex;
    flex-direction: column;
    // padding-top: 70px;
    margin-top: 70px;
    box-sizing: border-box;
    overflow: hidden;
  }
}
</style>
