<!--阈值管理-->
<template>
  <div class="threshold-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-icon><Setting /></el-icon>
        <span class="title">传感器阈值批量设置</span>
        <div class="stats-badge">
          <span class="stat-item"><i class="dot"></i>传感器总数 {{ totalSensors }}</span>
          <span class="stat-item"><i class="dot"></i>已配置 {{ configuredCount }}</span>
          <span class="stat-item"><i class="dot"></i>待配置 {{ unconfiguredCount }}</span>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" :icon="Plus" @click="showBatchDialog">批量设置</el-button>
        <el-button :icon="Refresh" @click="refreshData">刷新</el-button>
        <el-button :icon="Download" @click="exportConfig">导出配置</el-button>
      </div>
    </div>

    <!-- 分类查询栏 -->
    <div class="query-bar">
      <el-select v-model="queryParams.deviceType" placeholder="设备类型" clearable style="width: 140px">
        <el-option label="智能井盖" value="smart" />
        <el-option label="水位计" value="water" />
        <el-option label="气体监测仪" value="gas" />
        <el-option label="压力监测仪" value="pressure" />
        <el-option label="流量计" value="flow" />
      </el-select>
      <el-select v-model="queryParams.paramType" placeholder="监测参数" clearable style="width: 140px">
        <el-option label="甲烷浓度" value="methane" />
        <el-option label="水位深度" value="waterLevel" />
        <el-option label="倾斜角度" value="tilt" />
        <el-option label="管道压力" value="pressure" />
        <el-option label="瞬时流量" value="flow" />
      </el-select>
      <el-select v-model="queryParams.hasThreshold" placeholder="阈值状态" clearable style="width: 120px">
        <el-option label="已配置" value="configured" />
        <el-option label="未配置" value="unconfigured" />
      </el-select>
      <el-input
          v-model="queryParams.keyword"
          placeholder="搜索点位名称/编号"
          clearable
          :prefix-icon="Search"
          style="width: 200px"
      />
      <el-button type="primary" :icon="Search" @click="searchPoints">查询</el-button>
      <el-button @click="resetQuery">重置</el-button>
    </div>

    <!-- 传感器列表 -->
    <div class="sensor-table-container">
      <div class="table-header">
        <span>传感器点位列表</span>
        <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
      </div>
      <el-table
          :data="paginatedSensors"
          stripe
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
          ref="tableRef"
      >
        <el-table-column type="selection" width="45" align="center" />
        <el-table-column prop="code" label="点位编号" width="120" sortable />
        <el-table-column prop="name" label="点位名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="deviceTypeName" label="设备类型" width="110" />
        <el-table-column prop="paramTypeName" label="监测参数" width="110" />
        <el-table-column label="阈值配置" width="200">
          <template #default="{ row }">
            <div v-if="row.thresholdConfig" class="threshold-display">
              <span>预警: {{ row.thresholdConfig.warningThreshold }} {{ row.unit }}</span>
              <span>告警: {{ row.thresholdConfig.criticalThreshold }} {{ row.unit }}</span>
              <span v-if="row.thresholdConfig.timeRange" class="time-range">({{ row.thresholdConfig.timeRange }})</span>
            </div>
            <span v-else class="no-config">未配置</span>
          </template>
        </el-table-column>
        <el-table-column label="分时阈值" width="150" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.thresholdConfig?.timeRange" type="success" size="small">已启用</el-tag>
            <el-tag v-else type="info" size="small">未启用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="editSingleThreshold(row)">编辑</el-button>
            <el-button link type="info" size="small" @click="viewDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next"
            :total="filteredSensors.length"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
        />
      </div>
    </div>

    <!-- 批量设置对话框 -->
    <el-dialog v-model="batchDialogVisible" title="批量设置阈值" width="600px">
      <el-form :model="batchForm" label-width="110px">
        <el-form-item label="选择传感器">
          <div class="selected-sensors">
            <el-tag v-for="sensor in selectedSensors" :key="sensor.id" closable @close="removeSelected(sensor)" style="margin: 4px">
              {{ sensor.name }}
            </el-tag>
          </div>
          <div class="selected-count">已选择 {{ selectedSensors.length }} 个传感器</div>
        </el-form-item>
        <el-divider />
        <el-form-item label="报警阈值" required>
          <div class="threshold-inputs">
            <el-input-number v-model="batchForm.warningThreshold" :min="0" :step="1" placeholder="预警值" style="width: 140px" />
            <span class="separator">~</span>
            <el-input-number v-model="batchForm.criticalThreshold" :min="0" :step="1" placeholder="告警值" style="width: 140px" />
            <span class="unit">{{ batchForm.unit }}</span>
          </div>
        </el-form-item>
        <el-form-item label="分时阈值设置">
          <el-switch v-model="batchForm.enableTimeRange" active-text="启用" inactive-text="停用" />
        </el-form-item>
        <el-form-item v-if="batchForm.enableTimeRange" label="分时时段">
          <div class="time-range-config">
            <div class="time-item">
              <span class="time-label">工作日夜间 (22:00-06:00):</span>
              <el-input-number v-model="batchForm.nightThreshold" :min="0" :step="1" style="width: 100px" />
              <span class="unit">{{ batchForm.unit }}</span>
            </div>
            <div class="time-item">
              <span class="time-label">工作日白天 (06:00-22:00):</span>
              <el-input-number v-model="batchForm.dayThreshold" :min="0" :step="1" style="width: 100px" />
              <span class="unit">{{ batchForm.unit }}</span>
            </div>
            <div class="time-item">
              <span class="time-label">节假日/周末:</span>
              <el-input-number v-model="batchForm.holidayThreshold" :min="0" :step="1" style="width: 100px" />
              <span class="unit">{{ batchForm.unit }}</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="batchForm.remark" placeholder="可选，填写批量设置说明" rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBatchConfig">确认设置</el-button>
      </template>
    </el-dialog>

    <!-- 单点编辑对话框 -->
    <el-dialog v-model="singleDialogVisible" :title="`编辑阈值 - ${currentSensor?.name}`" width="550px">
      <el-form :model="singleForm" label-width="110px">
        <el-form-item label="点位编号">{{ currentSensor?.code }}</el-form-item>
        <el-form-item label="设备类型">{{ currentSensor?.deviceTypeName }}</el-form-item>
        <el-form-item label="监测参数">{{ currentSensor?.paramTypeName }}</el-form-item>
        <el-form-item label="报警阈值" required>
          <div class="threshold-inputs">
            <el-input-number v-model="singleForm.warningThreshold" :min="0" :step="1" placeholder="预警值" style="width: 140px" />
            <span class="separator">~</span>
            <el-input-number v-model="singleForm.criticalThreshold" :min="0" :step="1" placeholder="告警值" style="width: 140px" />
            <span class="unit">{{ currentSensor?.unit }}</span>
          </div>
        </el-form-item>
        <el-form-item label="分时阈值">
          <el-switch v-model="singleForm.enableTimeRange" active-text="启用" inactive-text="停用" />
        </el-form-item>
        <el-form-item v-if="singleForm.enableTimeRange" label="分时时段">
          <div class="time-range-config">
            <div class="time-item">夜间 (22:00-06:00): <el-input-number v-model="singleForm.nightThreshold" :min="0" style="width: 100px" /> {{ currentSensor?.unit }}</div>
            <div class="time-item">白天 (06:00-22:00): <el-input-number v-model="singleForm.dayThreshold" :min="0" style="width: 100px" /> {{ currentSensor?.unit }}</div>
            <div class="time-item">节假日: <el-input-number v-model="singleForm.holidayThreshold" :min="0" style="width: 100px" /> {{ currentSensor?.unit }}</div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="singleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSingleConfig">保存</el-button>
      </template>
    </el-dialog>

    <!-- 阈值详情抽屉 -->
    <el-drawer v-model="detailDrawerVisible" :title="`阈值详情 - ${currentSensor?.name}`" size="450px" direction="rtl">
      <div v-if="currentSensor" class="threshold-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="点位编号">{{ currentSensor.code }}</el-descriptions-item>
          <el-descriptions-item label="点位名称">{{ currentSensor.name }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{ currentSensor.deviceTypeName }}</el-descriptions-item>
          <el-descriptions-item label="监测参数">{{ currentSensor.paramTypeName }}</el-descriptions-item>
          <el-descriptions-item label="单位">{{ currentSensor.unit }}</el-descriptions-item>
          <el-descriptions-item label="预警阈值" v-if="currentSensor.thresholdConfig">
            {{ currentSensor.thresholdConfig.warningThreshold }} {{ currentSensor.unit }}
          </el-descriptions-item>
          <el-descriptions-item label="告警阈值" v-if="currentSensor.thresholdConfig">
            {{ currentSensor.thresholdConfig.criticalThreshold }} {{ currentSensor.unit }}
          </el-descriptions-item>
          <el-descriptions-item label="分时阈值" v-if="currentSensor.thresholdConfig?.timeRange">
            {{ currentSensor.thresholdConfig.timeRange }}
          </el-descriptions-item>
          <el-descriptions-item label="配置时间">{{ currentSensor.thresholdConfig?.configTime || '—' }}</el-descriptions-item>
          <el-descriptions-item label="配置人员">{{ currentSensor.thresholdConfig?.configUser || '—' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Setting, Plus, Refresh, Download, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 模拟传感器数据
const sensors = ref([
  { id: 1, code: 'FM-001', name: '世纪大道流量计', deviceType: 'flow', deviceTypeName: '流量计', paramType: 'flow', paramTypeName: '瞬时流量', unit: 'm³/h', thresholdConfig: { warningThreshold: 1000, criticalThreshold: 1200, configTime: '2025-03-15', configUser: '系统管理员' } },
  { id: 2, code: 'FM-002', name: '张杨路流量计', deviceType: 'flow', deviceTypeName: '流量计', paramType: 'flow', paramTypeName: '瞬时流量', unit: 'm³/h', thresholdConfig: { warningThreshold: 900, criticalThreshold: 1100, configTime: '2025-03-20', configUser: '系统管理员' } },
  { id: 3, code: 'CH4-001', name: '人民广场气体监测仪', deviceType: 'gas', deviceTypeName: '气体监测仪', paramType: 'methane', paramTypeName: '甲烷浓度', unit: 'ppm', thresholdConfig: { warningThreshold: 10, criticalThreshold: 20, configTime: '2025-03-10', configUser: '系统管理员' } },
  { id: 4, code: 'CH4-002', name: '世纪大道气体监测仪', deviceType: 'gas', deviceTypeName: '气体监测仪', paramType: 'methane', paramTypeName: '甲烷浓度', unit: 'ppm', thresholdConfig: null },
  { id: 5, code: 'WL-001', name: '张杨路水位计', deviceType: 'water', deviceTypeName: '水位计', paramType: 'waterLevel', paramTypeName: '水位深度', unit: 'cm', thresholdConfig: { warningThreshold: 30, criticalThreshold: 40, configTime: '2025-03-18', configUser: '系统管理员' } },
  { id: 6, code: 'WL-002', name: '龙阳路水位计', deviceType: 'water', deviceTypeName: '水位计', paramType: 'waterLevel', paramTypeName: '水位深度', unit: 'cm', thresholdConfig: null },
  { id: 7, code: 'PR-001', name: '东方路压力监测仪', deviceType: 'pressure', deviceTypeName: '压力监测仪', paramType: 'pressure', paramTypeName: '管道压力', unit: 'kPa', thresholdConfig: { warningThreshold: 320, criticalThreshold: 300, configTime: '2025-03-12', configUser: '系统管理员' } },
  { id: 8, code: 'TL-001', name: '人民路井盖', deviceType: 'smart', deviceTypeName: '智能井盖', paramType: 'tilt', paramTypeName: '倾斜角度', unit: '°', thresholdConfig: null },
])

// 统计数据
const totalSensors = computed(() => sensors.value.length)
const configuredCount = computed(() => sensors.value.filter(s => s.thresholdConfig).length)
const unconfiguredCount = computed(() => totalSensors.value - configuredCount.value)

// 查询参数
const queryParams = ref({
  deviceType: '',
  paramType: '',
  hasThreshold: '',
  keyword: ''
})
const currentPage = ref(1)
const pageSize = ref(10)
const selectedRows = ref([])
const selectAll = ref(false)
const tableRef = ref(null)

// 弹窗状态
const batchDialogVisible = ref(false)
const singleDialogVisible = ref(false)
const detailDrawerVisible = ref(false)
const selectedSensors = ref([])
const currentSensor = ref(null)

// 批量表单
const batchForm = ref({
  warningThreshold: 0,
  criticalThreshold: 0,
  unit: '',
  enableTimeRange: false,
  nightThreshold: 0,
  dayThreshold: 0,
  holidayThreshold: 0,
  remark: ''
})

// 单点表单
const singleForm = ref({
  warningThreshold: 0,
  criticalThreshold: 0,
  enableTimeRange: false,
  nightThreshold: 0,
  dayThreshold: 0,
  holidayThreshold: 0
})

// 过滤传感器
const filteredSensors = computed(() => {
  let list = sensors.value
  if (queryParams.value.deviceType) {
    list = list.filter(s => s.deviceType === queryParams.value.deviceType)
  }
  if (queryParams.value.paramType) {
    list = list.filter(s => s.paramType === queryParams.value.paramType)
  }
  if (queryParams.value.hasThreshold === 'configured') {
    list = list.filter(s => s.thresholdConfig)
  } else if (queryParams.value.hasThreshold === 'unconfigured') {
    list = list.filter(s => !s.thresholdConfig)
  }
  if (queryParams.value.keyword) {
    const kw = queryParams.value.keyword.toLowerCase()
    list = list.filter(s => s.name.toLowerCase().includes(kw) || s.code.toLowerCase().includes(kw))
  }
  return list
})

const paginatedSensors = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredSensors.value.slice(start, start + pageSize.value)
})

