<template>
  <div class="water-page">
    <div class="page-heading">
      <div class="page-title"><span class="page-title-icon"><el-icon><component :is="pageIcon" /></el-icon></span><div><h2>{{ title }}</h2><span class="muted">{{ view === 'gis' ? '设施分类图层、空间分布与详情联动' : '设施规模、状态与分类统计分析' }}</span></div></div>
      <div class="heading-actions">
        <template v-if="view === 'stats'">
          <el-select v-model="statusFilter" clearable placeholder="全部状态" class="status-select" @change="handleStatusChange">
            <el-option label="展示全部" value="" />
            <el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
          <el-checkbox-group v-model="selectedTypes" @change="handleTypeChange">
            <el-checkbox-button v-for="item in facilityTypes" :key="item.value" :value="item.value">{{ item.label }}</el-checkbox-button>
          </el-checkbox-group>
        </template>
        <el-checkbox-group v-if="view === 'gis'" v-model="selectedTypes" @change="loadData">
          <el-checkbox-button v-for="item in facilityTypes" :key="item.value" :value="item.value">{{ item.label }}</el-checkbox-button>
        </el-checkbox-group>
        <el-button v-if="view === 'stats'" type="success" plain icon="Download" :disabled="!selectedTypes.length" @click="exportData">导出</el-button>
        <el-button :icon="Refresh" @click="loadData">刷新</el-button>
      </div>
    </div>

    <div class="metric-grid">
      <div v-for="(item, index) in overview.slice(0, 5)" :key="item.label" class="metric">
        <div class="metric-icon"><el-icon><component :is="metricIcons[index % metricIcons.length]" /></el-icon></div>
        <div class="metric-body">
          <span>{{ item.label }}</span>
          <div class="metric-value"><strong>{{ item.value }}</strong><small>{{ item.unit }}</small></div>
        </div>
      </div>
    </div>

    <template v-if="view === 'gis'">
      <el-card shadow="never" class="map-card" v-loading="loading">
        <div class="map-legend"><span v-for="item in facilityTypes" :key="item.value"><i :style="{ background: item.color }"></i>{{ item.label }}</span></div>
        <div class="facility-map">
          <svg class="pipe-layer" viewBox="0 0 100 100" preserveAspectRatio="none">
            <polyline v-for="line in mapLines" :key="line.id" :points="line.points" fill="none" stroke="#64748b" stroke-width="0.75" vector-effect="non-scaling-stroke" />
          </svg>
          <button v-for="point in mapPoints" :key="point.id" class="facility-point" :style="pointStyle(point)" :title="point.name" @click="openFeature(point)">
            <span></span><b>{{ point.name || point.code || point.typeName }}</b>
          </button>
          <el-empty v-if="!mapPoints.length && !mapLines.length" description="暂无设施空间数据" />
        </div>
      </el-card>
    </template>

    <template v-else>
      <div class="chart-grid">
        <el-card shadow="never" class="chart-card">
          <template #header><div class="card-title"><el-icon><Histogram /></el-icon><span>设施数量与状态</span></div></template>
          <div ref="barChartRef" class="chart"></div>
        </el-card>
        <el-card shadow="never" class="chart-card">
          <template #header><div class="card-title"><el-icon><PieChart /></el-icon><span>设施类型占比</span></div></template>
          <div ref="pieChartRef" class="chart"></div>
        </el-card>
      </div>
      <el-card shadow="never" class="table-card">
        <template #header><div class="card-title"><el-icon><DataLine /></el-icon><span>统计明细</span></div></template>
        <el-table :data="rows" stripe border v-loading="loading">
          <el-table-column prop="section" min-width="180" show-overflow-tooltip>
            <template #header>
              <div class="table-header">
                <span>统计项</span>
                <el-tooltip content="按设施类型汇总的关键统计指标" placement="top">
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="统计分组" min-width="150" show-overflow-tooltip>
            <template #default="{ row }">
              <el-tag v-if="row.tagType" :type="row.tagType" effect="light">{{ row.name }}</el-tag>
              <span v-else>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="数值" width="110" />
          <el-table-column prop="unit" label="单位" width="90" />
          <el-table-column prop="description" label="说明" min-width="260" show-overflow-tooltip>
            <template #header>
              <div class="table-header">
                <span>说明</span>
                <el-tooltip content="当前行的统计口径和数据来源" placement="top">
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-if="!rows.length" :description="selectedTypes.length ? '暂无统计数据' : '请至少选择一类设施'" />
      </el-card>
    </template>

    <el-drawer v-model="detailVisible" class="detail-drawer" title="供水设施详情" direction="rtl" size="560px" append-to-body><el-descriptions :column="1" border><el-descriptions-item v-for="(value, key) in detail" :key="key" :label="key">{{ value ?? '-' }}</el-descriptions-item></el-descriptions></el-drawer>
  </div>
