<template>
  <SearchBar @search="onSearch" :loading-search="loadingSearch" />
  <HistoryData ref="childRef" class="mt-4" />
</template>

<script setup>
import SearchBar from 'components/search-bar-data.vue';
import HistoryData from 'components/data-report.vue';
import { computed, ref } from 'vue';
import { useStore } from 'vuex';

const childRef = ref(null);

let timer = 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 search = ref({});
const loadingSearch = ref(false);

/**
 * 历史数据统计
 * @param {*} deviceId // 站点 设备id
 * @param {*} date // 年月时间段
 * @param {*} sort // 1 -> 按时间正序 -1->按时间倒序
 * @param {*} page // 第几页
 * @param {*} size // 每页多少条
 * @param {*} type // 0查全部
 */
const getDate = async () => {
  try {
    if (token && token.value) {
      loadingSearch.value = true;
      const options = { ...search.value };
      const date = options && options.date ? options.date : [];
      const params = {
        deviceId: currentDeviceId.value,
        date,
        type: 0,
      };
      await store.dispatch('statistics/getRealtimeData', params);
      timer && clearTimeout(timer);
      timer = null;
      childRef.value.changeDate(realtimeData.value.data);
      loadingSearch.value = false;
    } else {
      loadingSearch.value = false;
      timer = setTimeout(() => {
        getDate();
      });
    }
  } catch (error) {
    loadingSearch.value = false;
    console.log('error: ', error);
  }
};

getDate();

/**
 * 监听search信息
 * @param {object} payload search组件emit的数据
 */
const onSearch = payload => {
  search.value = { ...payload };
  getDate();
};
</script>
