<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <el-space>
            <el-button text @click="$router.back()">
              <el-icon><ArrowLeft /></el-icon> 返回
            </el-button>
            <span>工程监管详情</span>
          </el-space>
          <el-space>
            <el-button type="primary" size="small" @click="goVideo">
              <el-icon><VideoCamera /></el-icon> 视频监控
            </el-button>
            <el-button type="primary" size="small" @click="goFile">
              <el-icon><Folder /></el-icon> 工程附件
            </el-button>
          </el-space>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 工程信息 Tab -->
        <el-tab-pane label="工程信息" name="info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="工程名称">{{ detail.name }}</el-descriptions-item>
            <el-descriptions-item label="工程类型">{{ detail.type }}</el-descriptions-item>
            <el-descriptions-item label="施工单位">{{ detail.contractor }}</el-descriptions-item>
            <el-descriptions-item label="开工日期">{{ detail.startDate }}</el-descriptions-item>
            <el-descriptions-item label="竣工日期">{{ detail.endDate }}</el-descriptions-item>
            <el-descriptions-item label="当前进度">
              <el-progress :percentage="parseInt(detail.progress)" />
            </el-descriptions-item>
            <el-descriptions-item label="工程状态" :span="2">
              <el-tag :type="detail.status === '已完工' ? 'success' : 'warning'">{{ detail.status }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="工程概况" :span="2">{{ detail.overview }}</el-descriptions-item>

            <!-- 水闸专项参数 -->
            <template v-if="detail.holeCount">
              <el-descriptions-item label="闸孔数">{{ detail.holeCount }}</el-descriptions-item>
              <el-descriptions-item label="闸孔高(m)">{{ detail.holeHeight }}</el-descriptions-item>
              <el-descriptions-item label="设计水位(m)">{{ detail.designLevel }}</el-descriptions-item>
              <el-descriptions-item label="设计流量(m³/s)">{{ detail.designFlow }}</el-descriptions-item>
            </template>
          </el-descriptions>
        </el-tab-pane>

        <!-- 实时监测 Tab -->
        <el-tab-pane label="实时监测" name="monitor">
          <div class="monitor-toolbar">
            <el-button type="primary" :loading="weeklyLoading" @click="fetchWeeklyData">
              <el-icon><Calendar /></el-icon> 一周历史数据
            </el-button>
            <span v-if="weeklyRange" class="monitor-range">查询范围：{{ weeklyRange }}</span>
          </div>

          <el-table :data="monitorData" stripe v-loading="monitorLoading">
            <el-table-column prop="stnm" label="站名" width="120" />
            <el-table-column prop="tm" label="时间" width="180" />
            <el-table-column prop="z" label="水位(m)" width="100" />
            <el-table-column prop="q" label="流量(m³/s)" width="120" />
            <el-table-column prop="w" label="含沙量" width="100" />
            <el-table-column v-if="weeklyMode" prop="yrDiv" label="年累计引水量" width="130" />
            <el-table-column v-if="weeklyMode" prop="yrDrn" label="年累计排水量" width="130" />
          </el-table>

          <!-- 调度令 -->
          <div class="dispatch-section" v-if="dispatchOrder">
            <el-divider content-position="left">当前调度令</el-divider>
            <el-descriptions :column="2" border size="small">
              <el-descriptions-item label="调度令编号">{{ dispatchOrder.code }}</el-descriptions-item>
              <el-descriptions-item label="发布单位">{{ dispatchOrder.org }}</el-descriptions-item>
              <el-descriptions-item label="发布时间">{{ dispatchOrder.time }}</el-descriptions-item>
              <el-descriptions-item label="有效期">{{ dispatchOrder.validPeriod }}</el-descriptions-item>
              <el-descriptions-item label="调度内容" :span="2">{{ dispatchOrder.content }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>

        <!-- 工程照片 Tab -->
        <el-tab-pane label="工程照片" name="photos">
          <el-row :gutter="20">
            <el-col :span="8" v-for="station in stationPhotos" :key="station.key">
              <el-card shadow="hover" class="photo-card">
                <el-image
                  :src="station.src"
                  :preview-src-list="[station.src]"
                  fit="cover"
                  class="station-photo"
                >
                  <template #error>
                    <div class="photo-placeholder">
                      <el-icon :size="40"><Picture /></el-icon>
                      <span>{{ station.name }}</span>
                    </div>
                  </template>
                </el-image>
                <div class="station-info">
                  <h4>{{ station.name }}</h4>
                  <p>{{ station.desc }}</p>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>

        <!-- 闸门运行记录 Tab -->
        <el-tab-pane label="闸门运行记录" name="gate">
          <div style="padding:8px 0">
            <el-alert title="闸门运行记录数据来自外部系统" type="warning" :closable="false" show-icon style="margin-bottom:12px" />
            <iframe :src="gateRecordUrl" width="100%" height="600px" style="border:1px solid #dcdfe6;border-radius:4px"></iframe>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup name="ZggcDetail">
import { ArrowLeft, VideoCamera, Folder, Calendar, Picture } from '@element-plus/icons-vue'
import { getProjectDetail, getWeeklyData } from '@/api/slgc/zggc/index'

const route = useRoute()
const router = useRouter()

const activeTab = ref('info')
const detail = ref({})
const monitorData = ref([])
const monitorLoading = ref(false)
const weeklyLoading = ref(false)
const weeklyMode = ref(false)
const weeklyRange = ref('')
const dispatchOrder = ref(null)

const gateRecordUrl = computed(() => {
  const name = (detail.value?.name || '').toLowerCase()
  const base = 'http://10.8.4.136:83/GongCheng/'
  if (name.includes('太浦')) return base + 'ZhaM_JKong_tpz.aspx'
  if (name.includes('望亭')) return base + 'ZhaM_JKong_wt.aspx'
  return base + 'ZhaM_JKong.aspx'
})

const stationPhotos = ref([
  {
    key: 'tpz',
    name: '太浦闸',
    src: '/profile/station/tpz.jpg',
    desc: '太浦闸位于江苏省苏州市吴江区，是太浦河控制工程的主体建筑物，承担防洪、排涝和水资源调度等功能。闸门总净宽120米，共30孔，是太湖流域重要的水利枢纽工程。'
  },
  {
    key: 'wt',
    name: '望亭枢纽',
    src: '/profile/station/wt.jpg',
    desc: '望亭枢纽位于江苏省苏州市相城区望亭镇，是望虞河入太湖口的控制性工程，具有防洪、排涝、引水、通航等综合功能，是太湖流域综合治理的关键节点。'
  },
  {
    key: 'cs',
    name: '常熟水利枢纽',
    src: '/profile/station/cs.jpg',
    desc: '常熟水利枢纽位于江苏省苏州市常熟市，是望虞河沿线重要的水利控制工程，主要承担区域防洪、排涝及水资源调配任务，为太湖水环境综合治理提供有力支撑。'
  }
])

function goVideo() {
  router.push({ path: '/slgc/zggc/video', query: { id: detail.value.id, name: detail.value.name } })
}

function goFile() {
  router.push({ path: '/slgc/zggc/file', query: { stcd: detail.value.id || '0' } })
}

function loadMonitor() {
  monitorLoading.value = true
  weeklyMode.value = false
  weeklyRange.value = ''
  getProjectDetail({ date: new Date().toISOString().slice(0, 10) }).then(r => {
    monitorData.value = r.rows || r.data || []
    dispatchOrder.value = r.dispatchOrder || null
    monitorLoading.value = false
  }).catch(() => { monitorLoading.value = false })
}

function fetchWeeklyData() {
  const end = new Date()
  const start = new Date()
  start.setDate(end.getDate() - 7)
  const fmt = d => d.toISOString().slice(0, 10)
  const params = { stcd: detail.value.id, startDate: fmt(start), endDate: fmt(end) }

  weeklyLoading.value = true
  getWeeklyData(params).then(r => {
    monitorData.value = r.rows || r.data || []
    weeklyMode.value = true
    weeklyRange.value = `${fmt(start)} ~ ${fmt(end)}`
    monitorLoading.value = false
    weeklyLoading.value = false
  }).catch(() => {
    monitorLoading.value = false
    weeklyLoading.value = false
  })
}

onMounted(() => {
  const query = route.query
  detail.value = {
    id: query.id || 1, name: query.name || 'XX水库除险加固工程', type: query.type || '水库',
    contractor: 'XX建设公司', startDate: '2026-01-15', endDate: '2026-12-30',
    progress: query.progress || '65%', status: query.status || '施工中',
    overview: '该工程是重点水利建设项目，建成后将有效提升区域防洪能力和水资源配置能力。'
  }
  loadMonitor()
})
</script>

<style scoped>
.card-header {
  font-weight: 600;
  font-size: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.monitor-toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.monitor-range {
  color: #909399;
  font-size: 13px;
}

.dispatch-section {
  margin-top: 20px;
}

.photo-card {
  margin-bottom: 20px;
}

.station-photo {
  width: 100%;
  height: 220px;
  display: block;
  border-radius: 4px;
  overflow: hidden;
}

.photo-placeholder {
  width: 100%;
  height: 220px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #c0c4cc;
  gap: 8px;
}

.station-info h4 {
  margin: 12px 0 4px;
  font-size: 15px;
  color: #303133;
}

.station-info p {
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
  margin: 0;
}
</style>