</template>

<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { DataAnalysis, DataLine, Histogram, InfoFilled, Location, MapLocation, PieChart, Refresh, Setting } from '@element-plus/icons-vue'
import { saveAs } from 'file-saver'
import * as echarts from 'echarts'
import { exportPipeNetworkStatistics, getPipeNetworkDashboard, getWaterFacilityDetail, getWaterFacilityFeatures, getWaterFacilityOverview } from '@/api/pipeNetwork/waterSupply'
import {
  FACILITY_SECTION_LABELS,
  FACILITY_SECTION_TYPES,
  buildPipeNetworkStatisticsQuery,
  getFacilityStatusOptions,
  resolveFacilityStatusLabel,
  resolveFacilityStatusTagType
} from '@/utils/waterFacilityStatisticsModel'
import { normalizeMapPoints, unwrapResponse } from '@/utils/waterSupplyModel'

const props = defineProps({ title: { type: String, required: true }, view: { type: String, default: 'stats' } })
const pageIcon = computed(() => props.view === 'gis' ? MapLocation : DataAnalysis)
const metricIcons = [Location, Setting, DataAnalysis, MapLocation]
const route = useRoute()
const facilityTypes = [
  { label: '水源地', value: 'source', color: '#3b82f6' },
  { label: '水厂', value: 'plant', color: '#22c55e' },
  { label: '泵站', value: 'pumpStation', color: '#f97316' },
  { label: '管网', value: 'pipe', color: '#06b6d4' },
  { label: '用水户', value: 'user', color: '#ef4446' }
]
const STATISTIC_LABELS = {
  totalCount: '总数',
  totalLength: '总长度',
  averageDiameter: '平均管径',
  designCapacity: '设计规模',
  currentCapacity: '实际规模',
  capacityUtilization: '产能利用率',
  pumpCount: '水泵数量',
  designFlow: '设计流量',
  designHead: '设计扬程',
  powerCapacity: '装机容量',
  annualWaterConsumption: '年用水量',
  materialDistribution: '管材分布',
  diameterDistribution: '管径分布',
  layingYearDistribution: '建设年代分布',
  pressureDistribution: '压力等级分布',
  statusDistribution: '状态分布',
  waterSourceTypeDistribution: '水源类型分布',
  sourceTypeDistribution: '水源地类型分布',
  qualityDistribution: '水质等级分布',
  protectionDistribution: '保护等级分布',
  userTypeDistribution: '用水户类型分布',
  consumptionDistribution: '用水量分布'
}
const STATISTIC_DESCRIPTIONS = {
  totalCount: '当前筛选条件下的设施总数',
  totalLength: '当前筛选条件下的管网总长度',
  averageDiameter: '当前筛选条件下的管径平均值',
  designCapacity: '水厂设计供水能力',
  currentCapacity: '水厂实际供水能力',
  capacityUtilization: '实际供水能力与设计供水能力的比值',
  pumpCount: '泵站内水泵总数量',
  designFlow: '泵站设计流量',
  designHead: '泵站设计扬程',
  powerCapacity: '泵站装机总容量',
  annualWaterConsumption: '用水户年度用水量',
  materialDistribution: '按管材统计管网数量',
  diameterDistribution: '按管径区间统计管网数量',
  layingYearDistribution: '按建设年代统计管网数量',
  pressureDistribution: '按压力等级统计管网数量',
  statusDistribution: '按业务状态统计设施数量',
  waterSourceTypeDistribution: '按水源类型统计水厂数量',
  sourceTypeDistribution: '按水源地类型统计数量',
  qualityDistribution: '按水质等级统计水源地数量',
  protectionDistribution: '按保护等级统计水源地数量',
  userTypeDistribution: '按用水户类型统计数量',
  consumptionDistribution: '按用水量区间统计用水户数量'
}
const STATUS_CATEGORY_LABELS = {
  abnormal: { source: '异常', plant: '停产', pumpStation: '故障停运', pipe: '停用', user: '停用' },
  warning: { pumpStation: '检修中', user: '欠费' }
}
const overview = ref([])
const rows = ref([])
const mapPoints = ref([])
const mapLines = ref([])
const routeTypes = String(route.query.type || '').split(',').map(item => item.trim()).filter(Boolean)
const selectedTypes = ref(routeTypes.length ? facilityTypes.map(item => item.value).filter(item => routeTypes.includes(item)) : facilityTypes.map(item => item.value))
const statusFilter = ref(String(route.query.status || ''))
const loading = ref(false)
const detailVisible = ref(false)
const detail = ref({})
const barChartRef = ref()
const pieChartRef = ref()
let barChart
let pieChart

