<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header"><span>水文信息</span></div>
      </template>

      <!-- 数据类型切换 -->
      <el-radio-group v-model="dataType" size="default" class="mb-16" @change="onDataTypeChange">
        <el-radio-button value="waterLevel">水位</el-radio-button>
        <el-radio-button value="flow">流量</el-radio-button>
        <el-radio-button value="waterQuality">水质</el-radio-button>
        <el-radio-button value="engineeringSH">工情(上海)</el-radio-button>
        <el-radio-button value="engineeringXJ">工情(新建和完善)</el-radio-button>
      </el-radio-group>

      <!-- 筛选条件 -->
      <el-form :inline="true" size="small" class="mb-16">
        <el-form-item v-if="dataType !== 'engineeringSH' && dataType !== 'engineeringXJ'" label="站点">
          <el-select v-model="station" placeholder="请选择站点" style="width: 180px" clearable>
            <el-option v-for="s in stations" :key="s.STNM" :label="s.STNM" :value="s.STCD || s.STNM" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            value-format="YYYY-MM-DD"
            :default-time="defaultTime"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled-date="disableDate"
            style="width: 280px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="refreshData">查询</el-button>
          <el-button type="info" icon="View" @click="handleStationDetail" :disabled="!station">站点详情</el-button>
        </el-form-item>
      </el-form>

      <!-- 水位/流量 概览卡片 -->
      <template v-if="dataType === 'waterLevel' || dataType === 'flow'">
        <el-row :gutter="16" class="mb-16">
          <el-col :span="6" v-for="s in dataList" :key="s.label">
            <el-card shadow="never" class="data-card">
              <div class="data-label">{{ s.label }}</div>
              <div class="data-value" :style="{ color: s.color }">{{ s.value }}</div>
              <div class="data-unit">{{ s.unit }}</div>
            </el-card>
          </el-col>
        </el-row>
      </template>

      <!-- 水位 / 流量 图表 -->
      <template v-if="dataType === 'waterLevel' || dataType === 'flow'">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-card shadow="never">
              <template #header><div class="card-header"><span>水位趋势</span></div></template>
              <div ref="levelChartRef" style="height: 320px; width: 100%"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="never">
              <template #header><div class="card-header"><span>流量趋势</span></div></template>
              <div ref="flowChartRef" style="height: 320px; width: 100%"></div>
            </el-card>
          </el-col>
        </el-row>
      </template>

      <!-- 水质模块 -->
      <template v-if="dataType === 'waterQuality'">
        <el-row :gutter="16" class="mb-16">
          <el-col :span="24">
            <el-card shadow="never">
              <template #header><div class="card-header"><span>水质参数趋势</span></div></template>
              <div ref="waterQualityChartRef" style="height: 400px; width: 100%"></div>
            </el-card>
          </el-col>
        </el-row>
        <el-card shadow="never">
          <template #header><div class="card-header"><span>水质数据明细</span></div></template>
          <el-table :data="waterQualityPageData" stripe border v-loading="loading" style="width: 100%">
            <el-table-column prop="MONITORTIME" label="监测时间" width="180" fixed />
            <el-table-column prop="STNM" label="站点" width="140" />
            <el-table-column prop="W0" label="水温(°C)" width="100" />
            <el-table-column prop="PH" label="PH值" width="90" />
            <el-table-column prop="DO" label="溶解氧(mg/L)" width="120" />
            <el-table-column prop="CODMN" label="高锰酸盐指数(mg/L)" width="150" />
            <el-table-column prop="COND" label="电导率(μS/cm)" width="130" />
            <el-table-column prop="ORP" label="氧化还原电位(mV)" width="150" />
            <el-table-column prop="TURB" label="浊度(NTU)" width="110" />
            <el-table-column prop="NH3N" label="氨氮(mg/L)" width="110" />
            <el-table-column prop="TN" label="总氮(mg/L)" width="100" />
            <el-table-column prop="TP" label="总磷(mg/L)" width="100" />
            <el-table-column prop="NH4" label="铵离子(mg/L)" width="110" />
          </el-table>
          <div class="pagination-wrap" v-if="waterQualityList.length > pageSize">
            <el-pagination
              v-model:current-page="waterQualityPage"
              :page-size="pageSize"
              :total="waterQualityList.length"
              layout="total, prev, pager, next"
              background
              @current-change="onWaterQualityPageChange"
            />
          </div>
        </el-card>
      </template>

      <!-- 工情(上海) -->
      <template v-if="dataType === 'engineeringSH'">
        <el-card shadow="never">
          <template #header><div class="card-header"><span>工情数据 - 上海</span></div></template>
          <el-table :data="engineeringSHPageData" stripe border v-loading="loading" style="width: 100%">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="STNM" label="站点名称" min-width="150" />
            <el-table-column prop="MONITORTIME" label="监测时间" width="180" />
            <el-table-column prop="W0" label="水位(m)" width="100" />
            <el-table-column prop="Q0" label="流量(m³/s)" width="110" />
            <el-table-column prop="STATUS" label="运行状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.STATUS === '正常' ? 'success' : scope.row.STATUS === '异常' ? 'danger' : 'warning'" size="small">
                  {{ scope.row.STATUS || '-' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="REMARK" label="备注" min-width="180" show-overflow-tooltip />
          </el-table>
          <div class="pagination-wrap" v-if="engineeringSHList.length > pageSize">
            <el-pagination
              v-model:current-page="engineeringSHPage"
              :page-size="pageSize"
              :total="engineeringSHList.length"
              layout="total, prev, pager, next"
              background
              @current-change="onEngineeringSHPageChange"
            />
          </div>
        </el-card>
      </template>

      <!-- 工情(新建和完善) -->
      <template v-if="dataType === 'engineeringXJ'">
        <el-card shadow="never">
          <template #header><div class="card-header"><span>工情数据 - 新建和完善</span></div></template>
          <el-table :data="engineeringXJPageData" stripe border v-loading="loading" style="width: 100%">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="STNM" label="站点名称" min-width="150" />
            <el-table-column prop="MONITORTIME" label="监测时间" width="180" />
            <el-table-column prop="TYPE" label="工程类型" width="110" />
            <el-table-column prop="W0" label="水位(m)" width="100" />
            <el-table-column prop="Q0" label="流量(m³/s)" width="110" />
            <el-table-column prop="STATUS" label="运行状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.STATUS === '正常' ? 'success' : scope.row.STATUS === '异常' ? 'danger' : 'warning'" size="small">
                  {{ scope.row.STATUS || '-' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="DESIGN_CAP" label="设计能力" width="110" />
            <el-table-column prop="REMARK" label="备注" min-width="180" show-overflow-tooltip />
          </el-table>
          <div class="pagination-wrap" v-if="engineeringXJList.length > pageSize">
            <el-pagination
              v-model:current-page="engineeringXJPage"
              :page-size="pageSize"
              :total="engineeringXJList.length"
              layout="total, prev, pager, next"
              background
              @current-change="onEngineeringXJPageChange"
            />
          </div>
        </el-card>
      </template>
    </el-card>

    <!-- 站点详情弹窗 (对应旧版 yj_history_select.html) -->
    <el-dialog v-model="stationDetailVisible" title="站点详情" width="600px" append-to-body>
      <div v-loading="stationDetailLoading">
        <template v-if="stationDetailInfo">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="测站名称">{{ stationDetailInfo.STNM }}</el-descriptions-item>
            <el-descriptions-item label="河流名称">{{ stationDetailInfo.RVNM }}</el-descriptions-item>
            <el-descriptions-item label="所属水系">{{ stationDetailInfo.HNNM }}</el-descriptions-item>
            <el-descriptions-item label="站类">{{ stationDetailInfo.STTP }}</el-descriptions-item>
            <el-descriptions-item label="地址">{{ stationDetailInfo.STLC }}</el-descriptions-item>
            <el-descriptions-item label="管理单位">{{ stationDetailInfo.ADMAUTH }}</el-descriptions-item>
          </el-descriptions>
          <el-divider />
          <div v-if="stationDetailMonitor.length" class="monitor-section">
            <h4 style="margin:0 0 12px">实时监测数据</h4>
            <el-table :data="stationDetailMonitor" stripe border>
              <el-table-column prop="VIEWTIME" label="观测时间" width="180" />
              <el-table-column prop="W0" label="水位(m)" width="120" />
              <el-table-column prop="Q0" label="流量(m³/s)" width="130" />
            </el-table>
          </div>
          <el-empty v-else description="暂无实时监测数据" :image-size="60" />
        </template>
        <el-empty v-else description="未找到站点信息" :image-size="60" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Hydrology">
import * as echarts from 'echarts'
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import {
  getStationList,
  getLevelData,
  getFlowData,
  getRealtimeData,
  getWaterQualityData,
  getEngineeringData
} from '@/api/slgc/hydrology/index'

// ---- 状态定义 ----
const dataType = ref('waterLevel')
const station = ref('')
const stations = ref([])
const loading = ref(false)
const stationDetailVisible = ref(false)
const stationDetailLoading = ref(false)
const stationDetailInfo = ref(null)
const stationDetailMonitor = ref([])
const defaultTime = ref([new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)])

// 日期范围 - 默认最近7天
const dateRange = ref(getDefaultDateRange())

function getDefaultDateRange() {
  const end = new Date()
  const start = new Date()
  start.setDate(start.getDate() - 6)
  return [formatDate(start), formatDate(end)]
}

function formatDate(d) {
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

// 31天限制
function disableDate(date) {
  if (!dateRange.value || !dateRange.value[0]) return false
  const start = new Date(dateRange.value[0]).getTime()
  const diff = date.getTime() - start
  const thirtyOneDays = 31 * 24 * 60 * 60 * 1000
  if (diff > thirtyOneDays) return true
  const now = new Date()
  now.setHours(23, 59, 59, 999)
  return date > now
}

// ---- 水位/流量 ----
const dataList = ref([
  { label: '当前水位', value: '-', unit: 'm', color: '#409EFF' },
  { label: '库容', value: '-', unit: '亿m³', color: '#67C23A' },
  { label: '入库流量', value: '-', unit: 'm³/s', color: '#E6A23C' },
  { label: '出库流量', value: '-', unit: 'm³/s', color: '#F56C6C' },
])

const levelChartRef = ref(null)
const flowChartRef = ref(null)
let levelChart = null
let flowChart = null

// ---- 水质 ----
const waterQualityChartRef = ref(null)
let waterQualityChart = null
const waterQualityList = ref([])
const waterQualityPage = ref(1)
const pageSize = 20

const waterQualityPageData = computed(() => {
  const start = (waterQualityPage.value - 1) * pageSize
  return waterQualityList.value.slice(start, start + pageSize)
})

// ---- 工情(上海) ----
const engineeringSHList = ref([])
const engineeringSHPage = ref(1)

const engineeringSHPageData = computed(() => {
  const start = (engineeringSHPage.value - 1) * pageSize
  return engineeringSHList.value.slice(start, start + pageSize)
})

// ---- 工情(新建和完善) ----
const engineeringXJList = ref([])
const engineeringXJPage = ref(1)

const engineeringXJPageData = computed(() => {
  const start = (engineeringXJPage.value - 1) * pageSize
  return engineeringXJList.value.slice(start, start + pageSize)
})

// ---- 分页事件 ----
function onWaterQualityPageChange(page) { waterQualityPage.value = page }
function onEngineeringSHPageChange(page) { engineeringSHPage.value = page }
function onEngineeringXJPageChange(page) { engineeringXJPage.value = page }

// ---- 水质参数配置 ----
const waterQualityParams = [
  { key: 'W0', name: '水温', unit: '°C', color: '#409EFF' },
  { key: 'PH', name: 'PH值', unit: '', color: '#67C23A' },
  { key: 'DO', name: '溶解氧', unit: 'mg/L', color: '#E6A23C' },
  { key: 'CODMN', name: '高锰酸盐指数', unit: 'mg/L', color: '#F56C6C' },
  { key: 'COND', name: '电导率', unit: 'μS/cm', color: '#909399' },
  { key: 'ORP', name: '氧化还原电位', unit: 'mV', color: '#9B59B6' },
  { key: 'TURB', name: '浊度', unit: 'NTU', color: '#1ABC9C' },
  { key: 'NH3N', name: '氨氮', unit: 'mg/L', color: '#E91E63' },
  { key: 'TN', name: '总氮', unit: 'mg/L', color: '#FF9800' },
  { key: 'TP', name: '总磷', unit: 'mg/L', color: '#795548' },
  { key: 'NH4', name: '铵离子', unit: 'mg/L', color: '#607D8B' },
]

// ---- 切换数据类型 ----
function handleStationDetail() {
  if (!station.value) return
  stationDetailVisible.value = true
  stationDetailLoading.value = true
  stationDetailInfo.value = null
  stationDetailMonitor.value = []

  const selected = stations.value.find(s => (s.STCD || s.STNM) === station.value)
  if (selected) {
    stationDetailInfo.value = selected
    const rtucd = selected.STTEL || selected.STCD
    if (rtucd) {
      getRealtimeData({ rtucd, startTime: '', endTime: '' }).then(res => {
        const data = res.data || []
        stationDetailMonitor.value = Array.isArray(data) ? data : (data.table?.list || [])
        stationDetailLoading.value = false
      }).catch(() => { stationDetailLoading.value = false })
    } else {
      stationDetailLoading.value = false
    }
  } else {
    stationDetailLoading.value = false
  }
}

function onDataTypeChange() {
  waterQualityPage.value = 1
  engineeringSHPage.value = 1
  engineeringXJPage.value = 1
  nextTick(() => {
    refreshData()
  })
}

// ---- 数据加载 ----
function refreshData() {
  if (dataType.value === 'waterLevel' || dataType.value === 'flow') {
    loadLevelFlowData()
  } else if (dataType.value === 'waterQuality') {
    loadWaterQualityData()
  } else if (dataType.value === 'engineeringSH') {
    loadEngineeringData('shanghai')
  } else if (dataType.value === 'engineeringXJ') {
    loadEngineeringData('xinjian')
  }
}

function loadLevelFlowData() {
  loading.value = true
  const params = buildParams()
  getRealtimeData().then(res => {
    const items = res.data?.list || res.data || res.rows || []
    if (items.length > 0) {
      const item = items[0]
      dataList.value = [
        { label: '当前水位', value: item.W0 || '-', unit: 'm', color: '#409EFF' },
        { label: '流量', value: item.Q0 || '-', unit: 'm³/s', color: '#67C23A' },
        { label: '站点', value: item.STNM || '-', unit: '', color: '#E6A23C' },
        { label: '时间', value: item.VIEWTIME || '-', unit: '', color: '#F56C6C' },
      ]
    }
  }).catch(() => {})

  getLevelData(params).then(res => {
    const items = res.data?.list || res.data || res.rows || []
    const times = items.map(i => i.VIEWTIME ? formatDisplayTime(i.VIEWTIME) : '')
    const vals = items.map(i => i.W0 != null ? Number(i.W0) : null)
    if (times.length > 0) updateLevelChart(times, vals)
    loading.value = false
  }).catch(() => { loading.value = false })

  getFlowData(params).then(res => {
    const items = res.data?.list || res.data || res.rows || []
    const times = items.map(i => i.VIEWTIME ? formatDisplayTime(i.VIEWTIME) : '')
    const vals = items.map(i => i.Q0 != null ? Number(i.Q0) : null)
    if (times.length > 0) updateFlowChart(times, vals)
  }).catch(() => {})
}

function loadWaterQualityData() {
  loading.value = true
  const params = buildParams()
  getWaterQualityData(params).then(res => {
    const items = res.data?.list || res.data || res.rows || []
    waterQualityList.value = items
    waterQualityPage.value = 1
    loading.value = false
    nextTick(() => {
      if (items.length > 0) updateWaterQualityChart(items)
    })
  }).catch(() => { loading.value = false })
}

function loadEngineeringData(type) {
  loading.value = true
  const params = { ...buildParams(), type }
  getEngineeringData(params).then(res => {
    const items = res.data?.list || res.data || res.rows || []
    if (type === 'shanghai') {
      engineeringSHList.value = items
      engineeringSHPage.value = 1
    } else {
      engineeringXJList.value = items
      engineeringXJPage.value = 1
    }
    loading.value = false
  }).catch(() => { loading.value = false })
}

function buildParams() {
  const params = {}
  if (station.value) params.rtucd = station.value
  if (dateRange.value && dateRange.value.length === 2) {
    params.startTime = dateRange.value[0]
    params.endTime = dateRange.value[1]
  }
  return params
}

function formatDisplayTime(t) {
  if (!t) return ''
  const d = new Date(t)
  if (isNaN(d.getTime())) return t
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const h = String(d.getHours()).padStart(2, '0')
  const min = String(d.getMinutes()).padStart(2, '0')
  return `${m}-${day} ${h}:${min}`
}

// ---- 图表更新 ----
function updateLevelChart(times, data) {
  if (!levelChartRef.value) return
  if (!levelChart) {
    levelChart = echarts.init(levelChartRef.value)
  }
  levelChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    grid: { left: '3%', right: '4%', bottom: '3%', top: '10%', containLabel: true },
    xAxis: {
      type: 'category',
      data: times,
      boundaryGap: false,
      axisLabel: { rotate: 30, fontSize: 11 }
    },
    yAxis: {
      type: 'value',
      name: '水位(m)',
      splitLine: { lineStyle: { type: 'dashed' } }
    },
    dataZoom: [
      { type: 'inside', start: 0, end: 100 },
      { type: 'slider', start: 0, end: 100, height: 20, bottom: 0 }
    ],
    series: [{
      name: '水位',
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 4,
      data,
      areaStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: 'rgba(64,158,255,0.25)' },
        { offset: 1, color: 'rgba(64,158,255,0.02)' }
      ])},
      lineStyle: { color: '#409EFF', width: 2 },
      itemStyle: { color: '#409EFF' }
    }]
  })
}

