<template>
  <div class="app-container">
    <!-- GIS 地图展示区 -->
    <div class="map-section" style="margin-bottom: 16px;">
      <div class="map-tabs">
        <div class="map-tab" :class="{ active: mainMapTab === 'all' }" @click="switchMainMapTab('all')">全部</div>
        <div class="map-tab" :class="{ active: mainMapTab === 'pipeline' }" @click="switchMainMapTab('pipeline')">管线</div>
        <div class="map-tab" :class="{ active: mainMapTab === 'pipePoint' }" @click="switchMainMapTab('pipePoint')">管点
        </div>
        <div class="map-tab" :class="{ active: mainMapTab === 'outlet' }" @click="switchMainMapTab('outlet')">排口</div>
      </div>
      <div id="psgwglMainMap" class="map-container" style="height: 350px;"></div>
    </div>

    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" class="search-form">
      <el-form-item label="管网名称">
        <el-input v-model="queryParams.name" placeholder="请输入" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="地点">
        <el-input v-model="queryParams.area" placeholder="请输入" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="管网类型">
        <el-select v-model="queryParams.networkType" placeholder="请选择" clearable style="width: 200px">
          <el-option label="管线" value="管线" />
          <el-option label="管点" value="管点" />
          <el-option label="排口" value="排口" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">删除</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="filteredList" border style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="监测点名称" prop="name" min-width="160" />
      <el-table-column label="地点" prop="area" min-width="100" />
      <el-table-column label="管网类型" prop="networkType" min-width="100" />
      <el-table-column label="数据时间" prop="time" min-width="120" />
      <el-table-column label="标记数量" prop="pointCount" min-width="80" />
      <el-table-column label="关联设备" min-width="160">
        <template #default="{ row }">
          {{ equipmentNameMap[row.id] || '' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240" align="center">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleView(row)">查看</el-button>
          <el-button link type="primary" @click="handleEdit(row)">修改</el-button>
          <el-button link type="primary" @click="handleBind(row)">关联设备</el-button>
          <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :total="total"
      :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 16px; justify-content: flex-end;" @size-change="loadData" @current-change="loadData" />

    <!-- 查看详情对话框 -->
    <el-dialog v-model="dialogVisible" title="详情" width="700px" :before-close="handleClose" @opened="onDialogOpened">
      <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.name }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">地点：</span>
              <span class="info-value">{{ currentRow.area }}</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.networkType }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">数据时间：</span>
              <span class="info-value">{{ currentRow.time }}</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">{{ currentRowPointCount }}</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 关联设备 -->
      <div v-if="viewEquipmentNames.length" class="detail-info" style="margin-top: 12px;">
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="info-item">
              <span class="info-label">关联设备：</span>
              <span class="info-value">{{ viewEquipmentNames.join('、') }}</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 地图区域 -->
      <div class="map-section">
        <div class="map-tabs">
          <div class="map-tab active">{{ currentRow.networkType || '位置标记' }}</div>
        </div>
        <div id="psgwglViewMap" class="map-container"></div>
      </div>
    </el-dialog>

    <!-- 新增/修改对话框 -->
    <el-dialog v-model="editDialogVisible" :title="editDialogTitle" width="800px" :before-close="handleEditClose"
      @opened="onEditDialogOpened">
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="监测点名称" prop="name">
              <el-input v-model="editForm.name" placeholder="请输入监测点名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地点" prop="area">
              <el-input v-model="editForm.area" placeholder="请输入地点" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="管网类型" prop="networkType">
              <el-select v-model="editForm.networkType" placeholder="请选择管网类型" style="width:100%"
                @change="onNetworkTypeChange">
                <el-option label="管线" value="管线" />
                <el-option label="管点" value="管点" />
                <el-option label="排口" value="排口" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据时间" prop="time">
              <el-date-picker v-model="editForm.time" type="date" placeholder="请选择日期" value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标记数量">
              <el-input :model-value="editPoints.length" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 地图标点区域 -->
      <div class="map-section" style="margin-top: 16px;">
        <div class="map-tabs">
          <div class="map-tab active">{{ editForm.networkType || '位置标记' }}</div>
          <div class="map-tab-action" @click="clearEditMarkers">清除所有标记</div>
        </div>
        <div id="psgwglEditMap" class="map-container" style="height: 350px;"></div>
        <div class="marker-count">
          已标记 {{ editPoints.length }} 个{{ editForm.networkType ? editMarkerLabel : '标记' }}
        </div>
      </div>

      <template #footer>
        <el-button @click="handleEditClose">取 消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 关联设备弹框 -->
    <el-dialog v-model="bindDialogVisible" title="关联设备" width="700px" @close="closeBindDialog">
      <el-form :inline="true" :model="bindQueryParams" style="margin-bottom: 12px;">
        <el-form-item label="设备名称">
          <el-input v-model="bindQueryParams.equipmentName" placeholder="请输入设备名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleBindQuery">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="bindLoading" :data="bindTableData" border row-key="equipmentId" ref="bindTableRef">
        <el-table-column label="选择" width="55" align="center">
          <template #default="{ row }">
            <el-radio v-model="selectedEquipmentId" :label="row.equipmentId">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column label="设备名称" prop="equipmentName" min-width="120" />
        <el-table-column label="设备编号" prop="equipmentCode" min-width="120" />
        <el-table-column label="设备类型" prop="equipmentTypeName" min-width="100" />
        <el-table-column label="安装位置" prop="installLocation" min-width="120" />
      </el-table>
      <el-pagination v-model:current-page="bindPageNum" v-model:page-size="bindPageSize" :total="bindTotal"
        :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 12px; justify-content: flex-end;" @size-change="loadBindData" @current-change="loadBindData" />
      <template #footer>
        <el-button @click="closeBindDialog">取 消</el-button>
        <el-button type="primary" @click="submitBind">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Psgwgl">
