<template>
  <div class="temperature-monitor">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-card class="search-card">
        <template #header>
          <div class="card-header">
            <span>温度监控查询</span>
          </div>
        </template>

        <el-form :model="searchForm" :inline="true" class="search-form">
          <!-- 时间范围选择 -->
          <el-form-item label="时间范围">
            <el-date-picker v-model="searchForm.timeRange" type="daterange" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" class="time-picker" />
          </el-form-item>

          <!-- 设备选择 -->
          <el-form-item label="查询条件">
            <el-select v-model="searchForm.Info" placeholder="请选择查询条件" clearable filterable class="device-select">
              <el-option v-for="device in deviceOptions" :key="device.value" :label="device.label"
                :value="device.value" />
            </el-select>
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon>
                <Search />
              </el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon>
                <Refresh />
              </el-icon>
              重置
            </el-button>
            <el-button type="success" @click="handleExport">
              <el-icon>
                <Download />
              </el-icon>
              导出
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 结果展示区域 -->
    <div class="result-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>查询结果</span>
            <span class="result-count">共 {{ totalCount }} 条记录</span>
          </div>

        </template>

        <!-- 使用el-tab分别展示数据表格和分析图表 -->
        <div class="result-content">
          <el-empty v-if="!hasData" description="暂无数据" />
          <div v-else>
            <el-tabs v-model="activeTab" type="border-card" class="result-tabs" @tab-change="handleTabChange">
              <!-- 数据表格标签页 -->
              <el-tab-pane label="数据表格" name="table">
                <div class="table-container">
                  <el-table :data="tableData" border stripe style="width: 100%" :max-height="600" v-loading="loading">
                    <!-- 序号列 -->
                    <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
                    <!-- 时间列 -->
                    <el-table-column prop="datetime" label="时间" width="160" align="center" fixed="left" />
                    <!-- 动态生成传感器列 -->
                    <el-table-column v-for="sensor in sensorColumns" :key="sensor.sensorNo" :prop="sensor.sensorName"
                      :label="sensor.sensorName" width="120" align="center" show-overflow-tooltip>
                      <template #default="scope">
                        <span>
                          {{ scope.row[sensor.sensorName] ? scope.row[sensor.sensorName].toFixed(2) : '-' }}
                        </span>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-tab-pane>

              <!-- 分析图表标签页 -->
              <el-tab-pane label="分析图表" name="chart">
                <div class="chart-container">
                  <TemperatureChart ref="chartRef" :chart-data="tableData" :sensor-columns="sensorColumns" />
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </el-card>
    </div>
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="queryParams.pageNumber" v-model:page-size="queryParams.pageSize"
        :total="totalCount" layout="total, prev, pager, next, jumper" @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import { listTemperature, listByInfo } from '@/api/monitoring/temperature'
import { listChannel, channelInfoList } from '@/api/monitoring/channel'
import TemperatureChart from './TemperatureChart.vue'

// 响应式数据
const loading = ref(false)
const totalCount = ref(0)
const activeTab = ref('table')
const chartRef = ref(null)

// 搜索表单数据
const searchForm = reactive({
  timeRange: [],
  Info: '',
  queryType: '',
  deviceId: '',
  minTemp: null,
  maxTemp: null
})
const queryParams = ref({
  pageNumber: 1,
  pageSize: 48
})

// 设备选项
const deviceOptions = ref([])

// 计算属性
const hasData = computed(() => {
  return totalCount.value > 0
})

// 表格数据相关
const tableData = ref([])
const sensorColumns = ref([])
const tableList = ref([])

const getDeviceList = () => {
  channelInfoList().then(res => {
    deviceOptions.value = res.map(item => ({
      label: item,
      value: item
    }))
  })
}
getDeviceList()

// 处理表格数据，按sensorNo分组
const processTableData = () => {
  if (!tableList.value || tableList.value.length === 0) {
    tableData.value = []
    sensorColumns.value = []
    return
  }

  // 获取所有唯一的传感器编号和对应的设备信息
  const sensorMap = new Map()
  tableList.value.forEach(item => {
    if (!sensorMap.has(item.sensorNo)) {
      sensorMap.set(item.sensorNo, {
        sensorNo: item.sensorNo,
        sensorName: item.channel?.info || `传感器${item.sensorNo}`
      })
    }
  })

  // 生成传感器列配置
  sensorColumns.value = Array.from(sensorMap.values()).sort((a, b) => a.sensorNo - b.sensorNo)

  // 按时间分组数据
  const timeGroups = {}
  tableList.value.forEach(item => {
    if (!timeGroups[item.datetime]) {
      timeGroups[item.datetime] = {
        datetime: item.datetime,
        ...sensorColumns.value.reduce((acc, sensor) => {
          acc[sensor.sensorName] = null
          return acc
        }, {})
      }
    }
    const sensorName = item.channel?.info || `传感器${item.sensorNo}`
    timeGroups[item.datetime][sensorName] = item.data
  })

  // 转换为数组并排序
  tableData.value = Object.values(timeGroups)
}

