<!-- 设备历史数据 -->
<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="时间范围" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 最新数据展示 -->
    <el-card class="mb-4" v-if="latestData">
      <template #header>
        <div class="flex items-center">
          <Icon icon="ep:data-line" class="mr-2" />
          <span class="font-semibold">最新数据</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="4">
          <div class="text-center">
            <div class="text-2xl font-bold text-blue-600">{{ latestData.temperatureC || '-' }}</div>
            <div class="text-sm text-gray-500">温度(°C)</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="text-center">
            <div class="text-2xl font-bold text-green-600">{{ latestData.currentValue || '-' }}</div>
            <div class="text-sm text-gray-500">电流(A)</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="text-center">
            <div class="text-2xl font-bold text-orange-600">{{ latestData.powerW || '-' }}</div>
            <div class="text-sm text-gray-500">功率(W)</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="text-center">
            <div class="text-2xl font-bold text-purple-600">{{ latestData.counter1Total || '0' }}</div>
            <div class="text-sm text-gray-500 mb-2">计数器1累计</div>
            <el-button
              type="warning"
              size="small"
              @click="handleResetCounter(1)"
              :loading="resetLoading1"
            >
              清零1
            </el-button>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="text-center">
            <div class="text-2xl font-bold text-red-600">{{ latestData.counter2Total || '0' }}</div>
            <div class="text-sm text-gray-500 mb-2">计数器2累计</div>
            <el-button
              type="warning"
              size="small"
              @click="handleResetCounter(2)"
              :loading="resetLoading2"
            >
              清零2
            </el-button>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="text-center">
            <div class="text-lg font-semibold text-gray-700">{{ formatDate(latestData.collectedAt) }}</div>
            <div class="text-sm text-gray-500">采集时间</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 列表 -->
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      height="600"
    >
      <el-table-column label="采集时间" align="center" prop="collectedAt" >
        <template #default="scope">
          <span>{{ formatDate(scope.row.collectedAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="温度(°C)" align="center" prop="temperatureC" >
        <template #default="scope">
          <span>{{ scope.row.temperatureC || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电流(A)" align="center" prop="currentValue" >
        <template #default="scope">
          <span>{{ scope.row.currentValue || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="功率(W)" align="center" prop="powerW" >
        <template #default="scope">
          <span>{{ scope.row.powerW || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="运行状态" align="center" prop="isOn" >
        <template #default="scope">
          <el-tag :type="scope.row.isOn ? 'success' : 'danger'">
            {{ scope.row.isOn ? '运行' : '停止' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="计数器1" align="center" prop="counter1" >
        <template #default="scope">
          <span>{{ scope.row.counter1 || '0' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计数器2" align="center" prop="counter2" >
        <template #default="scope">
          <span>{{ scope.row.counter2 || '0' }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="计数器1累计" align="center" prop="counter1Total" width="120">-->
<!--        <template #default="scope">-->
<!--          <span>{{ scope.row.counter1Total || '0' }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="计数器2累计" align="center" prop="counter2Total" width="120">-->
<!--        <template #default="scope">-->
<!--          <span>{{ scope.row.counter2Total || '0' }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="模拟量1" align="center" prop="analog1" width="90">-->
<!--        <template #default="scope">-->
<!--          <span>{{ scope.row.analog1 || '-' }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="模拟量2" align="center" prop="analog2" width="90">-->
<!--        <template #default="scope">-->
<!--          <span>{{ scope.row.analog2 || '-' }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="模拟量3" align="center" prop="analog3" width="90">-->
<!--        <template #default="scope">-->
<!--          <span>{{ scope.row.analog3 || '-' }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="模拟量4" align="center" prop="analog4" width="90">-->
<!--        <template #default="scope">-->
<!--          <span>{{ scope.row.analog4 || '-' }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="模拟量5" align="center" prop="analog5" width="90">-->
<!--        <template #default="scope">-->
<!--          <span>{{ scope.row.analog5 || '-' }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="模拟量6" align="center" prop="analog6" width="90">-->
<!--        <template #default="scope">-->
<!--          <span>{{ scope.row.analog6 || '-' }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="模拟量7" align="center" prop="analog7" width="90">-->
<!--        <template #default="scope">-->
<!--          <span>{{ scope.row.analog7 || '-' }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="数字量1" align="center" prop="digital1" width="80">-->
<!--        <template #default="scope">-->
<!--          <el-tag :type="scope.row.digital1 ? 'success' : 'info'" size="small">-->
<!--            {{ scope.row.digital1 ? '1' : '0' }}-->
<!--          </el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="数字量2" align="center" prop="digital2" width="80">-->
<!--        <template #default="scope">-->
<!--          <el-tag :type="scope.row.digital2 ? 'success' : 'info'" size="small">-->
<!--            {{ scope.row.digital2 ? '1' : '0' }}-->
<!--          </el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="数字量3" align="center" prop="digital3" width="80">-->
<!--        <template #default="scope">-->
<!--          <el-tag :type="scope.row.digital3 ? 'success' : 'info'" size="small">-->
<!--            {{ scope.row.digital3 ? '1' : '0' }}-->
<!--          </el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="数字量4" align="center" prop="digital4" width="80">-->
<!--        <template #default="scope">-->
<!--          <el-tag :type="scope.row.digital4 ? 'success' : 'info'" size="small">-->
<!--            {{ scope.row.digital4 ? '1' : '0' }}-->
<!--          </el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="数字量5" align="center" prop="digital5" width="80">-->
<!--        <template #default="scope">-->
<!--          <el-tag :type="scope.row.digital5 ? 'success' : 'info'" size="small">-->
<!--            {{ scope.row.digital5 ? '1' : '0' }}-->
<!--          </el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="数字量6" align="center" prop="digital6" width="80">-->
<!--        <template #default="scope">-->
<!--          <el-tag :type="scope.row.digital6 ? 'success' : 'info'" size="small">-->
<!--            {{ scope.row.digital6 ? '1' : '0' }}-->
<!--          </el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="原始帧数据" align="center" prop="frameRaw" min-width="200">-->
<!--        <template #default="scope">-->
<!--          <el-tooltip :content="scope.row.frameRaw" placement="top">-->
<!--            <span class="truncate">{{ scope.row.frameRaw || '-' }}</span>-->
<!--          </el-tooltip>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import { formatDate } from '@/utils/formatTime'
import { DeviceApi, DeviceHistoryDataVO, DeviceVO } from '@/api/iot/device/device'

defineOptions({ name: 'DeviceDetailsData' })

const { device } = defineProps<{ device: DeviceVO }>() // 定义 Props

const message = useMessage() // 消息弹窗
const loading = ref(true) // 列表的加载中
const list = ref<DeviceHistoryDataVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const latestData = ref<DeviceHistoryDataVO | null>(null) // 最新数据
const resetLoading1 = ref(false) // 清零1按钮加载状态
const resetLoading2 = ref(false) // 清零2按钮加载状态
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceId: device.id,
  dateRange: [] as any[],
  startTime: undefined as any,
  endTime: undefined as any
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 处理时间范围
    if (queryParams.dateRange && queryParams.dateRange.length === 2) {
      queryParams.startTime = queryParams.dateRange[0]
      queryParams.endTime = queryParams.dateRange[1]
    } else {
      queryParams.startTime = undefined
      queryParams.endTime = undefined
    }

    const data = await DeviceApi.getDeviceDataPage(queryParams)
    list.value = data.list
    total.value = data.total

    // 设置最新数据（列表第一条，因为已按时间倒序排序）
    latestData.value = data.list && data.list.length > 0 ? data.list[0] : null
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.dateRange = []
  handleQuery()
}

/** 重置计数器累计值 */
const handleResetCounter = async (counterType: number) => {
  try {
    // 确认操作
    await message.confirm(`确定要将计数器${counterType}的累计值重置为0吗？\n此操作只会重置最新一条数据的累计值，不影响历史记录。`, '警告')

    // 设置加载状态
    if (counterType === 1) {
      resetLoading1.value = true
    } else {
      resetLoading2.value = true
    }

    // 调用API重置计数器
    await DeviceApi.resetDeviceCounter(device.id, counterType)

    // 显示成功消息
    message.success(`计数器${counterType}累计值已清零`)

    // 刷新数据
    await getList()
  } catch (error) {
    // 用户取消或操作失败
    console.error('重置计数器失败:', error)
  } finally {
    // 取消加载状态
    if (counterType === 1) {
      resetLoading1.value = false
    } else {
      resetLoading2.value = false
    }
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
.truncate {
  display: inline-block;
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
