<template>
  <div class="page-container">
    <div class="page-content">
      <div class="search-bar">
        <div class="search-left">
          <el-select v-model="selectedUnit" placeholder="请选择共享单位" @change="handleUnitChange" class="unit-select">
            <el-option v-for="unit in unitList" :key="unit.unitCode" :label="unit.unitName" :value="unit.unitCode" />
          </el-select>
        </div>
        <div class="search-center">
          <div class="biz-buttons">
            <el-button 
              v-for="biz in bizList" 
              :key="biz.bizCode"
              :class="{ active: selectedBiz === biz.bizCode }"
              @click="handleBizClick(biz.bizCode)"
              size="default"
            >
              {{ biz.bizName }}
              <span class="station-count">{{ biz.stationCount || 0 }}</span>
            </el-button>
          </div>
        </div>
        <div class="search-right">
          <el-input v-model="searchKeyword" placeholder="请输入站名" @keyup.enter="loadStationData" clearable style="width: 200px">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
      
      <div class="table-container">
        <el-table :data="tableData" stripe border v-loading="loading">
          <el-table-column prop="stcd" label="站码" width="100" />
          <el-table-column prop="stnm" label="站名" width="150" />
          <el-table-column prop="rvnm" label="河流名称" width="120" />
          <el-table-column prop="lttd" label="纬度" width="100" />
          <el-table-column prop="lgtd" label="经度" width="100" />
          <el-table-column prop="latestDataTime" label="最新数据时间" width="170" />
          <el-table-column prop="wt" label="水温(℃)" width="100" />
          <el-table-column prop="ph" label="pH" width="80" />
          <el-table-column prop="do" label="溶解氧(mg/L)" width="110" />
          <el-table-column prop="nh3n" label="氨氮(mg/L)" width="100" />
          <el-table-column prop="tp" label="总磷(mg/L)" width="100" />
          <el-table-column prop="tn" label="总氮(mg/L)" width="100" />
          <el-table-column prop="cod" label="COD(mg/L)" width="100" />
          <el-table-column prop="bod" label="BOD(mg/L)" width="100" />
        </el-table>
        
        <div v-if="tableData.length === 0 && !loading" class="empty-state">
          <el-icon class="empty-icon"><DataAnalysis /></el-icon>
          <p>暂无数据</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, DataAnalysis } from '@element-plus/icons-vue'
import request from '@/utils/request'

const selectedUnit = ref('TBA')
const selectedBiz = ref('TBA_SW_1H2H')
const searchKeyword = ref('')
const loading = ref(false)

const unitList = ref([])
const bizList = ref([])
const stationList = ref([])
const tableData = ref([])

onMounted(() => {
  loadUnits()
})

function loadUnits() {
  request({
    url: '/gx/unit/front/list',
    method: 'get'
  }).then(res => {
    unitList.value = res.data || []
    loadBizList(selectedUnit.value)
  })
}

function handleUnitChange(val) {
  selectedBiz.value = ''
  stationList.value = []
  tableData.value = []
  loadBizList(val)
}

function loadBizList(unitCode) {
  request({
    url: '/gx/biz/front/list',
    method: 'get',
    params: { bizUnit: unitCode }
  }).then(res => {
    const bizData = res.data || []
    
    Promise.all(bizData.map(biz => {
      return request({
        url: '/gx/station/front/listByBizCode/' + biz.bizCode,
        method: 'get'
      }).then(stationRes => {
        const stations = stationRes.data || []
        return { ...biz, stationCount: stations.length }
      })
    })).then(results => {
      bizList.value = results
      
      if (bizList.value.length > 0) {
        const defaultBiz = bizList.value.find(b => b.bizCode === selectedBiz.value)
        if (defaultBiz) {
          selectedBiz.value = defaultBiz.bizCode
        } else {
          selectedBiz.value = bizList.value[0].bizCode
        }
        handleBizClick(selectedBiz.value)
      }
    })
  })
}

function handleBizClick(bizCode) {
  selectedBiz.value = bizCode
  loadStationData()
}

function loadStationData() {
  loading.value = true
  
  request({
    url: '/gx/station/front/listByBizCode/' + selectedBiz.value,
    method: 'get'
  }).then(res => {
    stationList.value = res.data || []
    
    let filteredStations = stationList.value
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase()
      filteredStations = filteredStations.filter(s => 
        s.stnm.toLowerCase().includes(keyword) || 
        s.stcd.toLowerCase().includes(keyword)
      )
    }
    
    Promise.all(filteredStations.map(station => {
      return request({
        url: '/gx/quality/front/list',
        method: 'get',
        params: { stcd: station.stcd, pageSize: 1 }
      }).then(qualityRes => {
        const qualityData = qualityRes.data || []
        const latestQuality = qualityData.length > 0 ? qualityData[0] : {}
        return {
          ...station,
          latestDataTime: latestQuality.uploadTime || '-',
          wt: latestQuality.wt || '-',
          ph: latestQuality.ph || '-',
          do: latestQuality.do || '-',
          nh3n: latestQuality.nh3n || '-',
          tp: latestQuality.tp || '-',
          tn: latestQuality.tn || '-',
          cod: latestQuality.cod || '-',
          bod: latestQuality.bod || '-'
        }
      })
    })).then(results => {
      tableData.value = results
      loading.value = false
    }).catch(() => {
      tableData.value = filteredStations.map(station => ({
        ...station,
        latestDataTime: '-',
        wt: '-',
        ph: '-',
        do: '-',
        nh3n: '-',
        tp: '-',
        tn: '-',
        cod: '-',
        bod: '-'
      }))
      loading.value = false
    })
  }).catch(() => {
    loading.value = false
  })
}
</script>

<style scoped>
.page-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 10px 0;
}

.page-header p {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.page-content {
  flex: 1;
  background: #fff;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.search-bar {
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.search-left {
  flex-shrink: 0;
}

.unit-select {
  width: 220px;
}

.search-center {
  flex: 1;
  display: flex;
  justify-content: center;
  padding: 0 20px;
}

.biz-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: center;
}

.biz-buttons :deep(.el-button) {
  padding: 6px 16px;
  border-radius: 4px;
  font-size: 14px;
  background: #f5f7fa;
  color: #606266;
  border-color: #dcdfe6;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.biz-buttons :deep(.el-button:hover) {
  background: #ecf5ff;
  border-color: #b3d8ff;
  color: #1c97e7;
}

.biz-buttons :deep(.el-button.active) {
  background: #1c97e7;
  color: #fff;
  border-color: #1c97e7;
}

.station-count {
  font-size: 12px;
  background: rgba(255, 255, 255, 0.2);
  padding: 2px 6px;
  border-radius: 10px;
}

.biz-buttons :deep(.el-button.active) .station-count {
  background: rgba(255, 255, 255, 0.3);
}

.search-right {
  flex-shrink: 0;
}

.table-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.table-container :deep(.el-table) {
  width: 100%;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #909399;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state p {
  font-size: 16px;
  margin: 0;
}
</style>
