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

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

const searchBar = ref(null);
let timer = null;
const store = useStore();
const token = computed(() => store.getters['user/token']);
const currentDeviceId = computed(() => store.state.device.currentDeviceId); // 正在操作的设备的id
const search = ref({});
const loadingSearch = ref(false);
const searchHeight = ref(50);

onMounted(() => {
  searchHeight.value = searchBar.value.$el.clientHeight;
});

/**
 * 历史数据统计
 * @param {*} deviceId // 站点 设备id
 * @param {*} date // 年月时间段
 * @param {*} sort // 1 -> 按时间正序 -1->按时间倒序
 * @param {*} page // 第几页
 * @param {*} size // 每页多少条
 * @param {*} type // 0查全部
 */
const getData = async () => {
  try {
    if (token && token.value) {
      if (!currentDeviceId.value) return;
      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;
      loadingSearch.value = false;
    } else {
      loadingSearch.value = false;
      timer = setTimeout(() => {
        getData();
      });
    }
  } catch (error) {
    loadingSearch.value = false;
    console.log('error: ', error);
  }
};

getData();

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