const statusOptions = computed(() => getFacilityStatusOptions(selectedTypes.value))

const handleTypeChange = () => {
  const options = getFacilityStatusOptions(selectedTypes.value)
  if (!options.some(option => option.value === statusFilter.value)) statusFilter.value = ''
  loadData()
}

const handleStatusChange = value => {
  if (value === undefined || value === null) return
  statusFilter.value = String(value ?? '')
  loadData()
}

const typeColor = type => facilityTypes.find(item => item.value === type)?.color || '#2563eb'
const flattenMetrics = (section, value) => {
  if (Array.isArray(value)) return value.map(item => ({ ...item, section }))
  if (!value || typeof value !== 'object') return [{ name: section, value, unit: '项', section: '' }]
  return Object.entries(value).flatMap(([name, metric]) => {
    if (Array.isArray(metric)) return metric.map(item => ({ ...item, section: `${section}/${name}` }))
    if (metric && typeof metric === 'object') return flattenMetrics(`${section}/${name}`, metric)
    return [{ name, value: metric, unit: '项', section }]
  })
}

const statusCategoryLabel = category => {
  const labels = new Set()
  selectedTypes.value.forEach(type => {
    const label = STATUS_CATEGORY_LABELS[category]?.[type]
    if (label) labels.add(label)
  })
  return labels.size ? [...labels].join(' / ') : category === 'normal' ? '正常' : '未知'
}

const formatStatisticRow = (section, item) => {
  const [facilityKey, metricKey] = section.split('/')
  const rawMetricKey = metricKey || item.name
  const facilityType = FACILITY_SECTION_TYPES[facilityKey] || facilityKey
  const facilityLabel = FACILITY_SECTION_LABELS[facilityKey] || facilityKey || '总览'
  const metricLabel = STATISTIC_LABELS[rawMetricKey] || rawMetricKey || '总览'
  const isStatusDistribution = metricKey === 'statusDistribution'
  const name = isStatusDistribution
    ? resolveFacilityStatusLabel(facilityType, item.name)
    : item.name ?? metricLabel

  return {
    section: `${facilityLabel} - ${metricLabel}`,
    name,
    tagType: isStatusDistribution ? resolveFacilityStatusTagType(facilityType, item.name) : undefined,
    value: item.value ?? item.totalCount ?? 0,
    unit: item.unit || '项',
    description: STATISTIC_DESCRIPTIONS[rawMetricKey] || '按当前筛选条件统计'
  }
}

