<template>
  <div class="gc-page">
    <!-- 顶部工具栏 -->
    <div class="gc-toolbar">
      <div class="gc-toolbar-left">
        <el-button type="success" icon="DataAnalysis" @click="handleStats">统计</el-button>
        <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
        <el-button type="warning" icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
        <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleBatchDelete">删除</el-button>
        <el-button type="info" icon="Upload" @click="importRef.open()">导入</el-button>
        <el-button type="success" icon="Download" @click="handleExport">导出</el-button>
      </div>
      <div class="gc-toolbar-right">
        <el-input v-model="queryParams.resName" placeholder="水库名称" clearable style="width: 160px" @keyup.enter="handleQuery" />
        <el-input v-model="queryParams.resLoc" placeholder="水库所在位置" clearable style="width: 160px" @keyup.enter="handleQuery" />
        <el-select v-model="queryParams.resType" placeholder="请选择类别-" clearable style="width: 140px">
          <el-option label="山丘水库" value="1" />
          <el-option label="平原水库" value="2" />
          <el-option label="地下水库" value="3" />
        </el-select>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="list" stripe border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="resName" label="水库名称" min-width="160" />
      <el-table-column prop="resLoc" label="水库所在位置" min-width="200" />
      <el-table-column prop="resType" label="水库类型" width="120">
        <template #default="scope">{{ resTypeMap[scope.row.resType] || scope.row.resType }}</template>
      </el-table-column>
      <el-table-column prop="engGrad" label="工程等别" width="100">
        <template #default="scope">{{ engGradMap[scope.row.engGrad] || scope.row.engGrad }}</template>
      </el-table-column>
      <el-table-column prop="totCap" label="总库容（10⁴m³）" width="140" />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <el-button type="primary" link icon="View" @click="handleDetail(scope.row)">查看</el-button>
          <el-button type="warning" link icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="danger" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="gc-pagination">
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </div>

    <!-- 查看详情弹窗 — el-descriptions 风格 -->
    <el-dialog :title="form.resName" v-model="open" width="900px" append-to-body class="gc-detail-dialog">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="水库名称">{{ form.resName }}</el-descriptions-item>
        <el-descriptions-item label="水库代码">{{ form.resCode }}</el-descriptions-item>
        <el-descriptions-item label="左下角经度">{{ form.lowLeftLong }}</el-descriptions-item>
        <el-descriptions-item label="左下角纬度">{{ form.lowLeftLat }}</el-descriptions-item>
        <el-descriptions-item label="右上角经度">{{ form.upRightLong }}</el-descriptions-item>
        <el-descriptions-item label="右上角纬度">{{ form.upRightLat }}</el-descriptions-item>
        <el-descriptions-item label="水库所在位置" :span="2">{{ form.resLoc }}</el-descriptions-item>
        <el-descriptions-item label="水库类型">{{ resTypeMap[form.resType] }}</el-descriptions-item>
        <el-descriptions-item label="工程等别">{{ engGradMap[form.engGrad] }}</el-descriptions-item>
        <el-descriptions-item label="工程规模">{{ form.engScal }}</el-descriptions-item>
        <el-descriptions-item label="坝址控制流域面积">{{ form.watShedArea }} km²</el-descriptions-item>
        <el-descriptions-item label="坝址多年平均径流量">{{ form.daadMulAverRuof }}</el-descriptions-item>
        <el-descriptions-item label="防洪高水位">{{ form.uppLevFlco }}</el-descriptions-item>
        <el-descriptions-item label="正常蓄水位">{{ form.normWatLev }} m</el-descriptions-item>
        <el-descriptions-item label="正常蓄水位相应水面面积">{{ form.normPoolStagArea }}</el-descriptions-item>
        <el-descriptions-item label="正常蓄水位相应库容">{{ form.normPoolStagCap }}</el-descriptions-item>
        <el-descriptions-item label="主汛期防洪限制水位">{{ form.flLowLimLev }}</el-descriptions-item>
        <el-descriptions-item label="防洪限制水位库容">{{ form.flLowLimLevCap }}</el-descriptions-item>
        <el-descriptions-item label="死水位">{{ form.deadLev }} m</el-descriptions-item>
        <el-descriptions-item label="总库容">{{ form.totCap }} 10⁴m³</el-descriptions-item>
        <el-descriptions-item label="调洪库容">{{ form.storFlCap }} 10⁴m³</el-descriptions-item>
        <el-descriptions-item label="防洪库容">{{ form.flcoCap }} 10⁴m³</el-descriptions-item>
        <el-descriptions-item label="兴利库容">{{ form.benResCap }} 10⁴m³</el-descriptions-item>
        <el-descriptions-item label="死库容">{{ form.deadCap }} 10⁴m³</el-descriptions-item>
        <el-descriptions-item label="工程建设情况">{{ engStatMap[form.engStat] }}</el-descriptions-item>
        <el-descriptions-item label="开工时间">{{ form.startDate }}</el-descriptions-item>
        <el-descriptions-item label="建成时间">{{ form.compDate }}</el-descriptions-item>
        <el-descriptions-item label="归口管理部门">{{ form.admDep }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ form.note }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="addEditOpen" width="900px" append-to-body>
      <el-form ref="addEditFormRef" :model="addEditForm" :rules="addEditRules" label-width="150px" class="gc-edit-form">
        <el-row :gutter="16">
          <el-col :span="8"><el-form-item label="水库名称" prop="resName"><el-input v-model="addEditForm.resName" maxlength="50" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="水库代码" prop="resCode"><el-input v-model="addEditForm.resCode" maxlength="50" :disabled="isEdit" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="左下角经度"><el-input-number v-model="addEditForm.lowLeftLong" :precision="4" :controls="false" style="width:100%" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8"><el-form-item label="左下角纬度"><el-input-number v-model="addEditForm.lowLeftLat" :precision="4" :controls="false" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="右上角经度"><el-input-number v-model="addEditForm.upRightLong" :precision="4" :controls="false" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="右上角纬度"><el-input-number v-model="addEditForm.upRightLat" :precision="4" :controls="false" style="width:100%" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8"><el-form-item label="水库所在位置"><el-input v-model="addEditForm.resLoc" maxlength="50" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="水库类型"><el-select v-model="addEditForm.resType" placeholder="请选择" style="width:100%"><el-option v-for="(v,k) in resTypeMap" :key="k" :label="v" :value="k" /></el-select></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="工程等别"><el-select v-model="addEditForm.engGrad" placeholder="请选择" style="width:100%"><el-option v-for="(v,k) in engGradMap" :key="k" :label="v" :value="k" /></el-select></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8"><el-form-item label="工程规模"><el-select v-model="addEditForm.engScal" placeholder="请选择" style="width:100%"><el-option label="大（1）型" value="1" /><el-option label="大（2）型" value="2" /><el-option label="中型" value="3" /><el-option label="小（1）型" value="4" /><el-option label="小（2）型" value="5" /></el-select></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="坝址控制流域面积"><el-input-number v-model="addEditForm.watShedArea" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="坝址多年平均径流量"><el-input-number v-model="addEditForm.daadMulAverRuof" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8"><el-form-item label="防洪高水位"><el-input-number v-model="addEditForm.uppLevFlco" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="正常蓄水位"><el-input-number v-model="addEditForm.normWatLev" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="正常蓄水位相应水面面积"><el-input-number v-model="addEditForm.normPoolStagArea" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8"><el-form-item label="正常蓄水位相应库容"><el-input-number v-model="addEditForm.normPoolStagCap" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="主汛期防洪限制水位"><el-input-number v-model="addEditForm.flLowLimLev" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="防洪限制水位库容"><el-input-number v-model="addEditForm.flLowLimLevCap" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8"><el-form-item label="死水位"><el-input-number v-model="addEditForm.deadLev" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="总库容"><el-input-number v-model="addEditForm.totCap" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="调洪库容"><el-input-number v-model="addEditForm.storFlCap" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8"><el-form-item label="防洪库容"><el-input-number v-model="addEditForm.flcoCap" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="兴利库容"><el-input-number v-model="addEditForm.benResCap" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="死库容"><el-input-number v-model="addEditForm.deadCap" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8"><el-form-item label="工程建设情况"><el-select v-model="addEditForm.engStat" placeholder="请选择" style="width:100%"><el-option v-for="(v,k) in engStatMap" :key="k" :label="v" :value="k" /></el-select></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="开工时间"><el-date-picker v-model="addEditForm.startDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="建成时间"><el-date-picker v-model="addEditForm.compDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择" style="width:100%" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8"><el-form-item label="归口管理部门"><el-input v-model="addEditForm.admDep" maxlength="50" /></el-form-item></el-col>
          <el-col :span="16"><el-form-item label="备注"><el-input v-model="addEditForm.note" maxlength="200" type="textarea" :rows="2" /></el-form-item></el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="addEditOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 统计弹窗 -->
    <el-dialog title="统计类别" v-model="statsVisible" width="500px" append-to-body>
      <el-table :data="statsData" stripe v-loading="statsLoading">
        <el-table-column prop="name" label="类别" min-width="120"><template #default="s">{{ s.row.NAME || s.row.name }}</template></el-table-column>
        <el-table-column prop="value" label="数量" width="120"><template #default="s">{{ s.row.VALUE ?? s.row.value }}</template></el-table-column>
      </el-table>
    </el-dialog>

    <!-- 导入弹窗 -->
    <excel-import-dialog ref="importRef" title="水库信息导入" action="/slgc/reservoir/importData" template-action="/slgc/reservoir/importTemplate" template-file-name="reservoir_template" @success="getList" />
  </div>
