<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Connection, SwitchButton } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/userStore'
import { useIotMonitoringStore } from '../stores/iotMonitoringStore'
import { formatDateTime } from '../utils/dateTimeFormatter'
import SidebarMenu from '../components/SidebarMenu.vue'
import BreadcrumbNav from '../components/BreadcrumbNav.vue'
import HudPageHero from '../components/shell/HudPageHero.vue'

const router = useRouter()
const { userInfo, getUserInfo } = useUserStore()
const iot = useIotMonitoringStore()

const tableData = ref([])
const searchForm = ref({ keyword: '', status: '', sensor_type: '' })
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const defaultForm = () => ({
  sensor_id: null,
  sensor_code: '',
  name: '',
  bridge_section: '',
  sensor_type: 'strain',
  status: 'offline',
  install_location: '',
  sampling_hz: 50,
  threshold_max: 100,
  threshold_min: 0,
  firmware_version: 'v1.0.0',
  remark: '',
})

const form = ref(defaultForm())

const formRules = {
  sensor_code: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  bridge_section: [{ required: true, message: '请输入桥区', trigger: 'blur' }],
  sensor_type: [{ required: true, message: '请选择类型', trigger: 'change' }],
}

const statusLabel = { online: '在线', offline: '离线', maintenance: '维护中' }
const statusType = { online: 'success', offline: 'info', maintenance: 'warning' }

const refreshList = () => {
  tableData.value = iot.listSensors(searchForm.value)
}

const resetSearch = () => {
  searchForm.value = { keyword: '', status: '', sensor_type: '' }
  refreshList()
}

const openCreate = () => {
  isEdit.value = false
  form.value = defaultForm()
  dialogVisible.value = true
}

const openEdit = (row) => {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

const submitForm = async () => {
  await formRef.value?.validate()
  const { ok, message } = iot.upsertSensor(form.value)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success(isEdit.value ? '传感器已更新' : '传感器已添加')
  dialogVisible.value = false
  refreshList()
}

const handleDelete = async (row) => {
  await ElMessageBox.confirm(`确定删除传感器「${row.name}」？`, '删除确认', { type: 'warning' })
  const { ok, message } = iot.deleteSensor(row.sensor_id)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success('已删除')
  refreshList()
}

const handleToggle = (row) => {
  const { ok, message } = iot.toggleSensorStatus(row.sensor_id)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success('状态已切换')
  refreshList()
}

const handleHeartbeat = (row) => {
  const { ok, message } = iot.simulateHeartbeat(row.sensor_id)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success('心跳已上报')
  refreshList()
}

const fmtTime = (row, col) => formatDateTime(row[col.property])

const stats = computed(() => ({
  total: iot.sensors.value.length,
  online: iot.onlineSensorCount.value,
  openAlerts: iot.openAlertCount.value,
}))

onMounted(() => {
  getUserInfo().then(() => {
    if (!userInfo.value) router.push('/login')
    else refreshList()
  })
})
</script>

<template>
  <div class="iot-page shell-layout-root">
    <div class="main-container">
      <div class="sidebar"><SidebarMenu /></div>
      <div class="content-area">
        <BreadcrumbNav />
        <HudPageHero title="传感器管理" description="登记桥梁监测传感器，配置阈值与在线状态，为采集与预警提供设备基础。" />

        <el-row :gutter="12" class="stat-row">
          <el-col :span="8">
            <el-card shadow="never" class="stat-card">
              <div class="stat-num">{{ stats.total }}</div>
              <div class="stat-label">传感器总数</div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="never" class="stat-card">
              <div class="stat-num stat-success">{{ stats.online }}</div>
              <div class="stat-label">在线设备</div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="never" class="stat-card">
              <div class="stat-num stat-warn">{{ stats.openAlerts }}</div>
              <div class="stat-label">待处理预警</div>
            </el-card>
          </el-col>
        </el-row>

        <el-card class="iot-card">
          <template #header>
            <div class="card-header">
              <h2>传感器列表</h2>
              <div>
                <el-button type="primary" @click="openCreate"><el-icon><Plus /></el-icon> 新增传感器</el-button>
                <el-button @click="refreshList"><el-icon><Refresh /></el-icon> 刷新</el-button>
              </div>
            </div>
          </template>

          <el-form :model="searchForm" inline class="search-form">
            <el-form-item label="关键词">
              <el-input v-model="searchForm.keyword" placeholder="编号/名称/桥区" clearable style="width: 220px" />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="全部" clearable style="width: 120px">
                <el-option label="在线" value="online" />
                <el-option label="离线" value="offline" />
                <el-option label="维护中" value="maintenance" />
              </el-select>
            </el-form-item>
            <el-form-item label="类型">
              <el-select v-model="searchForm.sensor_type" placeholder="全部" clearable style="width: 140px">
                <el-option v-for="t in iot.SENSOR_TYPES" :key="t.value" :label="t.label" :value="t.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="refreshList">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="sensor_id" label="ID" width="60" />
            <el-table-column prop="sensor_code" label="设备编号" width="120" show-overflow-tooltip />
            <el-table-column prop="name" label="名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="bridge_section" label="桥区" width="120" show-overflow-tooltip />
            <el-table-column label="类型" width="100">
              <template #default="{ row }">{{ iot.getSensorTypeLabel(row.sensor_type) }}</template>
            </el-table-column>
            <el-table-column label="状态" width="90">
              <template #default="{ row }">
                <el-tag :type="statusType[row.status]" size="small">{{ statusLabel[row.status] }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sampling_hz" label="采样(Hz)" width="95" />
            <el-table-column label="阈值" width="120">
              <template #default="{ row }">{{ row.threshold_min }} ~ {{ row.threshold_max }}</template>
            </el-table-column>
            <el-table-column prop="last_heartbeat" label="最近心跳" width="170" :formatter="fmtTime" />
            <el-table-column label="操作" width="280" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="openEdit(row)">编辑</el-button>
                <el-button link type="primary" @click="handleHeartbeat(row)">
                  <el-icon><Connection /></el-icon> 心跳
                </el-button>
                <el-button link type="warning" @click="handleToggle(row)">
                  <el-icon><SwitchButton /></el-icon> 切换状态
                </el-button>
                <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑传感器' : '新增传感器'" width="520px" @closed="form = defaultForm()">
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="设备编号" prop="sensor_code">
          <el-input v-model="form.sensor_code" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="名称" prop="name"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="桥区" prop="bridge_section"><el-input v-model="form.bridge_section" /></el-form-item>
        <el-form-item label="类型" prop="sensor_type">
          <el-select v-model="form.sensor_type" style="width: 100%">
            <el-option v-for="t in iot.SENSOR_TYPES" :key="t.value" :label="t.label" :value="t.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="安装位置"><el-input v-model="form.install_location" /></el-form-item>
        <el-form-item label="采样频率">
          <el-input-number v-model="form.sampling_hz" :min="1" :max="1000" />
        </el-form-item>
        <el-form-item label="阈值下限"><el-input-number v-model="form.threshold_min" /></el-form-item>
        <el-form-item label="阈值上限"><el-input-number v-model="form.threshold_max" /></el-form-item>
        <el-form-item label="固件版本"><el-input v-model="form.firmware_version" /></el-form-item>
        <el-form-item label="备注"><el-input v-model="form.remark" type="textarea" :rows="2" /></el-form-item>
        <el-form-item v-if="!isEdit" label="初始状态">
          <el-radio-group v-model="form.status">
            <el-radio label="offline">离线</el-radio>
            <el-radio label="online">在线</el-radio>
            <el-radio label="maintenance">维护中</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
@import '../styles/iot-page.css';
</style>