const clearStatistics = async () => {
  overview.value = []
  rows.value = []
  await renderCharts([])
}

const renderCharts = async facilityOverview => {
  await nextTick()
  barChart?.dispose(); pieChart?.dispose()
  if (!barChartRef.value || !pieChartRef.value) return
  const labels = facilityOverview.map(item => item.facilityTypeName || item.name || item.facilityType)
  const statusSeries = [
    { key: 'normalCount', name: '正常', color: '#22c55e' },
    { key: 'abnormalCount', name: statusCategoryLabel('abnormal'), color: '#ef4444' },
    { key: 'warningCount', name: statusCategoryLabel('warning'), color: '#f97316' },
    { key: 'unknownCount', name: '未知', color: '#94a3b8' }
  ].filter(series => facilityOverview.some(item => Number(item[series.key] || 0) > 0))
  const totalFacilities = facilityOverview.reduce((total, item) => total + Number(item.totalCount || 0), 0)
  barChart = echarts.init(barChartRef.value)
  barChart.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow', shadowStyle: { color: 'rgba(37, 99, 235, 0.06)' } } },
    legend: { top: 0, icon: 'circle', itemWidth: 9, itemHeight: 9, textStyle: { color: '#475569' } },
    grid: { left: 48, right: 20, top: 46, bottom: 36 },
    xAxis: { type: 'category', data: labels, axisLine: { lineStyle: { color: '#cbd5e1' } }, axisLabel: { color: '#475569' } },
    yAxis: { type: 'value', minInterval: 1, axisLine: { show: false }, axisLabel: { color: '#64748b' }, splitLine: { lineStyle: { color: '#e2e8f0', type: 'dashed' } } },
    series: statusSeries.map(series => ({
      name: series.name,
      type: 'bar',
      stack: 'status',
      barWidth: 24,
      data: facilityOverview.map(item => Number(item[series.key] || 0)),
      itemStyle: {
        borderRadius: [6, 6, 0, 0],
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: series.color },
          { offset: 1, color: `${series.color}33` }
        ]),
        shadowColor: 'rgba(15, 23, 42, 0.12)',
        shadowBlur: 8,
        shadowOffsetY: 4
      }
    }))
  })
  pieChart = echarts.init(pieChartRef.value)
  pieChart.setOption({
    tooltip: { trigger: 'item' },
    legend: { bottom: 0, icon: 'circle', itemWidth: 9, itemHeight: 9, textStyle: { color: '#475569' } },
    title: {
      text: String(totalFacilities),
      subtext: '设施总数',
      left: 'center',
      top: '33%',
      textStyle: { color: '#1e293b', fontSize: 24, fontWeight: 700 },
      subtextStyle: { color: '#64748b', fontSize: 12 }
    },
    series: [{
      type: 'pie',
      radius: ['52%', '72%'],
      center: ['50%', '45%'],
      data: facilityOverview.map(item => ({
        name: item.facilityTypeName || item.name || item.facilityType,
        value: Number(item.totalCount || 0),
        itemStyle: { color: typeColor(item.facilityType) }
      })),
      label: { formatter: '{b}\n{d}%', color: '#475569', lineHeight: 18 },
      itemStyle: { borderColor: '#fff', borderWidth: 3, borderRadius: 8 },
      emphasis: { scaleSize: 8 }
    }]
  })
}

