<!--
  Description: 报警查询列表页
  Author: 李亚光
  Date: 2025-05-28
 -->
<script name="AlarmSearch" lang="ts" setup>
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDictByCode } from '@/api/system/dict'
import { getAlarmListPage } from '@/api/data/alarm'
import type { DateModelType } from 'element-plus'
import { ElLoading, ElMessage } from 'element-plus'
import { exportFile } from '@/utils/exportUtils'
import { getGroupList } from '@/api/basic/group'
import dayjs from 'dayjs'
const dataList = ref([])
const total = ref(0)
const loadingTable = ref(true)
const searchQuery = ref({
  alarmCategory: '',  // 报警类别
  beginTime: '',// 开始时间
  devcode: '',// 设备编号
  deviceType: '',// 设备类型
  endTime: '',// 结束时间
  groupId: '', // 分组id
  offset: 1,
  limit: 20
})
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])// 筛选时间段数据
watch(dateRange, (val) => {
  if (val) {
    searchQuery.value.beginTime = dayjs(val[0]).format('YYYY-MM-DD') === 'Invalid Date' ? '' : dayjs(val[0]).format('YYYY-MM-DD')
    searchQuery.value.endTime = dayjs(val[1]).format('YYYY-MM-DD') === 'Invalid Date' ? '' : dayjs(val[1]).format('YYYY-MM-DD')
  }
  else {
    searchQuery.value.beginTime = ''
    searchQuery.value.endTime = ''
  }
})
// 表头
const columns = ref<TableColumn[]>([
  { text: '分组', value: '', align: 'center' },
  { text: '设备编号', value: '', align: 'center' },
  { text: '设备类型', value: '', align: 'center' },
  { text: '报警类别', value: '', align: 'center' },
  { text: '报警类型', value: '', align: 'center' },
  { text: '数据内容', value: '', align: 'center' },
  { text: '报警时间', value: '', align: 'center' },
])
// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    searchQuery.value.offset = 1
  }
  getAlarmListPage(searchQuery.value).then((response) => {
    dataList.value = response.data.rows
    total.value = parseInt(response.data.total)
    calcTableHeight()
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}
fetchData()
// 重置查询
const reset = () => {
  dateRange.value = ['', '']
  searchQuery.value = {
    alarmCategory: '',  // 报警类别
    beginTime: '',// 开始时间
    devcode: '',// 设备编号
    deviceType: '',// 设备类型
    endTime: '',// 结束时间
    groupId: '', // 分组id
    offset: 1,
    limit: 20
  }
  fetchData(true)
}
// 导出
const exportDataList = () => {
  if (dataList.value.length > 0) {
    const filename = `报警数据列表${new Date().valueOf()}.xlsx`

    // const loading = ElLoading.service({
    //   lock: true,
    //   text: '下载中请稍后',
    //   background: 'rgba(255, 255, 255, 0.8)',
    // })

    // // 导出接口
    // exportDeviceData(searchQuery.value).then((res) => {
    //   const blob = new Blob([res.data])
    //   exportFile(blob, filename)

    //   nextTick(() => {
    //     // 关闭loading
    //     loading.close()
    //   })
    // }).catch(() => {
    //   loading.close()
    // })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.value.limit = val.size
  }
  if (val && val.page) {
    searchQuery.value.offset = val.page
  }
  fetchData(true)
}

// 获取字典相关
const groupList = ref<any[]>([]) // 产品列表
const deviceTypeList = ref<any[]>([])  // 设备类型列表
const alarmCategoryList = ref<any[]>([])  // 报警类别列表
const fetchDict = () => {
  getGroupList({}).then((res: any) => {
    groupList.value = res.data.rows
  })
  getDictByCode('deviceType').then((res: any) => {
    deviceTypeList.value = res.data
  })
  getDictByCode('alarmCategory').then((res: any) => {
    alarmCategoryList.value = res.data
  })
}
fetchDict()

const tableHeight = ref(400)
const calcTableHeight = () => {
  // 顶部高度
  const topHeight = 110
  // app-container的 padding距离
  const appPadding = 20
  // 查询组件的高度
  const searchDiv = document.getElementById('search-div-id')
  const searchHeight = searchDiv ? searchDiv.clientHeight : 0
  // 表格顶部的文字提示高度
  const tableTopHeight = 32 + 10
  // 表格表头
  const tableHeaderHeight = 40
  // 分页器的高度
  const tablePaginationHeight = 40
  // 判断数据长度
  const height = window.innerHeight - topHeight - appPadding - searchHeight - tableTopHeight - tableHeaderHeight - tablePaginationHeight
  if (dataList.value.length * 40 >= height) {
    tableHeight.value = height
  }
  else {
    tableHeight.value = dataList.value.length ? (dataList.value.length + 1) * 40 : 200
  }
}
onBeforeUnmount(() => {
  window.removeEventListener('resize', calcTableHeight)
})
onMounted(() => {
  window.addEventListener('resize', calcTableHeight)
})
</script>

<template>
  <app-container>
    <search-area :need-clear="true" @search="fetchData" @clear="reset">
      <search-item>
        <el-select v-model="searchQuery.groupId" placeholder="选择分组" clearable style="width: 192px;">
          <el-option v-for="dict in groupList" :key="dict.id" :value="dict.id" :label="dict.groupName" />
        </el-select>
      </search-item>
      <search-item>
        <el-select v-model="searchQuery.deviceType" placeholder="设备类型" clearable style="width: 192px;">
          <el-option v-for="dict in deviceTypeList" :key="dict.id" :value="dict.value" :label="dict.name" />
        </el-select>
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.devcode" placeholder="设备编号" clearable />
      </search-item>
      <search-item>
        <el-select v-model="searchQuery.alarmCategory" placeholder="报警类别" clearable style="width: 192px;">
          <el-option v-for="dict in alarmCategoryList" :key="dict.id" :value="dict.value" :label="dict.name" />
        </el-select>
      </search-item>
      <search-item>
        <el-date-picker v-model="dateRange" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" />
      </search-item>
    </search-area>
    <table-container title="数据列表">
      <template #btns-right>
        <el-button type="primary">
          批量下发配置
        </el-button>
        <el-button type="primary" @click="exportDataList">
          导出
        </el-button>
      </template>
      <!-- 表格区域 -->
      <normal-table :data="dataList" :columns="columns" :total="total" :query="searchQuery" :list-loading="loadingTable"
        @change="changePage" :height="tableHeight">
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (searchQuery.offset! - 1) * searchQuery.limit! + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>

        <template #columns>
          <el-table-column fixed="right" label="操作" align="center" width="80">
            <template #default="{ row }">
              <el-button size="small" type="primary" link>
                查看
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>