const handleCurrentChange = (page) => {
  queryParams.value.pageNumber = page
  console.log(queryParams.value)
  // handleSearch()
}

// 查询监控数据
const handleSearch = async () => {
  loading.value = true
  try {
    // 验证表单
    if (!searchForm.timeRange || searchForm.timeRange.length === 0) {
      ElMessage.warning('请选择时间范围')
      return
    }
    if (!searchForm.Info || searchForm.Info.trim() === '') {
      ElMessage.warning('请选择查询条件')
      return
    }
    let startTime = searchForm.timeRange[0] + ' 00:00:00'
    let endTime = searchForm.timeRange[1] + ' 23:59:59'
    const res = await listByInfo({
      startTime: startTime,
      endTime: endTime,
      Info: searchForm.Info,
      ...queryParams.value
    })
    totalCount.value = res.total
    tableList.value = res.list

    // 处理数据，生成表格数据
    processTableData()

    ElMessage.success('查询成功')

  } catch (error) {
    ElMessage.error('查询失败')
    console.error('查询错误:', error)
  } finally {
    loading.value = false
  }
}

const handleReset = () => {
  searchForm.timeRange = []
  searchForm.Info = ''
  totalCount.value = 0
  tableList.value = []
  tableData.value = []
  sensorColumns.value = []
  ElMessage.info('已重置搜索条件')
}

const handleExport = () => {
  if (totalCount.value === 0) {
    ElMessage.warning('暂无数据可导出')
    return
  }

  ElMessage.success('导出功能开发中...')
  // 这里可以添加导出逻辑
}



// 监听标签页切换
const handleTabChange = (tabName) => {
  if (tabName === 'chart') {
    // 延迟触发图表重新渲染，确保DOM已更新
    nextTick(() => {
      setTimeout(() => {
        // 调用图表组件的resize方法
        if (chartRef.value) {
          chartRef.value.resizeChart()
        }
      }, 200)
    })
  }
}

</script>

<style lang="scss" scoped>
.temperature-monitor {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;

  .search-section {
    margin-bottom: 20px;

    .search-card {
      .card-header {
        font-weight: bold;
        color: #303133;
      }

      .search-form {
        .time-picker {
          width: 400px;
        }

        .query-select,
        .device-select {
          width: 200px;
        }

        .temp-input {
          width: 120px;
        }

        .temp-separator {
          margin: 0 10px;
          color: #909399;
        }
      }
    }
  }

  .result-section {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: bold;
      color: #303133;

      .result-count {
        font-size: 14px;
        color: #909399;
        font-weight: normal;
      }
    }

    .result-content {
      min-height: 200px;

      .pagination-container {
        margin-top: 20px;
        text-align: center;
      }

      // 标签页样式
      .result-tabs {
        .el-tabs__content {
          padding: 20px 0;
        }
      }

      // 表格容器样式
      .table-container {
        overflow-x: auto;
        width: 100%;

        // 自定义滚动条样式
        &::-webkit-scrollbar {
          height: 8px;
        }

        &::-webkit-scrollbar-track {
          background: #f1f1f1;
          border-radius: 4px;
        }

        &::-webkit-scrollbar-thumb {
          background: #c1c1c1;
          border-radius: 4px;

          &:hover {
            background: #a8a8a8;
          }
        }

        .el-table {
          .el-table__body-wrapper {
            overflow-x: auto;
          }
        }
      }

      // 图表容器样式
      .chart-container {
        width: 100%;
        height: 650px;
        min-height: 600px;
        display: flex;
        flex-direction: row;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .temperature-monitor {
    padding: 10px;

    .search-section {
      .search-card {
        .search-form {
          .time-picker {
            width: 100%;
          }

          .query-select,
          .device-select {
            width: 100%;
          }
        }
      }
    }
  }
}
</style>