<template>
  <div class="app-container">
    <!-- 顶部统计卡片区 -->
    <div class="stat-cards">
      <el-card class="stat-card stat-blue" shadow="hover">
        <div class="stat-card-inner">
          <div class="stat-icon"><el-icon :size="36">
              <Monitor />
            </el-icon></div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.total }}</div>
            <div class="stat-label">设备总数</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card stat-green" shadow="hover">
        <div class="stat-card-inner">
          <div class="stat-icon"><el-icon :size="36">
              <CircleCheck />
            </el-icon></div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.online }}</div>
            <div class="stat-label">在线设备</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card stat-gray" shadow="hover">
        <div class="stat-card-inner">
          <div class="stat-icon"><el-icon :size="36">
              <SwitchButton />
            </el-icon></div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.offline }}</div>
            <div class="stat-label">离线设备</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card stat-red" shadow="hover">
        <div class="stat-card-inner">
          <div class="stat-icon"><el-icon :size="36">
              <Warning />
            </el-icon></div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.alarm }}</div>
            <div class="stat-label">报警设备</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card stat-cyan" shadow="hover">
        <div class="stat-card-inner">
          <div class="stat-icon"><el-icon :size="36">
              <DataLine />
            </el-icon></div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.onlineRate }}%</div>
            <div class="stat-label">在线率</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 搜索/筛选区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" class="search-form">
      <el-form-item label="设备名称">
        <el-input v-model="queryParams.equipmentName" placeholder="请输入" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="设备状态">
        <el-select v-model="queryParams.currentStatus" placeholder="请选择" clearable style="width: 200px">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区 -->
    <div class="toolbar">
      <el-button type="warning" @click="handleExport">导出</el-button>
      <el-button type="primary" :disabled="selectedRows.length === 0" @click="handleBatchRepair">维修派单</el-button>
      <!-- <el-button type="danger" :disabled="selectedRows.length === 0" @click="handleBatchWarning">发布预警</el-button> -->
    </div>

    <!-- 实时数据表格 -->
    <el-table :data="tableData" border style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备名称" prop="equipmentName" min-width="140" />
      <el-table-column label="设备编号" prop="equipmentCode" min-width="130" />
      <el-table-column label="设备类型" prop="equipmentTypeName" min-width="100" align="center">
        <template #default="{ row }">
          <span>{{ row.equipmentTypeName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="安装位置" prop="equipmentLocation" min-width="160" />
      <el-table-column label="设备状态" prop="currentStatus" min-width="90" align="center">
        <template #default="{ row }">
          <el-tag :type="statusTagType(row.currentStatus)">{{ statusText(row.currentStatus) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="报警状态" prop="alarmStatus" min-width="90" align="center">
        <template #default="{ row }">
          <el-tag :type="row.alarmStatus === 1 ? 'danger' : 'success'">{{ row.alarmStatus === 1 ? '报警' : '正常' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="在线状态" prop="onlineStatus" min-width="90" align="center">
        <template #default="{ row }">
          <el-tag :type="row.onlineStatus === 1 ? 'success' : 'info'">{{ row.onlineStatus === 1 ? '在线' : '离线' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="安装时间" prop="installTime" min-width="120" />
      <el-table-column label="最近维护时间" prop="lastMaintainDate" min-width="130" />
      <el-table-column label="下次维护日期" prop="nextMaintainDate" min-width="130" />
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleView(row)">详情</el-button>
          <el-button link type="primary" @click="handleLocate(row)">定位</el-button>
          <el-button link type="warning" @click="handleRepair(row)">派单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleQuery" @current-change="handlePageChange" />

    <!-- 查看详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="设备实时详情" width="750px">
      <div class="detail-info">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">设备名称：</span>
              <span class="info-value">{{ currentRow.equipmentName }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">设备编号：</span>
              <span class="info-value">{{ currentRow.equipmentCode }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">设备类型：</span>
              <span class="info-value">{{ currentRow.equipmentTypeName || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">安装位置：</span>
              <span class="info-value">{{ currentRow.equipmentLocation }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">设备状态：</span>
              <span class="info-value">
                <el-tag :type="statusTagType(currentRow.currentStatus)">{{ statusText(currentRow.currentStatus)
                }}</el-tag>
              </span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">报警状态：</span>
              <span class="info-value">
                <el-tag :type="currentRow.alarmStatus === 1 ? 'danger' : 'success'">{{ currentRow.alarmStatus === 1 ? '报警'
                  : '正常' }}</el-tag>
              </span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">在线状态：</span>
              <span class="info-value">
                <el-tag :type="currentRow.onlineStatus === 1 ? 'success' : 'info'">{{ currentRow.onlineStatus === 1 ? '在线'
                  : '离线' }}</el-tag>
              </span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">安装时间：</span>
              <span class="info-value">{{ currentRow.installTime }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">最近维护时间：</span>
              <span class="info-value">{{ currentRow.lastMaintainDate }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">下次维护日期：</span>
              <span class="info-value">{{ currentRow.nextMaintainDate }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">维护人员：</span>
              <span class="info-value">{{ currentRow.maintainer }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">联系方式：</span>
              <span class="info-value">{{ currentRow.maintainerPhone }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">权属单位：</span>
              <span class="info-value">{{ currentRow.ownershipUnit }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="info-item">
              <span class="info-label">备注：</span>
              <span class="info-value">{{ currentRow.remark }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 定位弹窗 -->
    <el-dialog v-model="locateDialogVisible" title="设备定位" width="700px" @opened="onLocateDialogOpened"
      :before-close="handleLocateClose">
      <div class="locate-info">
        <div class="locate-device">
          <span class="info-label">设备名称：</span>
          <span class="info-value">{{ locateRow.equipmentName }}</span>
          <span style="margin-left: 20px" class="info-label">设备编号：</span>
          <span class="info-value">{{ locateRow.equipmentCode }}</span>
        </div>
        <div id="sbyxLocationMap" class="map-container"></div>
        <div class="locate-coords">
          经度：{{ locateTempLng }} 纬度：{{ locateTempLat }}
        </div>
        <div class="locate-tip">点击地图可修改设备定位</div>
      </div>
      <template #footer>
        <el-button @click="handleLocateCancel">取 消</el-button>
        <el-button type="primary" @click="handleLocateConfirm">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 维修派单弹窗 -->
    <el-dialog v-model="repairDialogVisible" title="维修派单" width="600px">
      <el-form ref="repairFormRef" :model="repairForm" :rules="repairRules" label-width="100px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="repairForm.name" disabled />
        </el-form-item>
        <el-form-item label="故障描述" prop="faultDesc">
          <el-input v-model="repairForm.faultDesc" type="textarea" :rows="3" placeholder="请输入故障描述" />
        </el-form-item>
        <el-form-item label="维修人员" prop="repairPerson">
          <el-input v-model="repairForm.repairPerson" placeholder="请输入维修人员" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="repairForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="紧急程度" prop="urgency">
          <el-select v-model="repairForm.urgency" placeholder="请选择紧急程度" style="width: 100%">
            <el-option v-for="item in urgencyOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="repairForm.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="repairDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRepairSubmit">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 发布预警弹窗 -->
    <el-dialog v-model="warningDialogVisible" title="发布预警" width="600px">
      <el-form ref="warningFormRef" :model="warningForm" :rules="warningRules" label-width="100px">
        <el-form-item label="预警设备" prop="name">
          <el-input v-model="warningForm.name" disabled />
        </el-form-item>
        <el-form-item label="预警级别" prop="level">
          <el-select v-model="warningForm.level" placeholder="请选择预警级别" style="width: 100%">
            <el-option v-for="item in warningLevelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前值" prop="currentValue">
          <el-input v-model="warningForm.currentValue" placeholder="请输入当前值" />
        </el-form-item>
        <el-form-item label="阈值" prop="thresholdValue">
          <el-input v-model="warningForm.thresholdValue" placeholder="请输入阈值" />
        </el-form-item>
        <el-form-item label="预警时间" prop="warningTime">
          <el-date-picker v-model="warningForm.warningTime" type="datetime" placeholder="请选择预警时间"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="预警内容" prop="content">
          <el-input v-model="warningForm.content" type="textarea" :rows="3" placeholder="请输入预警内容" />
        </el-form-item>
        <el-form-item label="发布范围" prop="scope">
          <el-select v-model="warningForm.scope" placeholder="请选择发布范围" style="width: 100%">
            <el-option v-for="item in scopeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="warningForm.scope === 3" label="选择人员" prop="userIds">
          <el-select v-model="warningForm.userIds" multiple placeholder="请选择人员" style="width: 100%">
            <el-option v-for="user in drainageUsers" :key="user.userId" :label="user.nickName" :value="user.userId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="warningDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleWarningSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Sbyx">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import locationIcon from '@/assets/images/location.png'
import { getEquipmentPage, publishWarning, addWorkOrder } from '@/api/drainage'
import { listUser, deptTreeSelect } from '@/api/system/user'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()

// 地图标记创建（用Label+img代替Marker）
function createMapMarker(map, bPoint, name) {
  const html = `<div style="text-align:center;cursor:pointer;">
    <div style="color:#fff;background:#409eff;border-radius:4px;padding:2px 6px;font-size:11px;white-space:nowrap;display:inline-block;margin-bottom:2px;">${name || ''}</div>
    <div><img src="${locationIcon}" style="width:28px;height:28px;display:block;margin:0 auto;"/></div>
  </div>`
  const label = new BMapGL.Label(html, {
    position: bPoint,
    offset: new BMapGL.Size(-30, -50)
  })
  label.setStyle({
    border: 'none',
    background: 'transparent',
    padding: '0'
  })
  map.addOverlay(label)
  return label
}

// ==================== 选项配置 ====================
const statusOptions = [
  { label: '在用', value: 1 },
  { label: '闲置', value: 2 },
  { label: '维修', value: 3 },
  { label: '报废', value: 4 },
  { label: '待入库', value: 5 }
]

const urgencyOptions = [
  { label: '一般', value: '1' },
  { label: '紧急', value: '2' },
  { label: '非常紧急', value: '3' }
]

const warningLevelOptions = [
  { label: '一级（红色）', value: '1' },
  { label: '二级（橙色）', value: '2' },
  { label: '三级（黄色）', value: '3' },
  { label: '四级（蓝色）', value: '4' }
]

const scopeOptions = [
  { label: '相关部门', value: 2 },
  { label: '指定人员', value: 3 }
]

function statusText(val) {
  const map = { 1: '在用', 2: '闲置', 3: '维修', 4: '报废', 5: '待入库' }
  return map[val] || '-'
}

function statusTagType(val) {
  const map = { 1: 'success', 2: 'info', 3: 'warning', 4: 'danger', 5: '' }
  return map[val] || 'info'
}

// ==================== 搜索参数 ====================
const queryParams = ref({
  equipmentName: '',
  currentStatus: '',
  equipmentTypeId: 'drainage',
  pageNum: 1,
  pageSize: 10
})

// ==================== 表格数据 ======================================
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// ==================== 统计数据 ====================
const stats = computed(() => {
  const list = tableData.value
  const t = total.value
  const online = list.filter(d => d.onlineStatus === 1).length
  const offline = list.filter(d => d.onlineStatus === 0).length
  const alarm = list.filter(d => d.alarmStatus === 1).length
  const onlineRate = t > 0 ? ((online / t) * 100).toFixed(1) : 0
  return { total: t, online, offline, alarm, onlineRate }
})

// ==================== 多选 ====================
const selectedRows = ref([])
function handleSelectionChange(selection) {
  selectedRows.value = selection
}

// 加载分页数据
async function loadData() {
  loading.value = true
  try {
    const { pageNum, pageSize, ...rest } = queryParams.value
    const res = await getEquipmentPage(pageNum, pageSize, rest)
    const pageData = res.code !== undefined ? res.data : res
    tableData.value = pageData.records || []
    total.value = pageData.total || 0
  } catch (error) {
    console.error('加载设备列表失败', error)
    ElMessage.error('加载设备列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
function handleQuery() {
  queryParams.value.pageNum = 1
  loadData()
}

function resetQuery() {
  queryParams.value = {
    equipmentName: '',
    currentStatus: '',
    equipmentTypeId: 'drainage',
    pageNum: 1,
    pageSize: 10
  }
  loadData()
}

function handlePageChange() {
  loadData()
}

onMounted(() => {
  loadData()
})

// ==================== 导出 ====================
function handleExport() {
  ElMessage.success('导出成功（模拟）')
}

// ==================== 查看详情弹窗 ====================
const detailDialogVisible = ref(false)
const currentRow = ref({})

function handleView(row) {
  currentRow.value = { ...row }
  detailDialogVisible.value = true
}

// ==================== 定位弹窗 ====================
const locateDialogVisible = ref(false)
const locateRow = ref({})
let locateMapInstance = null
let locateCurrentLabel = null
const locateTempLng = ref('')
const locateTempLat = ref('')

function handleLocate(row) {
  locateRow.value = { ...row }
  locateTempLng.value = row.longitude || ''
  locateTempLat.value = row.latitude || ''
  locateDialogVisible.value = true
}

function onLocateDialogOpened() {
  setTimeout(() => {
    initLocateMap()
  }, 300)
}

function initLocateMap() {
  const container = document.getElementById('sbyxLocationMap')
  if (!container) return

  try {
    locateMapInstance = new BMapGL.Map('sbyxLocationMap')
    const lng = parseFloat(locateRow.value.longitude)
    const lat = parseFloat(locateRow.value.latitude)
    const centerPoint = (lng && lat)
      ? new BMapGL.Point(lng, lat)
      : new BMapGL.Point(110.393, 28.452)
    locateMapInstance.centerAndZoom(centerPoint, 15)
    locateMapInstance.enableScrollWheelZoom(true)

    // 如果有坐标，显示标记
    if (lng && lat) {
      const bPoint = new BMapGL.Point(lng, lat)
      locateCurrentLabel = createMapMarker(locateMapInstance, bPoint, locateRow.value.equipmentName)
    }

    // 点击地图修改定位
    locateMapInstance.addEventListener('click', function (e) {
      const clickLng = e.latlng.lng
      const clickLat = e.latlng.lat
      locateTempLng.value = clickLng.toFixed(6)
      locateTempLat.value = clickLat.toFixed(6)

      // 清除旧标记，添加新标记
      if (locateCurrentLabel) {
        locateMapInstance.removeOverlay(locateCurrentLabel)
      }
      const bPoint = new BMapGL.Point(clickLng, clickLat)
      locateCurrentLabel = createMapMarker(locateMapInstance, bPoint, locateRow.value.equipmentName)
    })
  } catch (e) {
    console.error('百度地图初始化失败：', e)
  }
}

function handleLocateClose(done) {
  if (locateMapInstance) {
    locateMapInstance = null
  }
  locateCurrentLabel = null
  done()
}

function handleLocateCancel() {
  if (locateMapInstance) {
    locateMapInstance = null
  }
  locateCurrentLabel = null
  locateDialogVisible.value = false
}

function handleLocateConfirm() {
  // TODO: 接入后端保存坐标接口
  if (locateMapInstance) {
    locateMapInstance = null
  }
  locateCurrentLabel = null
  locateDialogVisible.value = false
  ElMessage.success('设备定位更新成功')
}

// ==================== 维修派单弹窗 ====================
const repairDialogVisible = ref(false)
const repairFormRef = ref(null)
const repairForm = ref({
  name: '',
  faultDesc: '',
  repairPerson: '',
  phone: '',
  urgency: '',
  remark: ''
})
// 当前派单关联的设备行（支持多选批量派单）
const repairDeviceRows = ref([])
// 前端紧急程度值 -> 后端工单优先级值
// 前端 urgency: 1-一般 2-紧急 3-非常紧急
// 后端 orderLevel: 1-紧急 2-一般 3-低
const urgencyToOrderLevel = { '1': 2, '2': 1, '3': 1 }

const repairRules = {
  faultDesc: [{ required: true, message: '请输入故障描述', trigger: 'blur' }],
  repairPerson: [{ required: true, message: '请输入维修人员', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  urgency: [{ required: true, message: '请选择紧急程度', trigger: 'change' }]
}

function openRepairDialog(name) {
  repairForm.value = {
    name: name,
    faultDesc: '',
    repairPerson: '',
    phone: '',
    urgency: '',
    remark: ''
  }
  repairDialogVisible.value = true
}

function handleRepair(row) {
  repairDeviceRows.value = [row]
  openRepairDialog(row.equipmentName)
}

function handleBatchRepair() {
  const names = selectedRows.value.map(r => r.equipmentName).join('、')
  repairDeviceRows.value = [...selectedRows.value]
  openRepairDialog(names)
}

function handleRepairSubmit() {
  repairFormRef.value.validate(async valid => {
    if (!valid) return
    const rows = repairDeviceRows.value.filter(r => r.equipmentId)
    if (rows.length === 0) {
      ElMessage.warning('所选设备缺少设备ID，无法派单')
      return
    }
    const orderLevel = urgencyToOrderLevel[repairForm.value.urgency]
    // 批量派单时为每个设备分别创建工单（单个失败不影响其他设备，后端校验：同一设备仅允许一个进行中工单）
    const failList = []
    for (const row of rows) {
      try {
        await addWorkOrder({
          deviceId: String(row.equipmentId),
          orderType: 1,
          orderLevel,
          orderDesc: repairForm.value.faultDesc
        })
      } catch (error) {
        failList.push((row.equipmentName || row.equipmentCode || row.equipmentId) + '：' + (error?.message || error?.msg || '创建失败'))
      }
    }
    if (failList.length === 0) {
      ElMessage.success('维修派单成功，共 ' + rows.length + ' 个工单')
      repairDialogVisible.value = false
    } else if (failList.length === rows.length) {
      ElMessage.error('维修派单失败：' + failList[0])
    } else {
      ElMessage.warning('部分设备派单失败（' + failList.length + '/' + rows.length + '）：' + failList.join('；'))
    }
  })
}

// ==================== 发布预警弹窗 ====================
const warningDialogVisible = ref(false)
const warningFormRef = ref(null)
const warningForm = ref({
  name: '',
  level: '',
  currentValue: '',
  thresholdValue: '',
  warningTime: '',
  content: '',
  scope: '',
  userIds: []
})
// 保存当前设备行数据，用于自动填充经纬度和位置
const warningRowData = ref({})

// 排水单位部门下的用户列表
const drainageUsers = ref([])
// 排水单位部门ID（publishScope=2时需传递scopeDeptId）
const drainageDeptId = ref(null)

const warningRules = {
  level: [{ required: true, message: '请选择预警级别', trigger: 'change' }],
  currentValue: [{ required: true, message: '请输入当前值', trigger: 'blur' }],
  thresholdValue: [{ required: true, message: '请输入阈值', trigger: 'blur' }],
  warningTime: [{ required: true, message: '请选择预警时间', trigger: 'change' }],
  content: [{ required: true, message: '请输入预警内容', trigger: 'blur' }],
  scope: [{ required: true, message: '请选择发布范围', trigger: 'change' }],
  userIds: [{
    validator: (rule, value, callback) => {
      if (warningForm.value.scope === 3 && (!value || value.length === 0)) {
        callback(new Error('请选择人员'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }]
}

// 加载排水单位部门下的用户列表
async function loadDrainageUsers() {
  try {
    const treeRes = await deptTreeSelect()
    const treeData = treeRes.data || treeRes
    // 递归找到包含"排水"的部门节点
    const findDept = (nodes) => {
      for (const node of nodes) {
        if (node.label && node.label.includes('排水')) return node
        if (node.children) {
          const found = findDept(node.children)
          if (found) return found
        }
      }
      return null
    }
    const drainageDept = findDept(treeData)
    if (drainageDept) {
      drainageDeptId.value = drainageDept.id
      const userRes = await listUser({ deptId: drainageDept.id, status: '0', pageSize: 1000 })
      drainageUsers.value = (userRes.rows || userRes.data?.rows || [])
    }
  } catch (e) {
    console.error('加载排水单位人员失败', e)
  }
}

function openWarningDialog(name, row) {
  warningForm.value = {
    name: name,
    level: '',
    currentValue: '',
    thresholdValue: '',
    warningTime: '',
    content: '',
    scope: '',
    userIds: []
  }
  warningRowData.value = row || {}
  warningDialogVisible.value = true
  loadDrainageUsers()
}

function handleBatchWarning() {
  const names = selectedRows.value.map(r => r.equipmentName).join('、')
  // 取第一个选中行的坐标和位置信息用于自动填充
  openWarningDialog(names, selectedRows.value[0])
}

function handleWarningSubmit() {
  warningFormRef.value.validate(async valid => {
    if (!valid) return
    try {
      // 校验设备经纬度
      const equipLng = warningRowData.value?.longitude
      const equipLat = warningRowData.value?.latitude
      if (!equipLng || !equipLat) {
        ElMessage.warning('所选设备没有经纬度坐标，预警发布后将在GIS一张图上无法显示点位。请先在设备管理中为该设备设置定位。')
      }
      const submitData = {
        warning: {
          equipmentId: warningRowData.value?.equipmentId,
          equipmentName: warningForm.value.name,
          warningLevel: warningForm.value.level,
          currentValue: warningForm.value.currentValue,
          thresholdValue: warningForm.value.thresholdValue,
          warningTime: warningForm.value.warningTime,
          content: warningForm.value.content,
          publishScope: warningForm.value.scope,
          scopeDeptId: warningForm.value.scope === 2 ? drainageDeptId.value : null,
          longitude: equipLng,
          latitude: equipLat,
          location: warningRowData.value?.equipmentLocation
        },
        userIds: warningForm.value.scope === 3 ? warningForm.value.userIds : []
      }
      await publishWarning(submitData)
      ElMessage.success('预警发布成功')
      warningDialogVisible.value = false
    } catch (error) {
      console.error('发布预警失败', error)
      ElMessage.error('发布预警失败')
    }
  })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

/* 统计卡片 */
.stat-cards {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  min-width: 0;
}

.stat-card :deep(.el-card__body) {
  padding: 16px 20px;
}

.stat-card-inner {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.stat-blue .stat-icon {
  background: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.stat-green .stat-icon {
  background: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.stat-gray .stat-icon {
  background: rgba(144, 147, 153, 0.1);
  color: #909399;
}

.stat-red .stat-icon {
  background: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.stat-cyan .stat-icon {
  background: rgba(0, 210, 219, 0.1);
  color: #00D2DB;
}

.stat-info {
  flex: 1;
  min-width: 0;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  line-height: 1.2;
}

.stat-blue .stat-value {
  color: #409EFF;
}

.stat-green .stat-value {
  color: #67C23A;
}

.stat-gray .stat-value {
  color: #909399;
}

.stat-red .stat-value {
  color: #F56C6C;
}

.stat-cyan .stat-value {
  color: #00D2DB;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

/* 搜索表单 */
.search-form {
  margin-bottom: 16px;
}

/* 操作按钮 */
.toolbar {
  margin-bottom: 16px;
}

/* 详情弹窗 */
.detail-info {
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  line-height: 32px;
}

.info-label {
  color: #909399;
  font-size: 14px;
  white-space: nowrap;
}

.info-value {
  color: #303133;
  font-size: 14px;
}

/* 定位弹窗 */
.locate-info {
  text-align: center;
}

.locate-device {
  text-align: left;
  margin-bottom: 16px;
}

.map-container {
  width: 100%;
  height: 350px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
}

.locate-coords {
  margin-top: 12px;
  font-size: 14px;
  color: #303133;
}

.locate-tip {
  margin-top: 6px;
  font-size: 12px;
  color: #909399;
}</style>
