<script setup lang="ts">
import { getStatus } from 'apis/system'
import { socket } from 'libs/socket'
import { useSystemStore } from 'stores/systemStore'
import { onBeforeUnmount, onMounted, ref } from 'vue'

const systemStore = useSystemStore()
onMounted(async () => {
  const res = await getStatus()
  console.log(res)
  systemStore.updateSystemStatus(res)
  startProgress()
})

socket.init((data: System.SystemStatus) => {
  systemStore.updateSystemStatus(data)
}, 'status')

const progress = ref(0)
let timer: any = null
const version = __APP_VERSION__

const startProgress = () => {
  const max = Math.floor(Math.random() * (90 - 80 + 1)) + 80
  timer = setInterval(() => {
    const randomStep = Math.floor(Math.random() * 9 + 1)

    if (systemStore.systemStatus.initComplete) {
      // 停止计时器
      progress.value = Math.min(progress.value + randomStep, 100)
    }
    else {
      progress.value = Math.min(progress.value + randomStep, max)
    }

    if (progress.value >= 100) {
      clearInterval(timer)
    }
  }, 100)
}

// 组件卸载时清理定时器
onBeforeUnmount(() => {
  clearInterval(timer)
})
</script>

<template>
  <!-- 进度条容器 -->
  <div v-if="progress < 100" class="main-content">
    <div class="progress-container">
      <div class="progress-bar" :style="{ width: `${progress}%` }" />
      <div class="progress-text">
        v{{ version }}系统初始化中 {{ progress }}%
      </div>
    </div>
  </div>

  <router-view v-else v-slot="{ Component }" class="main-content">
    <transition name="el-zoom-in-center">
      <component :is="Component" />
    </transition>
  </router-view>
</template>

<style scoped lang="scss">
.main-content {
  width: 100%;
  height: 100%;
  background: url("assets/images/background.svg") no-repeat center;
  background-size: cover;
  overflow: hidden;
}
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: #f0f2f5;
}
img {
  width: 600px;
  position: absolute;
  top: 40%;
  right: 20%;
}

.progress-container {
  width: 50%;
  height: 20px;
  background: #e4e7ed;
  border-radius: 30px;
  position: relative;
  top: 90%;
  margin: 0 auto;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg,  #1989FA, #096ae0);
  border-radius: 30px;
  transition: width 0.3s ease;
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  font-size: 12px;
  line-height: 12px;
  font-weight: 500;
}
</style>