const buildMap = features => {
  const rawPoints = []
  const rawLines = []
  features.forEach(feature => {
    const coordinates = feature.geometry?.coordinates || []
    const properties = feature.properties || {}
    if (feature.geometry?.type === 'Point') rawPoints.push({ ...properties, id: feature.id, longitude: coordinates[0], latitude: coordinates[1], type: properties.facilityType, typeName: properties.facilityTypeName })
    if (feature.geometry?.type === 'LineString' && coordinates.length > 1) rawLines.push({ id: feature.id, properties, coordinates })
  })
  const coordinatePoints = [...rawPoints, ...rawLines.flatMap(line => line.coordinates.map((coordinate, index) => ({ id: `${line.id}-${index}`, longitude: coordinate[0], latitude: coordinate[1] })))]
  const positions = new Map(normalizeMapPoints(coordinatePoints).map(item => [item.id, item]))
  mapPoints.value = rawPoints.map(point => ({ ...point, ...positions.get(point.id) })).filter(point => Number.isFinite(point.mapX))
  mapLines.value = rawLines.map(line => ({ ...line, points: line.coordinates.map((_, index) => positions.get(`${line.id}-${index}`)).filter(Boolean).map(point => `${point.mapX},${point.mapY}`).join(' ') })).filter(line => line.points)
}

const loadData = async () => {
  loading.value = true
  try {
    if (props.view === 'gis') {
      const [overviewResponse, featureResponse] = await Promise.all([getWaterFacilityOverview(), getWaterFacilityFeatures({ types: selectedTypes.value.join(',') })])
      const summary = unwrapResponse(overviewResponse) || []
      overview.value = summary.filter(item => item.facilityType !== 'total').map(item => ({ label: item.facilityTypeName, value: item.geoCompleteCount ?? 0, unit: '个点位' }))
      buildMap(unwrapResponse(featureResponse)?.features || [])
    } else {
      if (!selectedTypes.value.length) {
        await clearStatistics()
        return
      }
      const params = buildPipeNetworkStatisticsQuery({
        facilityTypes: selectedTypes.value,
        status: statusFilter.value
      })
      const data = unwrapResponse(await getPipeNetworkDashboard(params)) || {}
      const facilityOverview = Array.isArray(data.facilityOverview) ? data.facilityOverview : []
      overview.value = facilityOverview.map(item => ({ label: item.facilityTypeName || item.facilityType, value: item.totalCount ?? 0, unit: '项' }))
      rows.value = Object.entries(data)
        .filter(([section]) => section !== 'facilityOverview')
        .flatMap(([section, value]) => flattenMetrics(section, value))
        .map(item => formatStatisticRow(item.section, item))
      await renderCharts(facilityOverview)
    }
  } catch (error) { overview.value = []; rows.value = []; mapPoints.value = []; mapLines.value = []; console.warn(`[${props.title}] 数据加载失败`, error) } finally { loading.value = false }
}
const exportData = async () => {
  if (props.view === 'stats' && !selectedTypes.value.length) return
  try {
    const params = buildPipeNetworkStatisticsQuery({
      facilityTypes: selectedTypes.value,
      status: statusFilter.value
    })
    const blob = await exportPipeNetworkStatistics(params)
    saveAs(new Blob([blob]), `管网数据统计分析_${new Date().toISOString().slice(0, 10)}.xlsx`)
  } catch (error) {
    console.warn('管网统计导出失败', error)
  }
}
const pointStyle = point => ({ left: `${point.mapX}%`, top: `${point.mapY}%`, color: typeColor(point.type) })
const openFeature = async point => { try { const response = await getWaterFacilityDetail(point.type, point.id?.split(':').pop()); detail.value = unwrapResponse(response) || point; detailVisible.value = true } catch {} }
const resizeCharts = () => { barChart?.resize(); pieChart?.resize() }
onMounted(() => { loadData(); window.addEventListener('resize', resizeCharts) })
onBeforeUnmount(() => { window.removeEventListener('resize', resizeCharts); barChart?.dispose(); pieChart?.dispose() })
</script>

<style lang="scss">
@use './waterSupplyPageTheme.scss';
</style>

