<script setup>
import HeaderGroup  from './components/HeaderGroup';
import Sidebar from './components/Sidebar'
import TelNoticeBar from './components/TelNoticeBar'
import TelNoticeBox from './components/TelNoticeBox'
import NoticeBar from './components/NoticeBar'
import { AppMain } from './components'
import useVoiceStore from "@/store/modules/voice";
import useUserStore from "@/store/modules/user";
import { workbenchApi } from '@/api/voice/workbench';

import Cookies from 'js-cookie'

const useVoice = useVoiceStore();
const useUser = useUserStore();
const audioRef = ref(null);

const intervalTimer = ref(null);

let worker = null;
const isInitInProgress = ref(false); // 防止 `init()` 被多次调用

const init = async () => {
  if (isInitInProgress.value) return; // 防止重复初始化
  isInitInProgress.value = true;
  
  try {
    const { data } = await workbenchApi.getSeatsByUser({ userId: useUser.id });
    if (data) {
      await useVoice.HS_CTI_INSTANCE(data.outId);
      const voiceStatus = sessionStorage.getItem('VOICE_STATUS');
      setTimeout(async () => {
        if ( [100001, 100002].includes( Number(useVoice.HSCTIERRORCODE) ) ) {
          useVoice.systemState = false;
        } else {
          await useVoice.getAgentStatus();
          if ( voiceStatus && [1, 2].includes( Number(useVoice.AGENTSTATUS) )) {
            voiceStatus == 'busy' ? useVoice.setBusy() : useVoice.setIdle();
          } else {
            useVoice.setIdle();
          }
        }
      }, 2000);
    }
  } catch (error) {
    console.error("Error in init:", error);
  } finally {
    isInitInProgress.value = false;
    console.log("init complete");
  }

};
const handleWorkerMessage = async (event) => {
  if (event.data === "check" && useVoice.isAuthPane) {  
    const sdkRegister = Cookies.get("sdkRegister");
    if (!sdkRegister && !useVoice.noiceBarVisibleState && useVoice.AGENTSTATUS !== 0) {
      console.log("Reinitializing...");
      await useVoice.unInit();
      await init();
    }
  }
};

onMounted(async() => {
  if(useVoice.isAuthPane){
    await init();
    if (!worker) {
      worker = new Worker(new URL("@/workers/worker.js", import.meta.url), { type: "module" });
      worker.onmessage = handleWorkerMessage;
      worker.postMessage("start");
    }
  }
})

onUnmounted(() => {
  if(worker && useVoice.isAuthPane){
    worker.postMessage("stop");
    worker.terminate();
    worker = null;
  }
});

</script>

<template>
  <div class="app-wrapper">
    <HeaderGroup></HeaderGroup>
    <div class="main-wrapper">
      <Sidebar class="sidebar-container" />
      <AppMain class="main-container"/>
    </div>
    <TelNoticeBar></TelNoticeBar>
    <TelNoticeBox></TelNoticeBox>
    <NoticeBar></NoticeBar>
  </div>
</template>

<style lang="scss" scoped>
@import "@/assets/styles/mixin.scss";
@import "@/assets/styles/variables.module.scss";

.app-wrapper {
  @include clearfix;
  position: relative;
  height: 100vh;
  width: 100vw;
  background: #EFF1F8;
  overflow: hidden;
  
  .main-wrapper {
    display: flex;
    height: calc(100% - 92px);
    padding: 0 20px 20px 0;
    
    .sidebar-container {
      height: 100%;
      flex-shrink: 0;
    }
  }
}

</style>