<script setup lang="ts">
import { useDeviceStore } from 'stores/deviceStore'
import { useHomeStore } from 'stores/homeStore'
import { useLiquidStore } from 'stores/liquidStore'
import { useSystemStore } from 'stores/systemStore'
import { onBeforeMount, ref } from 'vue'

import { sendCmd, subscribeEvent } from '@/apis/system'

import { useDebugStore } from './stores/debugStore'
import { useFormulaStore } from './stores/formulaStore'
import { useSealStore } from './stores/sealStore'

/**
 * 应用初始化组件
 * @description 负责系统初始化流程控制，包括设备信息获取、数据同步及进度展示
 */

// 状态管理
const deviceStore = useDeviceStore()
const homeStore = useHomeStore()
const formulaStore = useFormulaStore()
const liquidStore = useLiquidStore()
const systemStore = useSystemStore()
const sealStore = useSealStore()
const deviceStateStore = useDeviceStore()
const debugStore = useDebugStore()
const deviceType = useDeviceStore().deviceTypeMap
// 组件状态
const progress = ref(0) // 初始化进度百分比
const version = __APP_VERSION__ // 应用版本号
let timer: any = null // 进度条定时器

/**
 * @hook 生命周期钩子 - 组件挂载前执行
 * @description 启动初始化流程和数据轮询
 */
onBeforeMount(async () => {
  startProgress() // 启动进度条
  await systemStore.getSystemTime() // 获取系统时间
})
// 监听设备的主动上报数据，并根据上报类型 保存到对应的store
subscribeEvent('stateUpdate', (data) => {
  if (data.fromClass === 'AirLeakDetectTest') {
    // 气密性测试
    sealStore.updateSealInfo(data.rely)
  }
  else if (data.fromClass === 'AddLiquidService') {
    // 加液服务
    liquidStore.updateAddLiquidWorkState(data.rely)
  }
  else if (data.fromClass === 'DrainLiquidService') {
    // 排液服务
    liquidStore.updateDrainLiquidWorkState(data.rely)
  }
  else if (data.fromClass === 'DisinfectionCtrlServiceExt') {
    // 消毒状态上报
    homeStore.updateHomeDisinfectionState(data.rely)
  }
  else if (data.fromClass === 'H2O2SensorMgr') {
    // console.log(data.rely)
    // 首页传感器状态上报
    homeStore.updateHomeData(data.rely)
  }
  else if (data.fromClass === 'AppCore') {
    // 应用事件上报
    deviceStateStore.setDeviceState(data.rely)
    systemStore.insertLogs(data.rely.appEvents)
  }
  else if (data.fromClass === 'TestPageCtrlService') {
    // 测试页面状态上报
    debugStore.updateDebugPageState(data.rely)
  }
})

/**
 * @function 启动初始化进度条
 * @desc 模拟初始化进度，同步加载各项数据
 */
const startProgress = () => {
  timer = setInterval(async () => {
    // 生成随机进度增长（1-9%）
    const randomStep = Math.floor(Math.random() * 9 + 1)
    progress.value = Math.min(progress.value + randomStep, 100)
    const deviceInfo: Device.DeviceInfo = await initDeviceInfo()
    if (deviceInfo.deviceType === deviceType.LargeSpaceDM_B) {
      await initData() // 核心数据
    }
    else {
      await initData() // 核心数据
      await initLiquidConfig() // 液体配置
    }
    // 进度完成后清除定时器
    if (progress.value >= 100) {
      clearInterval(timer)
    }
  }, 100)
}

/**
 * @function 初始化核心数据
 * @desc 同步获取消毒状态
 */
const initData = async () => {
  // 获取消毒状态
  // const disinfectionParams = {
  //   className: 'DisinfectionCtrlServiceExt',
  //   fnName: 'getState',
  // }
  // const disinfectionData = await sendCmd(disinfectionParams)
  // homeStore.updateHomeDisinfectionState(disinfectionData)
  await formulaStore.getFormualDefaultData() // 获取默认配方数据
}
/**
 * @function 初始化设备信息
 * @desc 从服务端获取设备信息并更新到状态存储
 */
const initDeviceInfo = async () => {
  const deviceParams = {
    className: 'DeviceInfoMgrService',
    fnName: 'getDeviceInfo',
  }
  const res = await sendCmd(deviceParams)
  deviceStore.updateDeviceInfo(res)
  return res
}

/**
 * @function 初始化
 * @desc 获取液体最大容量和更新周期配置
 */
const initLiquidConfig = async () => {
  const params = {
    className: 'AddLiquidService',
    fnName: 'getServiceConfig',
  }
  const liquidConfig = await sendCmd(params)
  liquidStore.initLiquidConfig(liquidConfig)

  // const liquidParams = {
  //   fnName: 'getState',
  //   className: 'AddLiquidService',
  // }
  // const liquidData = await sendCmd(liquidParams)
  // liquidStore.updateLiquidState(liquidData)
}
console.log(__DEVICE_TYPE__)
</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-slot="{ Component }" v-loading.fullscreen.lock="systemStore.loading" class="main-content">
    <transition name="">
      <component :is="Component" />
    </transition>
  </router-view>
</template>

<style scoped lang="scss">
.main-content {
  width: 100%;
  height: 100%;
  background: url('assets/images/background-logo.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>