</template>

<script setup name="Reservoir">
import { getReservoirList } from '@/api/slgc/gc/index'
import { getReservoir, getReservoirCountType, addReservoir, updateReservoir, delReservoir, exportReservoir } from '@/api/slgc/reservoir/index'
import ExcelImportDialog from '@/components/ExcelImportDialog/index.vue'

const { proxy } = getCurrentInstance()
const loading = ref(true)
const total = ref(0)
const open = ref(false)
const addEditOpen = ref(false)
const list = ref([])
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const queryParams = reactive({ pageNum: 1, pageSize: 10, resName: undefined, resLoc: undefined, resType: undefined })
const form = ref({})
const addEditForm = ref({})
const addEditFormRef = ref(null)
const importRef = ref(null)
const isEdit = ref(false)
const dialogTitle = ref('')
const statsVisible = ref(false)
const statsLoading = ref(false)
const statsData = ref([])
const resTypeMap = { '1': '山丘水库', '2': '平原水库', '3': '地下水库' }
const engGradMap = { '1': 'Ⅰ等', '2': 'Ⅱ等', '3': 'Ⅲ等', '4': 'Ⅳ等', '5': 'Ⅴ等' }
const engStatMap = { '1': '已建', '2': '在建', '3': '规划' }
const addEditRules = {
  resName: [{ required: true, message: '请输入水库名称', trigger: 'blur' }],
  resCode: [{ required: true, message: '请输入水库代码', trigger: 'blur' }]
}

