<!--
 * @Author: chris
 * @Date: 2025-09-11 17:11:16
 * @LastEditors: chris
 * @LastEditTime: 2026-01-23 12:01:19
-->
<script setup>
import HistoryTable from './components/HistoryTable.vue';
import SearchForm from './components/SearchForm.vue';
import { columnsConfig, defaultQueryParams } from './config';
import { useSettings } from '@/hooks/useSettings';
import { listDeviceData, exportDeviceData } from '@/api/deviceData';
import { useDict } from '@/utils/dict.js'

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

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

const { soil_type: soilTypeOptions } = useDict('soil_type')

getDeviceDataList();

async function getDeviceDataList () {
  loading.value = true;
  try {
    const res = await listDeviceData(queryParams.value);
    historyList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    proxy.$modal.msgError('获取土壤墒情设备实时数据失败: ' + (error.message || '未知错误'))
    console.error('Failed to get device live data:', error)
  } finally {
    loading.value = false;
  }
}

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

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

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

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

<template>
  <div :class="['soil-history-page', 'page-height', { 'hasTagsView': hasTags }]">
    <!-- 搜索表单 -->
    <search-form v-model:params="queryParams" :soil-options="soilTypeOptions" 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="getDeviceDataList" />
  </div>
</template>

<style lang="scss" scoped>
.soil-history-page {
  @apply p-20px;
}
</style>