<style scoped>
.water-page {
  padding: 20px;
  min-height: calc(100vh - 84px);
  background: linear-gradient(135deg, #eff6ff 0%, #f8fafc 45%, #eef2f7 100%);
}

.page-heading {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  margin-bottom: 18px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-title-icon {
  display: grid;
  place-items: center;
  width: 42px;
  height: 42px;
  border-radius: 8px;
  color: #fff;
  background: linear-gradient(135deg, #2563eb 0%, #06b6d4 100%);
  box-shadow: 0 8px 16px rgba(37, 99, 235, 0.2);
}

.page-heading h2 {
  margin: 0 0 4px;
  font-size: 20px;
  color: #1e293b;
}

.muted {
  font-size: 13px;
  color: #64748b;
}

.heading-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-select {
  width: 180px;
}

.metric-grid {
  display: grid;
  grid-template-columns: repeat(5, minmax(160px, 1fr));
  gap: 14px;
  margin-bottom: 16px;
}

.metric {
  display: flex;
  align-items: center;
  gap: 14px;
  min-width: 0;
  padding: 16px 18px;
  background: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  box-shadow: 0 6px 14px rgba(15, 23, 42, 0.04);
}

.metric-icon {
  position: static;
  flex: 0 0 42px;
  display: grid;
  place-items: center;
  width: 42px;
  height: 42px;
  border-radius: 8px;
  color: #2563eb;
  background: linear-gradient(135deg, #dbeafe 0%, #eff6ff 100%);
}

.metric-icon .el-icon {
  font-size: 22px;
}

.metric-body span {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 3px;
  color: #64748b;
  font-size: 13px;
}

.metric-value {
  display: flex;
  align-items: baseline;
  gap: 5px;
  min-width: 0;
}

.metric-value strong {
  color: #1e293b;
  font-size: 24px;
  line-height: 1.2;
}

.metric-value small {
  color: #94a3b8;
}

.chart-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.chart-card,
.table-card {
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  box-shadow: 0 6px 14px rgba(15, 23, 42, 0.04);
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #1e293b;
  font-weight: 600;
}

.card-title .el-icon {
  color: #2563eb;
  font-size: 18px;
}

.chart {
  height: 320px;
}

.table-card :deep(.el-card__body) {
  padding-top: 0;
}

.table-card :deep(.el-table__header th) {
  color: #475569;
  background: #f8fafc;
}

.table-header {
  display: flex;
  align-items: center;
  gap: 5px;
}

.table-header .el-icon {
  color: #94a3b8;
  cursor: help;
}

.map-card {
  min-height: 580px;
}

.map-legend {
  display: flex;
  gap: 18px;
  margin-bottom: 12px;
  color: #475569;
  font-size: 13px;
}

.map-legend i {
  display: inline-block;
  width: 9px;
  height: 9px;
  margin-right: 6px;
  border-radius: 50%;
}

.facility-map {
  position: relative;
  height: 500px;
  overflow: hidden;
  border: 1px solid #dbe6f2;
  border-radius: 8px;
  background-color: #f8fbff;
  background-image: linear-gradient(#eaf0f6 1px, transparent 1px), linear-gradient(90deg, #eaf0f6 1px, transparent 1px);
  background-size: 40px 40px;
}

.pipe-layer {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  overflow: visible;
}

.facility-point {
  position: absolute;
  padding: 0;
  border: 0;
  background: transparent;
  color: #2563eb;
  cursor: pointer;
  text-align: center;
  transform: translate(-50%, -50%);
}

.facility-point span {
  display: block;
  width: 15px;
  height: 15px;
  margin: auto;
  border: 3px solid #fff;
  border-radius: 50%;
  background: currentColor;
  box-shadow: 0 0 0 3px currentColor;
}

.facility-point b {
  display: block;
  margin-top: 4px;
  color: #334155;
  font-size: 11px;
  white-space: nowrap;
}

.facility-map :deep(.el-empty) {
  position: absolute;
  inset: 0;
}

@media (max-width: 1100px) {
  .metric-grid {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }

  .heading-actions {
    align-items: flex-end;
    flex-direction: column;
  }
}

@media (max-width: 800px) {
  .page-heading {
    align-items: flex-start;
    flex-direction: column;
  }

  .chart-grid,
  .metric-grid {
    grid-template-columns: 1fr;
  }

  .heading-actions {
    align-items: flex-start;
  }

  .heading-actions :deep(.el-checkbox-group) {
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