// 方法
const searchPoints = () => { currentPage.value = 1 }
const resetQuery = () => {
  queryParams.value = { deviceType: '', paramType: '', hasThreshold: '', keyword: '' }
  currentPage.value = 1
}
const refreshData = () => { ElMessage.success('数据已刷新') }
const exportConfig = () => { ElMessage.success('导出阈值配置（演示）') }

const handleSelectionChange = (val) => {
  selectedRows.value = val
  selectAll.value = val.length === paginatedSensors.value.length && paginatedSensors.value.length > 0
}
const handleSelectAll = (val) => {
  if (val) {
    paginatedSensors.value.forEach(row => tableRef.value?.toggleRowSelection(row, true))
  } else {
    tableRef.value?.clearSelection()
  }
}

const showBatchDialog = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要批量设置的传感器')
    return
  }
  selectedSensors.value = [...selectedRows.value]
  // 获取公共单位（简化处理，取第一个的单位）
  if (selectedSensors.value.length > 0) {
    batchForm.value.unit = selectedSensors.value[0].unit
  }
  batchForm.value.warningThreshold = 0
  batchForm.value.criticalThreshold = 0
  batchForm.value.enableTimeRange = false
  batchForm.value.nightThreshold = 0
  batchForm.value.dayThreshold = 0
  batchForm.value.holidayThreshold = 0
  batchForm.value.remark = ''
  batchDialogVisible.value = true
}

