<template>
  <box1 />
  <box2 @switch-spot="switchSpot" />
  <box3 />
</template>

<script setup>
  import box1 from './components/box-1.vue'
  import box2 from './components/box-2.vue'
  import box3 from './components/box-3.vue'

  import { useHomeStore } from '@/stores/home'
  import { useWebSocket } from '@/hooks/socket'
  import { mode, socketBaseUrl, proSocketBaseUrl } from '@/utils/config'

  const { isConnected, dataRes, sendMessage } = useWebSocket(
    `${mode == 'dev' ? socketBaseUrl : proSocketBaseUrl}/ws/third-party`
  )
  const homeStore = useHomeStore()

  let timer = null

  watch(
    () => isConnected.value,
    (val) => {
      if (val) {
        sendMessage(
          JSON.stringify({
            action: 'start',
            type: '',
            scenicSpot: ''
          })
        )
      }
    }
  )
  watch(
    () => dataRes.value,
    (val) => {
      if (val) {
        console.log(val, '首页接受数据')
        switch (val.type) {
          case 'userPortrait':
            homeStore.setUserPortraitData(val.data)
            break
          case 'admission':
            homeStore.setScenicData(val)
            break
          case 'queuingInScenicSpots':
            homeStore.setScenicQueueData(val)
            break
          case 'queuingScenicSpots':
            homeStore.setScenicBearData(val)
            break
          case 'visitorInfo':
            homeStore.setVisitorInfoData(val.data)
            break
          case 'visitorDataInfo':
            homeStore.setVisitorInfoList(val.data)
            break
          case 'baiduMap':
            homeStore.setBaiduMapData(val.data)
            break
          case 'wordkOrderlist':
            homeStore.setWordkOrderList(val.data)
            break
          case 'wordkOrderTotal':
            homeStore.setWordkOrderData(val)
            break
          case 'trafficInformation':
            homeStore.setTrafficInfoData(val)
            break
          case 'carStopInfo':
            homeStore.setCarStopInfoData(val)
            break
          case 'carShipData':
            homeStore.setCarShipData(val.data)
            break
          case 'hotelData':
            homeStore.setHotelData(val.data)
            break
          case 'getMapNotifyInfo':
            homeStore.setNotifyInfo(val.data)
            break
        }
        if (!timer) sendCarShip()
      }
    }
  )
  const sendCarShip = (e) => {
    timer = setInterval(() => {
      if (isConnected.value) {
        sendMessage(
          JSON.stringify({
            action: 'start',
            type: 'carShipData',
            scenicSpotId: ''
          })
        )
      }
    }, 5000)
  }
  const switchSpot = (e) => {
    sendMessage(
      JSON.stringify({
        action: 'start',
        type: 'index',
        scenicSpot: e
      })
    )
  }

  onUnmounted(() => {
    if (timer) clearInterval(timer)
  })
</script>
