<template>
  <div class="pipe-network-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="设施名称">
          <el-input v-model="searchForm.networkName" placeholder="请输入设施名称" clearable />
        </el-form-item>
        <el-form-item label="管养单位">
          <el-input v-model="searchForm.managementUnit" placeholder="请输入管养单位" clearable />
        </el-form-item>
        <el-form-item label="等级">
          <el-select v-model="searchForm.networkLevel" placeholder="请选择" clearable style="width:160px">
            <el-option v-for="d in pipeNetworkLevelDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="设施类型">
          <el-select v-model="searchForm.networkType" placeholder="请选择" clearable style="width:160px">
            <el-option v-for="d in pipeNetworkTypeDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="材质">
          <el-input v-model="searchForm.material" placeholder="请输入材质" clearable style="width:160px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable style="width:160px">
            <el-option v-for="d in pipeNetworkStatusDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
          <el-button type="warning" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table :data="tableData" border stripe v-loading="loading" style="width: 100%">
        <el-table-column prop="networkCode" label="设施编码" min-width="120" />
        <el-table-column prop="networkName" label="设施名称" min-width="150" />
        <el-table-column prop="networkType" label="设施类型" width="100">
          <template #default="{ row }">{{ getDictLabel(pipeNetworkTypeDict, row.networkType) }}</template>
        </el-table-column>
        <el-table-column prop="networkLevel" label="等级" width="90">
          <template #default="{ row }">{{ getDictLabel(pipeNetworkLevelDict, row.networkLevel) }}</template>
        </el-table-column>
        <el-table-column prop="managementUnit" label="管养单位" min-width="150" />
        <el-table-column prop="material" label="材质" width="100" />
        <el-table-column prop="location" label="位置" min-width="180" />
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="row.status === '0' ? 'success' : 'danger'">{{ getDictLabel(pipeNetworkStatusDict, row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next, sizes"
        :page-sizes="[10, 20, 50]"
        @change="loadData"
        style="margin-top: 16px; justify-content: flex-end"
      />
    </el-card>

    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="650px" destroy-on-close>
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="设施编码" prop="networkCode">
          <el-input v-model="formData.networkCode" placeholder="请输入设施编码" />
        </el-form-item>
        <el-form-item label="设施名称" prop="networkName">
          <el-input v-model="formData.networkName" placeholder="请输入设施名称" />
        </el-form-item>
        <el-form-item label="设施类型">
          <el-select v-model="formData.networkType">
            <el-option v-for="d in pipeNetworkTypeDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="等级">
          <el-select v-model="formData.networkLevel">
            <el-option v-for="d in pipeNetworkLevelDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="管养单位">
          <el-input v-model="formData.managementUnit" placeholder="请输入管养单位" />
        </el-form-item>
        <el-form-item label="位置描述">
          <el-input v-model="formData.location" placeholder="请输入位置描述" />
        </el-form-item>
        <el-form-item label="材质">
          <el-input v-model="formData.material" placeholder="请输入材质" />
        </el-form-item>
        <el-form-item label="经度">
          <el-input-number v-model="formData.longitude" :precision="10" :step="0.0001" placeholder="请输入经度" style="width: 100%" />
        </el-form-item>
        <el-form-item label="纬度">
          <el-input-number v-model="formData.latitude" :precision="10" :step="0.0001" placeholder="请输入纬度" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formData.status" placeholder="请选择">
            <el-option v-for="d in pipeNetworkStatusDict" :key="d.dictValue" :label="d.dictLabel" :value="d.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPipeNetworkPage, getPipeNetworkById, addPipeNetwork, updatePipeNetwork, deletePipeNetwork } from '@/api/pipeNetwork/basic'
import { getDicts } from '@/api/system/dict/data'

const loading = ref(false)
const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

const searchForm = reactive({
  networkName: '', managementUnit: '', networkLevel: '', networkType: '', material: '', status: ''
})

const dialogVisible = ref(false)
const dialogTitle = ref('新增')
const formRef = ref(null)
const formData = reactive({
  networkId: '', networkCode: '', networkName: '', networkType: '0',
  networkLevel: '', managementUnit: '', location: '', material: '',
  longitude: null, latitude: null, status: '0', remark: ''
})

const rules = {
  networkCode: [{ required: true, message: '请输入设施编码', trigger: 'blur' }],
  networkName: [{ required: true, message: '请输入设施名称', trigger: 'blur' }]
}

const pipeNetworkStatusDict = ref([])
const pipeNetworkLevelDict = ref([])
const pipeNetworkTypeDict = ref([])

function getDictLabel(dict, value) {
  const item = dict.find(d => d.dictValue === value)
  return item ? item.dictLabel : value
}

async function loadDicts() {
  const [statusRes, levelRes, typeRes] = await Promise.all([
    getDicts('pipe_network_status'),
    getDicts('pipe_network_level'),
    getDicts('pipe_network_type')
  ])
  pipeNetworkStatusDict.value = statusRes.data
  pipeNetworkLevelDict.value = levelRes.data
  pipeNetworkTypeDict.value = typeRes.data
}

async function loadData() {
  loading.value = true
  try {
    const res = await getPipeNetworkPage(pageNum.value, pageSize.value, searchForm)
    tableData.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  pageNum.value = 1
  loadData()
}

function handleReset() {
  Object.assign(searchForm, { networkName: '', managementUnit: '', networkLevel: '', networkType: '', material: '', status: '' })
  handleSearch()
}

function handleAdd() {
  dialogTitle.value = '新增'
  Object.assign(formData, { networkId: '', networkCode: '', networkName: '', networkType: '0', networkLevel: '', managementUnit: '', location: '', material: '', longitude: null, latitude: null, status: '0', remark: '' })
  dialogVisible.value = true
}

function handleEdit(row) {
  dialogTitle.value = '编辑'
  Object.assign(formData, row)
  dialogVisible.value = true
}

async function handleSubmit() {
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return
  try {
    if (formData.networkId) {
      await updatePipeNetwork(formData)
      ElMessage.success('修改成功')
    } else {
      await addPipeNetwork(formData)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    loadData()
  } catch (e) {
    console.error(e)
  }
}

function handleDelete(row) {
  ElMessageBox.confirm('确认删除该管网信息？', '提示', { type: 'warning' }).then(async () => {
    await deletePipeNetwork(row.networkId)
    ElMessage.success('删除成功')
    loadData()
  }).catch(() => {})
}

function handleExport() {
  ElMessage.info('导出功能开发中')
}

onMounted(async () => { await loadDicts(); loadData() })
</script>

<style scoped>
.pipe-network-container { padding: 16px; }
.search-card { margin-bottom: 16px; }
.search-form { display: flex; flex-wrap: wrap; }
</style>
