<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.pustName" placeholder="请输入名称" clearable style="width: 160px" @keyup.enter="handleQuery" />
        <el-input v-model="queryParams.pustLoc" placeholder="请输入位置" clearable style="width: 160px" @keyup.enter="handleQuery" />
        <el-select v-model="queryParams.pustType" 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="pustName" label="泵站名称" min-width="180" />
      <el-table-column prop="pustLoc" label="泵站所在位置" min-width="220" />
      <el-table-column prop="insFlow" label="装机流量（m³/s）" width="150" />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="s">
          <el-button type="primary" link icon="View" @click="handleDetail(s.row)">查看</el-button>
          <el-button type="warning" link icon="Edit" @click="handleUpdate(s.row)">修改</el-button>
          <el-button type="danger" link icon="Delete" @click="handleDelete(s.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-dialog :title="form.pustName" v-model="open" width="900px" append-to-body class="gc-detail-dialog">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="泵站名称">{{ form.pustName }}</el-descriptions-item>
        <el-descriptions-item label="泵站代码">{{ form.pustCode }}</el-descriptions-item>
        <el-descriptions-item label="泵站经度">{{ form.pustLong }}</el-descriptions-item>
        <el-descriptions-item label="泵站纬度">{{ form.pustLat }}</el-descriptions-item>
        <el-descriptions-item label="泵站所在位置" :span="2">{{ form.pustLoc }}</el-descriptions-item>
        <el-descriptions-item label="泵站类型">{{ pustTypeMap[form.pustType] }}</el-descriptions-item>
        <el-descriptions-item label="装机流量">{{ form.insFlow }} m³/s</el-descriptions-item>
        <el-descriptions-item label="装机功率">{{ form.insPow }}</el-descriptions-item>
        <el-descriptions-item label="水泵数量">{{ form.pumpNum }}</el-descriptions-item>
        <el-descriptions-item label="设计扬程">{{ form.desHead }}</el-descriptions-item>
        <el-descriptions-item label="工程任务">{{ form.engTask }}</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.mainBuildGrad }}</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="归口管理部门" :span="2">{{ form.admDep }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="3">{{ 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="140px" class="gc-edit-form">
        <el-row :gutter="16">
          <el-col :span="8"><el-form-item label="泵站名称" prop="pustName"><el-input v-model="addEditForm.pustName" maxlength="50" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="泵站代码" prop="pustCode"><el-input v-model="addEditForm.pustCode" maxlength="50" :disabled="isEdit" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="泵站经度"><el-input-number v-model="addEditForm.pustLong" :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.pustLat" :precision="4" :controls="false" style="width:100%" /></el-form-item></el-col>
          <el-col :span="16"><el-form-item label="泵站所在位置"><el-input v-model="addEditForm.pustLoc" maxlength="50" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8"><el-form-item label="泵站类型"><el-select v-model="addEditForm.pustType" placeholder="请选择" style="width:100%"><el-option v-for="(v,k) in pustTypeMap" :key="k" :label="v" :value="k" /></el-select></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="装机流量"><el-input-number v-model="addEditForm.insFlow" :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.insPow" :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.pumpNum" :controls="false" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="设计扬程"><el-input-number v-model="addEditForm.desHead" :precision="2" :controls="false" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="工程任务"><el-input v-model="addEditForm.engTask" maxlength="50" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <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-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-select v-model="addEditForm.mainBuildGrad" placeholder="请选择" style="width:100%"><el-option label="1级" value="1" /><el-option label="2级" value="2" /><el-option label="3级" value="3" /><el-option label="4级" value="4" /><el-option label="5级" value="5" /></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.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/pust/importData" template-action="/slgc/pust/importTemplate" template-file-name="pust_template" @success="getList" />
  </div>
</template>

<script setup name="Pust">
import { getPustList } from '@/api/slgc/gc/index'
import { getPust, getPustCountType, addPust, updatePust, delPust, exportPust } from '@/api/slgc/pust/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, pustName: undefined, pustLoc: undefined, pustType: 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 pustTypeMap = { '1': '排水泵站', '2': '供水泵站', '3': '供排结合泵站' }
const engGradMap = { '1': 'Ⅰ等', '2': 'Ⅱ等', '3': 'Ⅲ等', '4': 'Ⅳ等', '5': 'Ⅴ等' }
const engStatMap = { '1': '已建', '2': '在建', '3': '规划' }
const addEditRules = {
  pustName: [{ required: true, message: '请输入泵站名称', trigger: 'blur' }],
  pustCode: [{ required: true, message: '请输入泵站代码', trigger: 'blur' }]
}

function getList() {
  loading.value = true
  getPustList(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.pustCode)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}
function handleDetail(row) { getPust(row.pustCode).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 = '修改泵站信息'
  getPust(row.pustCode || ids.value[0]).then(res => { addEditForm.value = res.data; addEditOpen.value = true })
}
function submitForm() {
  addEditFormRef.value.validate(valid => {
    if (!valid) return
    const fn = isEdit.value ? updatePust : addPust
    fn(addEditForm.value).then(() => { proxy.$modal.msgSuccess(isEdit.value ? '修改成功' : '新增成功'); addEditOpen.value = false; getList() })
  })
}
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除该条泵站数据？').then(() => {
    return delPust(row.pustCode)
  }).then(() => { getList(); proxy.$modal.msgSuccess('删除成功') }).catch(() => {})
}
function handleBatchDelete() {
  if (!ids.value.length) return
  proxy.$modal.confirm('是否确认删除选中的 ' + ids.value.length + ' 条泵站数据？').then(() => {
    return delPust(ids.value.join(','))
  }).then(() => { getList(); proxy.$modal.msgSuccess('删除成功') }).catch(() => {})
}
function handleExport() {
  exportPust(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
  getPustCountType().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, .gc-toolbar-right { display: flex; align-items: center; gap: 8px; }
.gc-pagination { margin-top: auto; padding-top: 16px; display: flex; justify-content: flex-end; }
: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>
