<template>
  <SearchBar @search="getData" />
  <RealtimeData ref="childRef" class="mt-4" />
</template>

<script setup>
import SearchBar from 'components/search-bar.vue';
import RealtimeData from 'components/realtime-data.vue';
import { computed, ref, onUnmounted } from 'vue';
import { useStore } from 'vuex';
import dayjs from 'dayjs';
import { REALTIME_DATA_INTERVAL } from '@/config/config';

const childRef = ref(null);
let timer = null;
let apiTimer = null;
const store = useStore();
const token = computed(() => store.getters['user/token']);
const realtimeData = computed(() => store.state.statistics.realtimeData);
const currentDeviceId = computed(() => store.state.device.currentDeviceId); // 正在操作的设备的id

/**
 * 实时数据统计
 */
const getData = async () => {
  try {
    if (token && token.value) {
      const start = +dayjs().startOf('day').format('x');
      const end = +dayjs().format('x');
      const params = {
        deviceId: currentDeviceId.value,
        date: [start, end],
        type: 0,
      };
      await store.dispatch('statistics/getRealtimeData', params);
      timer && clearTimeout(timer);
      timer = null;
      childRef.value.changeDate(realtimeData.value.data);

      // 定时轮询请求新数据
      if (!apiTimer) {
        apiTimer = setInterval(() => {
          getData();
        }, REALTIME_DATA_INTERVAL);
      }
    } else {
      timer = setTimeout(() => {
        getData();
      }, 20);
    }
  } catch (error) {
    console.log('error: ', error);
  }
};

getData();

onUnmounted(() => {
  apiTimer && clearInterval(apiTimer);
  apiTimer = null;
});
</script>