const removeSelected = (sensor) => {
  const index = selectedSensors.value.findIndex(s => s.id === sensor.id)
  if (index !== -1) selectedSensors.value.splice(index, 1)
  // 同时从表格选择中移除
  tableRef.value?.toggleRowSelection(sensor, false)
  selectedRows.value = selectedRows.value.filter(r => r.id !== sensor.id)
}

const submitBatchConfig = () => {
  if (batchForm.value.warningThreshold <= 0 || batchForm.value.criticalThreshold <= 0) {
    ElMessage.warning('请填写完整的阈值')
    return
  }
  const configTime = new Date().toLocaleString()
  let timeRangeDesc = ''
  if (batchForm.value.enableTimeRange) {
    timeRangeDesc = `分时: 夜间${batchForm.value.nightThreshold} | 白天${batchForm.value.dayThreshold} | 节假日${batchForm.value.holidayThreshold}`
  }
  selectedSensors.value.forEach(sensor => {
    sensor.thresholdConfig = {
      warningThreshold: batchForm.value.warningThreshold,
      criticalThreshold: batchForm.value.criticalThreshold,
      configTime,
      configUser: '当前用户',
      timeRange: timeRangeDesc || null
    }
  })
  ElMessage.success(`成功设置 ${selectedSensors.value.length} 个传感器的阈值`)
  batchDialogVisible.value = false
  selectedRows.value = []
  selectAll.value = false
  tableRef.value?.clearSelection()
}