function updateFlowChart(times, data) {
  if (!flowChartRef.value) return
  if (!flowChart) {
    flowChart = echarts.init(flowChartRef.value)
  }
  flowChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    grid: { left: '3%', right: '4%', bottom: '3%', top: '10%', containLabel: true },
    xAxis: {
      type: 'category',
      data: times,
      boundaryGap: false,
      axisLabel: { rotate: 30, fontSize: 11 }
    },
    yAxis: {
      type: 'value',
      name: '流量(m³/s)',
      splitLine: { lineStyle: { type: 'dashed' } }
    },
    dataZoom: [
      { type: 'inside', start: 0, end: 100 },
      { type: 'slider', start: 0, end: 100, height: 20, bottom: 0 }
    ],
    series: [{
      name: '流量',
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 4,
      data,
      areaStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: 'rgba(103,194,58,0.25)' },
        { offset: 1, color: 'rgba(103,194,58,0.02)' }
      ])},
      lineStyle: { color: '#67C23A', width: 2 },
      itemStyle: { color: '#67C23A' }
    }]
  })
}

function updateWaterQualityChart(items) {
  if (!waterQualityChartRef.value) return
  if (!waterQualityChart) {
    waterQualityChart = echarts.init(waterQualityChartRef.value)
  }

  const times = items.map(i => i.MONITORTIME ? formatDisplayTime(i.MONITORTIME) : '')
  const seriesList = waterQualityParams.map(p => ({
    name: p.name,
    type: 'line',
    smooth: true,
    symbol: 'none',
    lineStyle: { width: 1.5 },
    itemStyle: { color: p.color },
    data: items.map(i => i[p.key] != null ? Number(i[p.key]) : null),
    yAxisIndex: p.key === 'COND' || p.key === 'ORP' ? 1 : 0,
  }))

  waterQualityChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    legend: {
      data: waterQualityParams.map(p => p.name),
      type: 'scroll',
      bottom: 30,
      textStyle: { fontSize: 11 }
    },
    grid: { left: '3%', right: '5%', bottom: '15%', top: '8%', containLabel: true },
    xAxis: {
      type: 'category',
      data: times,
      boundaryGap: false,
      axisLabel: { rotate: 30, fontSize: 11 }
    },
    yAxis: [
      {
        type: 'value',
        name: '常规参数',
        splitLine: { lineStyle: { type: 'dashed' } }
      },
      {
        type: 'value',
        name: '电导率/电位',
        splitLine: { show: false }
      }
    ],
    dataZoom: [
      { type: 'inside', start: 0, end: 100 },
      { type: 'slider', start: 0, end: 100, height: 20, bottom: 55 }
    ],
    series: seriesList
  }, true)
}

// ---- 窗口resize ----
function handleResize() {
  levelChart && levelChart.resize()
  flowChart && flowChart.resize()
  waterQualityChart && waterQualityChart.resize()
}

// ---- 站点加载 ----
function loadStations() {
  getStationList().then(res => {
    stations.value = res.data || res.rows || []
  }).catch(() => {})
}

// ---- 初始化 ----
onMounted(() => {
  loadStations()
  refreshData()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (levelChart) { levelChart.dispose(); levelChart = null }
  if (flowChart) { flowChart.dispose(); flowChart = null }
  if (waterQualityChart) { waterQualityChart.dispose(); waterQualityChart = null }
})
</script>

<style scoped>
.card-header {
  font-weight: 600;
  font-size: 16px;
}
.mb-16 {
  margin-bottom: 16px;
}
.data-card {
  text-align: center;
  margin-bottom: 16px;
}
.data-label {
  font-size: 14px;
  color: #999;
}
.data-value {
  font-size: 28px;
  font-weight: 700;
  margin: 8px 0;
}
.data-unit {
  font-size: 13px;
  color: #999;
}
.pagination-wrap {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>