function getList() {
  loading.value = true
  getReservoirList(queryParams).then(res => {
    list.value = res.rows; total.value = res.total; loading.value = false
  })
}
function handleQuery() { queryParams.pageNum = 1; getList() }
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.resCode)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}
function handleDetail(row) {
  getReservoir(row.resCode).then(res => { form.value = res.data; open.value = true })
}
function handleAdd() {
  isEdit.value = false
  dialogTitle.value = '新增水库信息'
  addEditForm.value = {}
  addEditOpen.value = true
}
function handleUpdate(row) {
  isEdit.value = true
  dialogTitle.value = '修改水库信息'
  const resCode = row.resCode || ids.value[0]
  getReservoir(resCode).then(res => { addEditForm.value = res.data; addEditOpen.value = true })
}
function submitForm() {
  addEditFormRef.value.validate(valid => {
    if (!valid) return
    if (isEdit.value) {
      updateReservoir(addEditForm.value).then(() => { proxy.$modal.msgSuccess('修改成功'); addEditOpen.value = false; getList() })
    } else {
      addReservoir(addEditForm.value).then(() => { proxy.$modal.msgSuccess('新增成功'); addEditOpen.value = false; getList() })
    }
  })
}
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除该条水库数据？').then(() => {
    return delReservoir(row.resCode)
  }).then(() => { getList(); proxy.$modal.msgSuccess('删除成功') }).catch(() => {})
}
function handleBatchDelete() {
  if (!ids.value.length) return
  proxy.$modal.confirm('是否确认删除选中的 ' + ids.value.length + ' 条水库数据？').then(() => {
    return delReservoir(ids.value.join(','))
  }).then(() => { getList(); proxy.$modal.msgSuccess('删除成功') }).catch(() => {})
}
function handleExport() {
  exportReservoir(queryParams).then(res => {
    const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '水库信息数据.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
  })
}
function handleStats() {
  statsVisible.value = true
  statsLoading.value = true
  getReservoirCountType().then(res => {
    statsData.value = res.data || []
    statsLoading.value = false
  }).catch(() => { statsLoading.value = false })
}

onMounted(() => { getList() })
</script>

<style scoped>
.gc-page {
  padding: 16px;
  background: #fff;
  min-height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
}
.gc-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 8px;
}
.gc-toolbar-left {
  display: flex;
  align-items: center;
  gap: 8px;
}
.gc-toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}
.gc-pagination {
  margin-top: auto;
  padding-top: 16px;
  display: flex;
  justify-content: flex-end;
}
/* 详情弹窗：el-descriptions 标签加粗、居中 */
:deep(.gc-detail-dialog .el-descriptions__label) {
  font-weight: 500;
  color: #303133;
  background-color: #f5f7fa;
}
:deep(.gc-detail-dialog .el-descriptions__content) {
  color: #606266;
}
/* 编辑弹窗：更紧凑 */
.gc-edit-form :deep(.el-form-item) {
  margin-bottom: 18px;
}
</style>
