<template>
  <SearchBar @search="getDate" />
  <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';

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

/**
 * 实时数据统计
 * @param {*} deviceId // 站点 设备id
 * @param {*} date // 年月时间段
 * @param {*} sort // 1 -> 按时间正序 -1->按时间倒序
 * @param {*} page // 第几页
 * @param {*} size // 每页多少条
 * @param {*} type // 0查全部
 */
const getDate = async () => {
  try {
    if (token) {
      const startTime = new Date(new Date(new Date().toLocaleDateString()).getTime());
      const start = dayjs(startTime).format('X');
      const end = dayjs(new Date()).format('X');

      const params = {
        deviceId: currentDeviceId.value,
        date: [start, end],
        sort: 1,
        page: 1,
        size: 10,
        type: 0,
      };
      await store.dispatch('statistics/getRealtimeData', params);
      timer && clearTimeout(timer);
      timer = null;
      childRef.value.changeDate(realtimeData.value);
    } else {
      timer = setTimeout(() => {
        getDate();
      });
    }
  } catch (error) {
    console.log('error: ', error);
  }
};

getDate();
apiTimer = setInterval(() => {
  getDate();
}, 5000);

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