import { ref, computed, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import locationIcon from '@/assets/images/location.png'
import {
  getPipeNetworkPage,
  addDrainagePipeNetwork,
  updateDrainagePipeNetwork,
  deleteDrainagePipeNetwork,
  getEquipmentPage,
  getEquipmentById,
  bindPipeNetworkEquipment
} from '@/api/drainage'

// 地图标记创建（用Label+img代替Marker）
function createMapMarker(map, bPoint, name, bgColor) {
  const color = bgColor || '#409eff'
  const html = `<div style="text-align:center;cursor:pointer;">
    <div style="color:#fff;background:${color};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
}

// 解析坐标数据（兼容JSON字符串和数组）
function parsePoints(data) {
  if (!data) return []
  if (typeof data === 'string') {
    try { return JSON.parse(data) } catch (e) { return [] }
  }
  return Array.isArray(data) ? data : []
}

// ==================== 顶部主地图 ====================
let mainMapInstance = null
const mainMapTab = ref('all')

function switchMainMapTab(tab) {
  mainMapTab.value = tab
  renderMainMapMarkers()
}

function initMainMap() {
  const container = document.getElementById('psgwglMainMap')
  if (!container) return
  try {
    mainMapInstance = new BMapGL.Map('psgwglMainMap')
    const centerPoint = new BMapGL.Point(110.393, 28.452)
    mainMapInstance.centerAndZoom(centerPoint, 12)
    mainMapInstance.enableScrollWheelZoom(true)
    renderMainMapMarkers()
  } catch (e) {
    console.error('顶部百度地图初始化失败：', e)
  }
}

function renderMainMapMarkers() {
  if (!mainMapInstance) return
  mainMapInstance.clearOverlays()

  const allPoints = []
  const tab = mainMapTab.value
  // 按 networkType 过滤：管线tab显示networkType='管线'的，管点tab显示'管点'，排口tab显示'排口'，全部显示所有
  const networkTypeMap = { pipeline: '管线', pipePoint: '管点', outlet: '排口' }
  const targetNetworkType = tab === 'all' ? null : networkTypeMap[tab]

  tableData.value.forEach(row => {
    if (targetNetworkType && row.networkType !== targetNetworkType) return
    const points = parsePoints(row.points)
    if (points.length === 0) return

    if (row.networkType === '管线') {
      // 管线模式：绘制折线 + 节点标记
      if (points.length >= 2) {
        const polylinePoints = points.map(p => new BMapGL.Point(p.lng, p.lat))
        const polyline = new BMapGL.Polyline(polylinePoints, {
          strokeColor: '#409eff',
          strokeWeight: 4,
          strokeOpacity: 0.8
        })
        mainMapInstance.addOverlay(polyline)
      }
      points.forEach(p => {
        if (p.lng && p.lat) {
          const bPoint = new BMapGL.Point(p.lng, p.lat)
          createMapMarker(mainMapInstance, bPoint, p.name || row.name)
          allPoints.push(bPoint)
        }
      })
    } else {
      // 管点/排口模式：只显示标记点
      points.forEach(p => {
        if (p.lng && p.lat) {
          const bPoint = new BMapGL.Point(p.lng, p.lat)
          createMapMarker(mainMapInstance, bPoint, p.name || row.name)
          allPoints.push(bPoint)
        }
      })
    }
  })

  if (allPoints.length > 0) {
    mainMapInstance.setViewport(allPoints)
  }
}

// ==================== 搜索参数 ====================
const queryParams = ref({
  name: '',
  area: '',
  networkType: ''
})

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

// 加载分页数据
async function loadData() {
  loading.value = true
  try {
    const res = await getPipeNetworkPage(pageNum.value, pageSize.value, queryParams.value)
    // 兼容直接返回Page对象（无code包装）和AjaxResult包装两种格式
    const pageData = res.code !== undefined ? res.data : res
    const records = pageData.records || []
    // 为每条记录计算 pointCount（从 points 字段自动统计）
    records.forEach(row => {
      const pts = parsePoints(row.points)
      row.pointCount = pts.length
    })
    tableData.value = records
    total.value = pageData.total || 0
    renderMainMapMarkers()
    resolveEquipmentNames()
  } catch (e) {
    console.error('加载排水管网数据失败', e)
  } finally {
    loading.value = false
  }
}

// 关联设备名称映射
const equipmentNameMap = ref({})

async function resolveEquipmentNames() {
  const map = {}
  for (const row of tableData.value) {
    if (row.equipmentId) {
      const ids = row.equipmentId.split(',')
      const names = []
      for (const id of ids) {
        try {
          const res = await getEquipmentById(id.trim())
          const data = res.code !== undefined ? res.data : res
          const info = data && data.equipmentInfo ? data.equipmentInfo : data
          if (info && info.equipmentName) names.push(info.equipmentName)
        } catch (e) { /* skip */ }
      }
      map[row.id] = names.join('、')
    }
  }
  equipmentNameMap.value = map
}

onMounted(() => {
  loadData()
  setTimeout(() => { initMainMap() }, 500)
})

// 多选
const selectedIds = ref([])
function handleSelectionChange(selection) {
  selectedIds.value = selection.map(item => item.id)
}

// 表格数据直接用 tableData（已是分页数据）
const filteredList = computed(() => tableData.value)

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

// ==================== 查看详情对话框 ====================
const dialogVisible = ref(false)
const currentRow = ref({})
const viewEquipmentNames = ref([])
let viewMapInstance = null

const currentRowPointCount = computed(() => {
  return parsePoints(currentRow.value.points).length
})

async function handleView(row) {
  currentRow.value = { ...row }
  dialogVisible.value = true
  viewEquipmentNames.value = []
  if (row.equipmentId) {
    const ids = row.equipmentId.split(',')
    const names = []
    for (const id of ids) {
      try {
        const res = await getEquipmentById(id.trim())
        const data = res.code !== undefined ? res.data : res
        const info = data && data.equipmentInfo ? data.equipmentInfo : data
        if (info && info.equipmentName) names.push(info.equipmentName)
      } catch (e) { /* skip */ }
    }
    viewEquipmentNames.value = names
  }
}

function handleClose() {
  dialogVisible.value = false
  if (viewMapInstance) {
    viewMapInstance = null
  }
}

function onDialogOpened() {
  setTimeout(() => {
    initViewMap()
  }, 300)
}

function initViewMap() {
  const container = document.getElementById('psgwglViewMap')
  if (!container) return

  try {
    viewMapInstance = new BMapGL.Map('psgwglViewMap')
    const centerPoint = new BMapGL.Point(110.393, 28.452)
    viewMapInstance.centerAndZoom(centerPoint, 15)
    viewMapInstance.enableScrollWheelZoom(true)
    renderViewMarkers()
  } catch (e) {
    console.error('百度地图初始化失败：', e)
  }
}

function renderViewMarkers() {
  if (!viewMapInstance) return
  viewMapInstance.clearOverlays()

  const points = parsePoints(currentRow.value.points)

  points.forEach(point => {
    const bPoint = new BMapGL.Point(point.lng, point.lat)
    createMapMarker(viewMapInstance, bPoint, point.name)
  })

  // 管线模式：绘制折线
  if (currentRow.value.networkType === '管线' && points.length >= 2) {
    const polylinePoints = points.map(p => new BMapGL.Point(p.lng, p.lat))
    const polyline = new BMapGL.Polyline(polylinePoints, {
      strokeColor: '#409eff',
      strokeWeight: 4,
      strokeOpacity: 0.8
    })
    viewMapInstance.addOverlay(polyline)
  }

  if (points.length > 0) {
    const viewPoints = points.map(p => new BMapGL.Point(p.lng, p.lat))
    viewMapInstance.setViewport(viewPoints)
  }
}

// ==================== 新增/修改对话框 ====================
const editDialogVisible = ref(false)
const editDialogTitle = ref('新增监测点')
const editFormRef = ref(null)
const isEditMode = ref(false)
const editRowId = ref(null)

const editForm = ref({
  name: '',
  area: '',
  networkType: '',
  time: '',
  pointCount: 0,
  points: []
})

const editRules = {
  name: [{ required: true, message: '请输入监测点名称', trigger: 'blur' }],
  area: [{ required: true, message: '请输入地点', trigger: 'blur' }],
  networkType: [{ required: true, message: '请选择管网类型', trigger: 'change' }],
  time: [{ required: true, message: '请选择数据时间', trigger: 'change' }]
}

// 编辑弹窗地图相关
let editMapInstance = null
let editPoints = ref([])
let editMarkerCount = ref(0)

// 标记类型中文名
const editMarkerLabel = computed(() => {
  const map = { '管线': '管线节点', '管点': '管点', '排口': '排口' }
  return map[editForm.value.networkType] || '标记'
})

// 管网类型变更时，清空已有标记
function onNetworkTypeChange() {
  editPoints.value = []
  editMarkerCount.value = 0
  renderEditMarkers()
}

function handleAdd() {
  isEditMode.value = false
  editDialogTitle.value = '新增监测点'
  editRowId.value = null
  editForm.value = {
    name: '',
    area: '',
    networkType: '',
    time: '',
    pointCount: 0,
    points: []
  }
  editPoints.value = []
  editMarkerCount.value = 0
  editDialogVisible.value = true
}

function handleEdit(row) {
  isEditMode.value = true
  editDialogTitle.value = '修改监测点'
  editRowId.value = row.id
  editForm.value = {
    name: row.name,
    area: row.area,
    networkType: row.networkType,
    time: row.time,
    pointCount: row.pointCount || 0,
    points: []
  }
  // 深拷贝标记点数据
  const pts = parsePoints(row.points)
  editPoints.value = pts.map(p => ({ ...p }))
  editMarkerCount.value = editPoints.value.length
  editDialogVisible.value = true
}

function handleEditClose() {
  editDialogVisible.value = false
  if (editMapInstance) {
    editMapInstance = null
  }
}

function onEditDialogOpened() {
  setTimeout(() => {
    initEditMap()
  }, 300)
}

function initEditMap() {
  const container = document.getElementById('psgwglEditMap')
  if (!container) return

  try {
    editMapInstance = new BMapGL.Map('psgwglEditMap')
    const centerPoint = new BMapGL.Point(110.393, 28.452)
    editMapInstance.centerAndZoom(centerPoint, 15)
    editMapInstance.enableScrollWheelZoom(true)

    // 点击地图添加标记
    editMapInstance.addEventListener('click', function (e) {
      addEditMarker(e.latlng)
    })

    // 渲染已有标记
    renderEditMarkers()
  } catch (e) {
    console.error('百度地图初始化失败：', e)
  }
}

function addEditMarker(point) {
  const networkType = editForm.value.networkType
  if (!networkType) {
    ElMessage.warning('请先选择管网类型')
    return
  }

  // 管点和排口只能标记一个点位，再次点击则替换位置
  if ((networkType === '管点' || networkType === '排口') && editPoints.value.length >= 1) {
    editPoints.value[0] = {
      name: editPoints.value[0].name,
      lng: point.lng,
      lat: point.lat
    }
    renderEditMarkers(false)
    return
  }

  const count = ++editMarkerCount.value
  const labelPrefix = networkType === '管线' ? '管线节点' : networkType

  editPoints.value.push({
    name: `${labelPrefix}${count}`,
    lng: point.lng,
    lat: point.lat
  })

  // 统一重绘，保证地图与数据完全一致
  renderEditMarkers(false)
}

function renderEditMarkers(shouldCenter = true) {
  if (!editMapInstance) return
  editMapInstance.clearOverlays()

  const points = editPoints.value
  if (shouldCenter) {
    const center = points.length > 0
      ? new BMapGL.Point(points[0].lng, points[0].lat)
      : new BMapGL.Point(110.393, 28.452)
    editMapInstance.centerAndZoom(center, 15)
  }

  points.forEach((point, index) => {
    const bPoint = new BMapGL.Point(point.lng, point.lat)
    const label = createMapMarker(editMapInstance, bPoint, point.name)

    // 右键删除标记
    label.addEventListener('rightclick', () => {
      editPoints.value.splice(index, 1)
      renderEditMarkers(false)
    })
  })

  // 管线模式：绘制折线
  if (editForm.value.networkType === '管线' && points.length >= 2) {
    const polylinePoints = points.map(p => new BMapGL.Point(p.lng, p.lat))
    const polyline = new BMapGL.Polyline(polylinePoints, {
      strokeColor: '#409eff',
      strokeWeight: 4,
      strokeOpacity: 0.8
    })
    editMapInstance.addOverlay(polyline)
  }
}

function clearEditMarkers() {
  editPoints.value = []
  editMarkerCount.value = 0
  renderEditMarkers()
}

function handleEditSubmit() {
  editFormRef.value.validate(async valid => {
    if (!valid) return

    const formData = {
      name: editForm.value.name,
      area: editForm.value.area,
      networkType: editForm.value.networkType,
      time: editForm.value.time,
      pointCount: editPoints.value.length,
      points: JSON.stringify(editPoints.value.map(p => ({ name: p.name, lng: p.lng, lat: p.lat })))
    }
    try {
      if (isEditMode.value) {
        formData.id = editRowId.value
        const res = await updateDrainagePipeNetwork(formData)
        if (res.code === 0 || res.code === 200) {
          ElMessage.success('修改成功')
        } else {
          ElMessage.error(res.msg || '修改失败')
          return
        }
      } else {
        const res = await addDrainagePipeNetwork(formData)
        if (res.code === 0 || res.code === 200) {
          ElMessage.success('新增成功')
        } else {
          ElMessage.error(res.msg || '新增失败')
          return
        }
      }
      editDialogVisible.value = false
      if (editMapInstance) {
        editMapInstance = null
      }
      loadData()
    } catch (e) {
      console.error('提交失败', e)
      ElMessage.error('操作失败')
    }
  })
}

// ==================== 删除功能 ====================
function handleDelete(row) {
  ElMessageBox.confirm(`确认删除监测点"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteDrainagePipeNetwork(row.id)
      if (res.code === 0 || res.code === 200) {
        ElMessage.success('删除成功')
        loadData()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (e) {
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

function handleBatchDelete() {
  if (selectedIds.value.length === 0) return
  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 排水管网暂无批量删除接口，逐条删除
    try {
      await Promise.all(selectedIds.value.map(id => deleteDrainagePipeNetwork(id)))
      selectedIds.value = []
      ElMessage.success('删除成功')
      loadData()
    } catch (e) {
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

// ==================== 关联设备 ====================
const bindDialogVisible = ref(false)
const bindLoading = ref(false)
const bindTableData = ref([])
const bindTotal = ref(0)
const bindPageNum = ref(1)
const bindPageSize = ref(10)
const bindQueryParams = ref({ equipmentName: '', equipmentTypeId: 'drainage' })
const selectedEquipmentId = ref('')
const currentPartitionId = ref('')
const bindTableRef = ref(null)

async function handleBind(row) {
  currentPartitionId.value = row.id
  bindDialogVisible.value = true
  bindPageNum.value = 1
  bindQueryParams.value.equipmentName = ''
  // 回显已关联设备（取第一个）
  if (row.equipmentId) {
    selectedEquipmentId.value = row.equipmentId.split(',')[0].trim()
  } else {
    selectedEquipmentId.value = ''
  }
  nextTick(() => {
    loadBindData()
  })
}

function handleBindQuery() {
  bindPageNum.value = 1
  loadBindData()
}

async function loadBindData() {
  bindLoading.value = true
  try {
    const res = await getEquipmentPage(bindPageNum.value, bindPageSize.value, bindQueryParams.value)
    const pageData = res.code !== undefined ? res.data : res
    bindTableData.value = pageData.records || []
    bindTotal.value = pageData.total || 0
  } catch (e) {
    console.error('加载设备列表失败', e)
  } finally {
    bindLoading.value = false
  }
}

function closeBindDialog() {
  bindDialogVisible.value = false
  bindTableData.value = []
  selectedEquipmentId.value = ''
}

async function submitBind() {
  if (!selectedEquipmentId.value) {
    ElMessage.warning('请选择要关联的设备')
    return
  }
  try {
    const res = await bindPipeNetworkEquipment({
      partitionId: currentPartitionId.value,
      equipmentIds: [selectedEquipmentId.value]
    })
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('关联成功')
      closeBindDialog()
      loadData()
    } else {
      ElMessage.error(res.msg || '关联失败')
    }
  } catch (e) {
    console.error('关联设备失败', e)
    ElMessage.error('关联失败')
  }
}
</script>

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

.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;
}

.map-section {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.map-tabs {
  display: flex;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.map-tab {
  padding: 8px 24px;
  font-size: 14px;
  cursor: pointer;
  color: #606266;
  transition: all 0.3s;
  user-select: none;
}

.map-tab:hover {
  color: #409eff;
}

.map-tab.active {
  background: #409eff;
  color: #fff;
}

.map-tab-action {
  padding: 8px 24px;
  font-size: 14px;
  cursor: pointer;
  color: #f56c6c;
  transition: all 0.3s;
  user-select: none;
  margin-left: auto;
}

.map-tab-action:hover {
  color: #f78989;
  text-decoration: underline;
}

.map-container {
  width: 100%;
  height: 400px;
}

.marker-count {
  padding: 8px 16px;
  font-size: 13px;
  color: #909399;
  background: #f5f7fa;
  border-top: 1px solid #e4e7ed;
}
</style>
