<template>
  <div class="app-container">
    <!-- 顶部搜索区 -->
    <el-form :model="searchKey" :inline="true" class="search-form">
      <el-form-item label="管网名称">
        <el-input v-model="searchKey.name" placeholder="请输入管网名称" clearable style="width: 220px" />
      </el-form-item>
      <el-form-item label="管网类型">
        <el-select v-model="searchKey.networkType" placeholder="请选择" clearable style="width: 140px">
          <el-option v-for="item in networkTypeOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>

    <div class="main-layout">
      <!-- 左侧管网列表 -->
      <div class="left-panel">
        <div class="panel-title">管网列表</div>
        <div class="pipe-list" v-loading="listLoading">
          <div v-for="item in pipeList" :key="item.id" class="pipe-item"
            :class="{ active: currentPipe?.id === item.id }" @click="selectPipe(item)">
            <div class="pipe-item-name">{{ item.name }}</div>
            <div class="pipe-item-meta">
              <el-tag size="small" :type="networkTypeTagType(item.networkType)" effect="light">{{ item.networkType }}</el-tag>
              <span class="pipe-item-area">{{ item.area }}</span>
            </div>
            <div v-if="item._alarmCount > 0" class="pipe-item-alarm">
              <el-icon color="#F56C6C"><Warning /></el-icon>
              <span>{{ item._alarmCount }} 条报警</span>
            </div>
          </div>
          <el-empty v-if="pipeList.length === 0 && !listLoading" description="暂无数据" :image-size="60" />
        </div>
      </div>

      <!-- 右侧详情区 -->
      <div class="right-panel">
        <template v-if="currentPipe">
          <el-tabs v-model="activeTab" type="border-card">
            <!-- Tab 1: 基本信息 -->
            <el-tab-pane label="基本信息" name="basic">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="管网名称">{{ currentPipe.name }}</el-descriptions-item>
                <el-descriptions-item label="所属区域">{{ currentPipe.area }}</el-descriptions-item>
                <el-descriptions-item label="管网类型">
                  <el-tag :type="networkTypeTagType(currentPipe.networkType)" effect="light">{{ currentPipe.networkType }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="关联设备">
                  <span v-if="currentPipe.equipmentId">已关联 (ID: {{ currentPipe.equipmentId }})</span>
                  <span v-else style="color:#909399">未关联</span>
                </el-descriptions-item>
                <el-descriptions-item label="坐标信息" :span="2">{{ formatPoints(currentPipe.points) }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ currentPipe.createTime }}</el-descriptions-item>
                <el-descriptions-item label="更新时间">{{ currentPipe.updateTime }}</el-descriptions-item>
              </el-descriptions>
            </el-tab-pane>

            <!-- Tab 2: 报警统计 -->
            <el-tab-pane label="报警统计" name="alarm">
              <div v-if="currentPipe.equipmentId" v-loading="alarmLoading">
                <!-- 报警统计概览 -->
                <div class="alarm-stats-bar">
                  <div class="alarm-stat-item">
                    <span class="alarm-stat-value">{{ alarmTotal }}</span>
                    <span class="alarm-stat-label">总报警数</span>
                  </div>
                  <div class="alarm-stat-item">
                    <span class="alarm-stat-value" style="color:#F56C6C">{{ alarmUnhandled }}</span>
                    <span class="alarm-stat-label">未处理</span>
                  </div>
                  <div class="alarm-stat-item">
                    <span class="alarm-stat-value" style="color:#E6A23C">{{ alarmHandling }}</span>
                    <span class="alarm-stat-label">处理中</span>
                  </div>
                  <div class="alarm-stat-item">
                    <span class="alarm-stat-value" style="color:#67C23A">{{ alarmHandled }}</span>
                    <span class="alarm-stat-label">已处理</span>
                  </div>
                </div>

                <!-- 报警列表 -->
                <el-table :data="alarmList" border style="width: 100%; margin-top: 16px;" v-if="alarmList.length > 0">
                  <el-table-column label="序号" type="index" width="60" align="center" />
                  <el-table-column prop="alarmTime" label="报警时间" min-width="160" />
                  <el-table-column prop="alarmType" label="报警类型" min-width="100" />
                  <el-table-column prop="alarmContent" label="报警内容" min-width="220" />
                  <el-table-column prop="status" label="状态" min-width="90" align="center">
                    <template #default="{ row }">
                      <el-tag :type="row.status === 0 ? 'warning' : row.status === 1 ? 'primary' : 'success'" size="small">
                        {{ row.status === 0 ? '未处理' : row.status === 1 ? '处理中' : '已处理' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
                <el-empty v-else description="暂无报警数据" :image-size="60" />

                <!-- 报警分页 -->
                <div v-if="alarmTotal > 0" class="alarm-pagination">
                  <el-pagination
                    v-model:current-page="alarmPageNum"
                    v-model:page-size="alarmPageSize"
                    :page-sizes="[10, 20, 50]"
                    :total="alarmTotal"
                    layout="total, sizes, prev, pager, next"
                    small
                    background
                    @size-change="loadAlarmData"
                    @current-change="loadAlarmData"
                  />
                </div>
              </div>
              <el-empty v-else description="该管网未关联设备，无报警数据" :image-size="80" />
            </el-tab-pane>

            <!-- Tab 3: 报警趋势 -->
            <el-tab-pane label="报警趋势" name="trend">
              <div v-if="currentPipe.equipmentId && alarmTrendData.length > 0">
                <div ref="trendChartRef" style="height: 350px;"></div>
              </div>
              <el-empty v-else description="暂无报警趋势数据" :image-size="80" />
            </el-tab-pane>
          </el-tabs>
        </template>
        <el-empty v-else description="请选择左侧管网查看详情" :image-size="120" />
      </div>
    </div>
  </div>
</template>

<script setup name="Zhfxxqfx">
import { ref, computed, watch, nextTick, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { Warning } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getPipeNetworkPage, getAlarmDataPage } from '@/api/drainage'

const route = useRoute()

// ==================== 选项 ====================
const networkTypeOptions = ['管线', '管点', '排口']

// ==================== 搜索 ====================
const searchKey = ref({ name: '', networkType: '管线' })
const handleSearch = () => { loadPipeList() }

// ==================== 管网列表 ====================
const pipeList = ref([])
const listLoading = ref(false)
const currentPipe = ref(null)
const activeTab = ref('basic')

const loadPipeList = async () => {
  listLoading.value = true
  try {
    const params = {}
    if (searchKey.value.name) params.name = searchKey.value.name
    if (searchKey.value.networkType) params.networkType = searchKey.value.networkType

    // 加载较多数据用于左侧列表
    const res = await getPipeNetworkPage(1, 200, params)
    const pageData = res.code !== undefined ? res.data : res
    const rows = pageData.records || pageData.rows || []

    // 批量查询报警数
    const withAlarms = await Promise.all(
      rows.map(async (item) => {
        let alarmCount = 0
        if (item.equipmentId) {
          try {
            const alarmRes = await getAlarmDataPage(1, 1, { equipmentId: item.equipmentId, equipmentType: 'drainage' })
            const alarmPageData = alarmRes.code !== undefined ? alarmRes.data : alarmRes
            alarmCount = alarmPageData.total ?? 0
          } catch (e) { /* ignore */ }
        }
        return { ...item, _alarmCount: alarmCount }
      })
    )
    pipeList.value = withAlarms

    // 如果有路由参数指定ID，自动选中
    const queryId = route.query.id
    if (queryId) {
      const found = withAlarms.find(i => String(i.id) === String(queryId))
      if (found) selectPipe(found)
    } else if (withAlarms.length > 0 && !currentPipe.value) {
      selectPipe(withAlarms[0])
    }
  } catch (e) {
    console.error('加载管网列表失败', e)
    pipeList.value = []
  } finally {
    listLoading.value = false
  }
}

const selectPipe = (item) => {
  currentPipe.value = item
  activeTab.value = 'basic'
  // 重置报警数据
  alarmList.value = []
  alarmTotal.value = 0
  alarmPageNum.value = 1
  alarmTrendData.value = []
}

// ==================== 报警数据 ====================
const alarmLoading = ref(false)
const alarmList = ref([])
const alarmTotal = ref(0)
const alarmPageNum = ref(1)
const alarmPageSize = ref(10)

const alarmUnhandled = computed(() => alarmList.value.filter(i => i.status === 0).length)
const alarmHandling = computed(() => alarmList.value.filter(i => i.status === 1).length)
const alarmHandled = computed(() => alarmList.value.filter(i => i.status === 2).length)

const loadAlarmData = async () => {
  if (!currentPipe.value?.equipmentId) return
  alarmLoading.value = true
  try {
    const res = await getAlarmDataPage(alarmPageNum.value, alarmPageSize.value, {
      equipmentId: currentPipe.value.equipmentId,
      equipmentType: 'drainage'
    })
    const pageData = res.code !== undefined ? res.data : res
    alarmList.value = pageData.records || pageData.rows || []
    alarmTotal.value = pageData.total ?? 0
  } catch (e) {
    alarmList.value = []
    alarmTotal.value = 0
  } finally {
    alarmLoading.value = false
  }
}

// ==================== 报警趋势 ====================
const alarmTrendData = ref([])
const trendChartRef = ref(null)
let trendChart = null

const loadAlarmTrend = async () => {
  if (!currentPipe.value?.equipmentId) return
  try {
    // 加载较多报警数据用于趋势分析
    const res = await getAlarmDataPage(1, 500, {
      equipmentId: currentPipe.value.equipmentId,
      equipmentType: 'drainage'
    })
    const trendPageData = res.code !== undefined ? res.data : res
    const rows = trendPageData.records || trendPageData.rows || []
    // 按日期聚合报警数
    const dateMap = {}
    rows.forEach(item => {
      const date = (item.alarmTime || '').substring(0, 10)
      if (date) {
        dateMap[date] = (dateMap[date] || 0) + 1
      }
    })
    alarmTrendData.value = Object.entries(dateMap)
      .sort((a, b) => a[0].localeCompare(b[0]))
      .map(([date, count]) => ({ date, count }))
  } catch (e) {
    alarmTrendData.value = []
  }
}

const initTrendChart = () => {
  if (!trendChartRef.value || alarmTrendData.value.length === 0) return
  if (trendChart) { trendChart.dispose(); trendChart = null }
  trendChart = echarts.init(trendChartRef.value)
  trendChart.setOption({
    tooltip: { trigger: 'axis' },
    grid: { left: 50, right: 30, top: 30, bottom: 30 },
    xAxis: {
      type: 'category',
      data: alarmTrendData.value.map(d => d.date),
      axisLabel: { fontSize: 11, color: '#909399', rotate: 30 }
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      axisLabel: { color: '#909399' },
      splitLine: { lineStyle: { type: 'dashed' } }
    },
    series: [{
      type: 'bar',
      data: alarmTrendData.value.map(d => d.count),
      itemStyle: { color: '#E6A23C', borderRadius: [4, 4, 0, 0] },
      barMaxWidth: 30
    }]
  })
}

// ==================== 监听Tab切换 ====================
watch(activeTab, (val) => {
  if (val === 'alarm' && currentPipe.value?.equipmentId) {
    loadAlarmData()
  }
  if (val === 'trend' && currentPipe.value?.equipmentId) {
    loadAlarmTrend().then(() => nextTick(() => initTrendChart()))
  }
})

// 监听选中管网变化时销毁图表
watch(currentPipe, () => {
  if (trendChart) { trendChart.dispose(); trendChart = null }
})

// ==================== 工具函数 ====================
const networkTypeTagType = (type) => {
  const map = { '管线': '', '管点': 'warning', '排口': 'success' }
  return map[type] || ''
}

const formatPoints = (points) => {
  if (!points) return '暂无坐标'
  try {
    const parsed = typeof points === 'string' ? JSON.parse(points) : points
    if (Array.isArray(parsed)) {
      return parsed.map(p => `${p.lng || p[0]}, ${p.lat || p[1]}`).join(' → ')
    }
    return String(points)
  } catch {
    return String(points)
  }
}

// ==================== 初始化 ====================
onMounted(() => {
  loadPipeList()
})
</script>

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

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

/* 主布局 */
.main-layout {
  display: flex;
  gap: 16px;
  min-height: calc(100vh - 160px);
}

/* 左侧面板 */
.left-panel {
  width: 280px;
  flex-shrink: 0;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.panel-title {
  padding: 12px 16px;
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  border-bottom: 1px solid #e4e7ed;
}

.pipe-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.pipe-item {
  padding: 10px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 4px;
  border: 1px solid transparent;
}

.pipe-item:hover {
  background: #f5f7fa;
}

.pipe-item.active {
  background: #ecf5ff;
  border-color: #409EFF;
}

.pipe-item-name {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
  margin-bottom: 6px;
}

.pipe-item-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.pipe-item-area {
  font-size: 12px;
  color: #909399;
}

.pipe-item-alarm {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #F56C6C;
  margin-top: 4px;
}

/* 右侧面板 */
.right-panel {
  flex: 1;
  min-width: 0;
}

/* 报警统计栏 */
.alarm-stats-bar {
  display: flex;
  gap: 24px;
  padding: 16px 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.alarm-stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.alarm-stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
}

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

/* 报警分页 */
.alarm-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
</style>
