<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.wagaName" placeholder="请输入名称" clearable style="width: 160px" @keyup.enter="handleQuery" />
        <el-input v-model="queryParams.wagaLoc" placeholder="请输入位置" clearable style="width: 160px" @keyup.enter="handleQuery" />
        <el-select v-model="queryParams.wagaType" placeholder="请选择" clearable style="width: 140px">
          <el-option label="分（泄）洪闸" value="1" /><el-option label="节制闸" value="2" /><el-option label="排（退）水闸" value="3" /><el-option label="引（进）水闸" value="4" /><el-option label="挡潮闸" value="5" /><el-option label="船闸" value="6" /><el-option label="其他" value="9" />
        </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="wagaName" label="水闸名称" min-width="180" />
      <el-table-column prop="wagaLoc" label="水闸所在位置" min-width="220" />
      <el-table-column prop="engGrad" label="工程等别" width="120">
        <template #default="s">{{ engGradMap[s.row.engGrad] || s.row.engGrad }}</template>
      </el-table-column>
      <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.wagaName" v-model="open" width="900px" append-to-body class="gc-detail-dialog">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="水闸名称">{{ form.wagaName }}</el-descriptions-item>
        <el-descriptions-item label="水闸代码">{{ form.wagaCode }}</el-descriptions-item>
        <el-descriptions-item label="起点经度">{{ form.startLong }}</el-descriptions-item>
        <el-descriptions-item label="起点纬度">{{ form.startLat }}</el-descriptions-item>
        <el-descriptions-item label="终点经度">{{ form.endLong }}</el-descriptions-item>
        <el-descriptions-item label="终点纬度">{{ form.endLat }}</el-descriptions-item>
        <el-descriptions-item label="水闸所在位置" :span="2">{{ form.wagaLoc }}</el-descriptions-item>
        <el-descriptions-item label="水闸类型">{{ wagaTypeMap[form.wagaType] }}</el-descriptions-item>
        <el-descriptions-item label="水闸用途">{{ form.wagaUse }}</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.lockDisc }}</el-descriptions-item>
        <el-descriptions-item label="闸孔数量">{{ form.gaorNum }}</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="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="wagaName"><el-input v-model="addEditForm.wagaName" maxlength="50" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="水闸代码" prop="wagaCode"><el-input v-model="addEditForm.wagaCode" maxlength="50" :disabled="isEdit" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="起点经度"><el-input-number v-model="addEditForm.startLong" :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.startLat" :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.endLong" :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.endLat" :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.wagaLoc" maxlength="50" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="水闸类型"><el-select v-model="addEditForm.wagaType" placeholder="请选择" style="width:100%"><el-option v-for="(v,k) in wagaTypeMap" :key="k" :label="v" :value="k" /></el-select></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="水闸用途"><el-input v-model="addEditForm.wagaUse" 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-input-number v-model="addEditForm.lockDisc" :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.gaorNum" :controls="false" style="width:100%" /></el-form-item></el-col>
          <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-row>
        <el-row :gutter="16">
          <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-col :span="8"><el-form-item label="归口管理部门"><el-input v-model="addEditForm.admDep" maxlength="50" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="备注"><el-input v-model="addEditForm.note" maxlength="50" /></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/waga/importData" template-action="/slgc/waga/importTemplate" template-file-name="waga_template" @success="getList" />
  </div>
</template>

<script setup name="Waga">
import { getWagaList } from '@/api/slgc/gc/index'
import { getWaga, getWagaCountType, addWaga, updateWaga, delWaga, exportWaga } from '@/api/slgc/waga/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, wagaName: undefined, wagaLoc: undefined, wagaType: 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 wagaTypeMap = { '1': '分（泄）洪闸', '2': '节制闸', '3': '排（退）水闸', '4': '引（进）水闸', '5': '挡潮闸', '6': '船闸', '9': '其他' }
const engGradMap = { '1': 'Ⅰ等', '2': 'Ⅱ等', '3': 'Ⅲ等', '4': 'Ⅳ等', '5': 'Ⅴ等' }
const engStatMap = { '1': '已建', '2': '在建', '3': '规划' }
const addEditRules = {
  wagaName: [{ required: true, message: '请输入水闸名称', trigger: 'blur' }],
  wagaCode: [{ required: true, message: '请输入水闸代码', trigger: 'blur' }]
}

function getList() {
  loading.value = true
  getWagaList(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.wagaCode)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}
function handleDetail(row) { getWaga(row.wagaCode).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 = '修改水闸信息'
  getWaga(row.wagaCode || 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 ? updateWaga : addWaga
    fn(addEditForm.value).then(() => { proxy.$modal.msgSuccess(isEdit.value ? '修改成功' : '新增成功'); addEditOpen.value = false; getList() })
  })
}
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除该条水闸数据？').then(() => {
    return delWaga(row.wagaCode)
  }).then(() => { getList(); proxy.$modal.msgSuccess('删除成功') }).catch(() => {})
}
function handleBatchDelete() {
  if (!ids.value.length) return
  proxy.$modal.confirm('是否确认删除选中的 ' + ids.value.length + ' 条水闸数据？').then(() => {
    return delWaga(ids.value.join(','))
  }).then(() => { getList(); proxy.$modal.msgSuccess('删除成功') }).catch(() => {})
}
function handleExport() {
  exportWaga(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
  getWagaCountType().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>
