<!--
 * @Author: chris
 * @Date: 2025-10-15 17:07:16
 * @LastEditors: chris
 * @LastEditTime: 2026-01-23 12:01:04
-->
<script setup>
import HistoryTable from './components/HistoryTable.vue';
import SearchForm from './components/SearchForm.vue';
import Statistics from './components/Statistics.vue';
import { columnsConfig, defaultQueryParams } from './config';
import { useSettings } from '@/hooks/useSettings';
import { listNotify } from '@/api/pest/pushHistory';

const { hasTags } = useSettings();
const { proxy } = getCurrentInstance();

const historyList = ref([]);
const chartData = ref([]);
const total = ref(0);
const loading = ref(false);
const queryParams = ref({...defaultQueryParams});

getHistoryList();

async function getHistoryList () {
  loading.value = true;
  try {
    const res = await listNotify(queryParams.value);
    historyList.value = res.rows;
    chartData.value = createChartData(res.rows)
    total.value = res.total;
  } catch (error) {
    proxy.$modal.msgError('获取推送历史数据失败: ' + (error.message || '未知错误'))
    console.error('Failed to get push history data:', error)
  } finally {
    loading.value = false;
  }
}

function handleSelectionChange(selection) {
  console.log(selection)
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getHistoryList();
}

function handleReset(queryRef) {
  queryParams.value = {...defaultQueryParams}
  queryRef.resetFields()
  getHistoryList()
}

async function handleExport() {
  const fileName = await proxy.download_2('/business/device-data/export', queryParams.value, `土壤墒情设备数据_${new Date().getTime()}.xlsx`)
  fileName && proxy.$download.name(fileName)
}

function createChartData(data) {
  const res = {}
  data.forEach(item => {
    const date = item.createTime?.split(' ')[0]
    res[date] ? res[date]++ : (res[date] = 1)
  })
  return {
    names: Object.keys(res),
    data: Object.values(res)
  }
}
</script>

<template>
  <div :class="['push-history-page', 'page-height', { 'hasTagsView': hasTags }]">
    <el-card class="history-table-card">
      <!-- 搜索表单 -->
      <search-form v-model:params="queryParams" class="mb-12px" @query="handleQuery" @reset="handleReset" @export="handleExport" />
      <!-- 历史记录表格 -->
      <history-table :dataList="historyList" :columns="columnsConfig" :loading="loading" @selection-change="handleSelectionChange" />
      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getHistoryList" />
    </el-card>
    <el-card class="analysis-card">
      <statistics :chartData="chartData" />
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.push-history-page {
  @apply p-20px flex flex-col gap-15px;
}

.history-table-card {
  @apply flex-1;
}

.analysis-card {
  @apply h-380px;
}
</style>