const editSingleThreshold = (row) => {
  currentSensor.value = row
  if (row.thresholdConfig) {
    singleForm.value.warningThreshold = row.thresholdConfig.warningThreshold
    singleForm.value.criticalThreshold = row.thresholdConfig.criticalThreshold
    singleForm.value.enableTimeRange = !!row.thresholdConfig.timeRange
  } else {
    singleForm.value.warningThreshold = 0
    singleForm.value.criticalThreshold = 0
    singleForm.value.enableTimeRange = false
    singleForm.value.nightThreshold = 0
    singleForm.value.dayThreshold = 0
    singleForm.value.holidayThreshold = 0
  }
  singleDialogVisible.value = true
}

const submitSingleConfig = () => {
  if (singleForm.value.warningThreshold <= 0 || singleForm.value.criticalThreshold <= 0) {
    ElMessage.warning('请填写完整的阈值')
    return
  }
  let timeRangeDesc = ''
  if (singleForm.value.enableTimeRange) {
    timeRangeDesc = `分时: 夜间${singleForm.value.nightThreshold} | 白天${singleForm.value.dayThreshold} | 节假日${singleForm.value.holidayThreshold}`
  }
  currentSensor.value.thresholdConfig = {
    warningThreshold: singleForm.value.warningThreshold,
    criticalThreshold: singleForm.value.criticalThreshold,
    configTime: new Date().toLocaleString(),
    configUser: '当前用户',
    timeRange: timeRangeDesc || null
  }
  ElMessage.success(`阈值配置已保存`)
  singleDialogVisible.value = false
}

const viewDetail = (row) => {
  currentSensor.value = row
  detailDrawerVisible.value = true
}
</script>

<style scoped>
.threshold-management {
  background: #f0f2f6;
  min-height: 100vh;
  padding: 20px;
}
.page-header {
  background: white;
  border-radius: 16px;
  padding: 16px 24px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-left { display: flex; align-items: center; gap: 20px; }
.header-left .title { font-size: 1.3rem; font-weight: 600; }
.stats-badge { display: flex; gap: 20px; }
.stat-item { font-size: 13px; display: flex; align-items: center; gap: 6px; }
.stat-item .dot { width: 8px; height: 8px; border-radius: 50%; background: #909399; }
.header-right { display: flex; gap: 12px; }

.query-bar {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  align-items: center;
}

.sensor-table-container {
  background: white;
  border-radius: 16px;
  padding: 16px;
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-weight: 600;
}
.threshold-display { display: flex; flex-direction: column; gap: 2px; font-size: 12px; }
.threshold-display .time-range { color: #e6a23c; }
.no-config { color: #c0c4cc; }
.pagination-wrapper { margin-top: 16px; display: flex; justify-content: flex-end; }

.selected-sensors { min-height: 50px; border: 1px dashed #ddd; padding: 8px; border-radius: 8px; margin-bottom: 8px; }
.selected-count { font-size: 12px; color: #909399; }

.threshold-inputs { display: flex; align-items: center; gap: 8px; }
.separator { color: #909399; }
.unit { margin-left: 4px; color: #606266; }

.time-range-config { display: flex; flex-direction: column; gap: 12px; width: 100%; }
.time-item { display: flex; align-items: center; gap: 12px; }
.time-label { width: 160px; font-size: 13px; }

.threshold-detail { padding: 8px; }
</style>